diff options
Diffstat (limited to 'web/src/lib/game/line/lineParser.ts')
| -rw-r--r-- | web/src/lib/game/line/lineParser.ts | 389 |
1 files changed, 389 insertions, 0 deletions
diff --git a/web/src/lib/game/line/lineParser.ts b/web/src/lib/game/line/lineParser.ts new file mode 100644 index 0000000..ecd694f --- /dev/null +++ b/web/src/lib/game/line/lineParser.ts @@ -0,0 +1,389 @@ +/** + * The ability-line parser (client port of the reference + * `LineBuilder.createLines`, PORTING.md §8b). Takes the (already in-game + * translated) ability lines and produces the structured {@link ColumnNode} + * tree the Svelte renderer walks. It runs the reference's pipeline in order — + * expand embedded newlines → Frosthaven conversion (sub-line / conditional + * markers) → per-line monster-stat application → layout — mirroring the + * reference's container directives (`[c]`/`[r]`/`[s]`), the `!` + * right-part-of-last-line attach, the gray sub-line boxes, the dotted + * conditional boxes, element images and dividers. + * + * The tree is theme-free: the renderer decides font sizes, colors and which + * image assets to load (the `_fh` suffix, `_black` variants, dividers, …). + */ + +import { + applyMonsterStats, + type StatMonster +} from './statApplier'; +import { + convertLinesToFH, + expandEmbeddedNewlines, + shouldOverflow +} from './frosthavenConverter'; +import { TOKENS, hasGHVersion, isElement } from './tokens'; +import type { + Align, + ColumnNode, + ConditionalNode, + LineBuildOptions, + LineStyle, + Node, + RowNode, + SubLineNode +} from './types'; + +// --- Whole-tree text / image helpers (the reference's getAllTextInWidget / +// getAllImagesInWidget) ------------------------------------------------- + +function allText(node: Node): string { + switch (node.kind) { + case 'text': + return node.text; + // The element-use colon is a separate text segment; the element icon + // itself carries no text (matches the reference's getAllTextInWidget). + case 'elementUse': + case 'token': + return ''; + case 'row': + case 'rowgroup': + case 'column': + case 'subline': + case 'conditional': + return node.children.reduce((acc, c) => acc + allText(c), ''); + default: + return ''; + } +} + +function allImages(node: Node): string[] { + switch (node.kind) { + case 'token': + return [node.gfx]; + case 'elementUse': + return [node.element, 'use']; + case 'image': + return [node.gfx]; + case 'divider': + return ['divider']; + case 'row': + case 'rowgroup': + case 'column': + case 'subline': + case 'conditional': + return node.children.flatMap(allImages); + default: + return []; + } +} + +/** A fresh empty row. */ +function newRow(align: Align, children: Node[] = []): RowNode { + return { kind: 'row', align, children }; +} + +export function parseLines(lines: string[], opts: LineBuildOptions): ColumnNode { + const { + left, + applyStats, + applyAll, + align, + frosthavenStyle, + monster, + flying = false, + bossStatCard = false, + translate = (s) => s + } = opts; + + const rowMainAlign: Align = + align === 'left' ? 'left' : align === 'right' ? 'right' : 'center'; + + let strings = expandEmbeddedNewlines([...lines]); + if (frosthavenStyle) { + strings = convertLinesToFH(strings, applyStats); + } else { + strings = strings.filter((s) => s !== '[newLine]' && s !== '[subLineEnd]'); + } + + // Containers (the reference's specialized-layout stacks). + const top: Node[] = []; + const inColumn: Node[] = []; + const inRow: Node[] = []; + const inInnerRow: Node[] = []; + let isInColumn = false; + let isInRow = false; + let isColumnInRow = false; + let hasInnerRow = false; + + /** The container a freshly built row / image / divider is added to. */ + function target(): Node[] { + if (hasInnerRow) return inInnerRow; + if (isInColumn && (!isInRow || isColumnInRow)) return inColumn; + if (isInRow && !isInColumn) return inRow; + return top; + } + + /** The most recent row, for `!` attach + sub-line background building. */ + let lastRow: RowNode | null = null; + + // The reference's buildFHStyleBackgrounds: split the last row at the + // `[subLineStart]` marker, grouping the following segments into sub-line + // rows on `[lineBreak]`. + function buildSubLineBackgrounds() { + if (!lastRow) return; + const parts = lastRow.children; + let startIdx = -1; + for (let i = 0; i < parts.length; i++) { + const p = parts[i]; + if (p.kind === 'text' && p.text.includes('[subLineStart]')) { + startIdx = i; + break; + } + } + if (startIdx < 0) return; + + const mainParts = parts.slice(0, startIdx); + const groups: Node[][] = []; + let current: Node[] = []; + for (let j = startIdx + 1; j < parts.length; j++) { + const p = parts[j]; + if (p.kind === 'text' && p.text.includes('[lineBreak]')) { + groups.push(current); + current = []; + } else { + current.push(p); + } + } + groups.push(current); + + const subLine: SubLineNode = { + kind: 'subline', + boss: bossStatCard, + conditional: false, + children: groups.map((g) => newRow(rowMainAlign, g)) + }; + lastRow.children = [newRow(rowMainAlign, mainParts), subLine]; + } + + for (let i = 0; i < strings.length; i++) { + let line = strings[i]; + let sizeToken = ''; + let isRightPart = false; + let styleToUse: LineStyle = 'normal'; + const textParts: Node[] = []; + + // Sub-line background (the gray box) — closes the open sub-line. + if (line.includes('[subLineEnd]')) { + buildSubLineBackgrounds(); + continue; + } + + // Layout directives. + if (line === '[c]') { + isInColumn = true; + if (isInRow) isColumnInRow = true; + continue; + } + if (line === '[/c]') { + isInColumn = false; + const column: ColumnNode = { kind: 'column', align, children: [...inColumn] }; + inColumn.length = 0; + if (isColumnInRow) inRow.push(column); + else top.push(column); + continue; + } + if (line === '[r]') { + isInRow = true; + continue; + } + if (line === '[s]') { + hasInnerRow = true; + continue; + } + if (line === '[/s]' || line === '[/r]') { + const isInner = line === '[/s]'; + if (isInner) hasInnerRow = false; + else isInRow = false; + + const src = isInner ? inInnerRow : inRow; + const texts = src.map(allText).join(''); + const elementUse = texts.includes(' :'); + const conditional = elementUse; + const columnHack = + texts.lastIndexOf(' :') !== texts.indexOf(' :'); + const rowChildren = columnHack ? src.slice(1) : [...src]; + src.length = 0; + + const row = newRow(rowMainAlign, rowChildren); + + if (frosthavenStyle && conditional) { + const outer = isInner ? inColumn : top; + const belongs = computeBelongs(outer, row); + const cond: ConditionalNode = { + kind: 'conditional', + elementUse, + belongs, + boss: bossStatCard, + children: [row] + }; + outer.push(cond); + } else if (isInner) { + inColumn.push(row); + } else { + top.push(row); + } + continue; + } + + // Element image (¤). + if (line.startsWith('¤')) { + const element = line.substring(1); + const node: Node = { kind: 'image', gfx: element, element: isElement(element) }; + target().push(node); + continue; + } + + // Right-part-of-last-line attach. + if (line.startsWith('!')) { + isRightPart = true; + line = line.substring(1); + } + // Small / divider. + if (line.startsWith('*')) { + sizeToken = '*'; + styleToUse = 'small'; + line = line.substring(1); + if (line.startsWith('....')) { + styleToUse = 'divider'; + if (line.startsWith('*')) { + line = line.substring(1); + styleToUse = 'dividerThin'; + } + // In FH (or left-aligned) the divider is a picture. + if (frosthavenStyle || align === 'left') { + const node: Node = { kind: 'divider', thin: styleToUse === 'dividerThin', boss: align === 'left' }; + target().push(node); + continue; + } + } + } + // Mid / mid-squished. + if (line.startsWith('^')) { + sizeToken = '^'; + styleToUse = 'mid'; + line = line.substring(1); + if (line.startsWith('^')) { + styleToUse = 'midSquished'; + line = line.substring(1); + } + } + // Granted line (no stat application) vs. stat application. + if (line.startsWith('>')) { + line = line.substring(1); + } else if (applyStats && monster) { + const statLines = applyMonsterStats(line, sizeToken, monster, applyAll); + line = statLines.shift() ?? ''; + if (statLines.length > 0) strings.splice(i + 1, 0, ...statLines); + } + + // Parse the line into segments (%, £, Å). + let partStart = 0; + let isIconPart = false; + let addText = true; + for (let ci = 0; ci < line.length; ci++) { + const ch = line[ci]; + if (ch === '|') addText = false; + if (ch === '%') { + if (isIconPart) { + const iconToken = line.substring(partStart, ci); + let iconGfx = iconToken; + if (monster && iconToken === 'move' && flying) iconGfx = 'flying'; + if (left) { + const tokenVal = TOKENS[iconToken]; + if (tokenVal && /[a-z]/.test(tokenVal)) iconGfx += '_black'; + } + if (iconToken === 'use') { + // Element-use: consume the previous element icon, overlay "use". + const prev = textParts.pop(); + const element = + prev && prev.kind === 'token' ? prev.token : iconToken; + textParts.push({ kind: 'elementUse', element, style: styleToUse }); + textParts.push({ + kind: 'text', + text: frosthavenStyle ? ' :' : ' : ', + style: 'normal' + }); + } else { + const rawLabel = TOKENS[iconToken] ?? null; + const label = + frosthavenStyle || rawLabel == null + ? null + : translate(rawLabel); + if (addText && label) { + textParts.push({ kind: 'text', text: label, style: styleToUse }); + } + textParts.push({ + kind: 'token', + token: iconToken, + gfx: iconGfx, + overflow: shouldOverflow(frosthavenStyle, iconGfx), + isElement: isElement(iconToken), + style: styleToUse + }); + } + isIconPart = false; + addText = true; + } else { + if (ci > 0 && partStart < ci) { + let textPart = line.substring(partStart, ci); + if (line[ci - 1] === '|') + textPart = line.substring(partStart, ci - 1); + textParts.push({ kind: 'text', text: textPart, style: styleToUse }); + } + isIconPart = true; + } + partStart = ci + 1; + } + if (ch === '£') { + partStart = ci + 1; + if (styleToUse === 'normal') styleToUse = 'elite'; + else if (styleToUse === 'small') styleToUse = 'eliteSmall'; + else if (styleToUse === 'mid') styleToUse = 'eliteMid'; + } + if (ch === 'Å') styleToUse = 'special'; + } + if (partStart < line.length) { + textParts.push({ kind: 'text', text: line.substring(partStart), style: styleToUse }); + } + + // Attach to the previous row, or add a fresh one. + if (isRightPart && lastRow) { + lastRow.children.push(...textParts); + } else { + const row = newRow(rowMainAlign, textParts); + target().push(row); + lastRow = row; + } + } + + return { kind: 'column', align, children: top }; +} + +/** Whether the conditional box draws the top "element" banner. */ +function computeBelongs(outer: Node[], row: Node): boolean { + let belongs = true; + if (outer.length === 0) { + belongs = false; + } else { + const last = outer[outer.length - 1]; + if (last.kind === 'divider') belongs = false; + } + const graphics = allImages(row); + if (graphics.length === 2 && isElement(graphics[0]) && isElement(graphics[1])) + belongs = false; + return belongs; +} + +// Re-export for convenience in tests / the renderer. +export { hasGHVersion }; |
