summaryrefslogtreecommitdiff
path: root/web/src/lib/game/line
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-16 22:19:39 +0100
commit94e2850fb73005f3fb30af8489905e5cdfb6fac5 (patch)
tree1aea8e7e6683af770f0c57c0fb654003778c9f16 /web/src/lib/game/line
parent4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (diff)
Phase 4: cards and decks (M4)
Full card play in the browser: ability-line rendering, monster ability decks, the full modifier-deck (AMD) suite, and the loot deck — all server commands, faithful to the reference flows and layout. Web (Svelte 5): - Line renderer + in-game translations: $lib/game/line/ renders the reference line_builder output (emphasis, range markers, element styling); gameI18n.ts loads the /i18n/ in-game ability-text tables (the client-side TranslationService equivalent) - Card components: stat cards, monster ability cards (OG + FH styles, rendered lines, element/flying tokens), modifier cards (gfx resolver incl. P<n> perk graphics), loot cards (party-size value rules, owner, enhancements) - Monster ability decks: AbilityCardSlot in each monster row (front of the current card while active in playTurns, else the back with the draw-pile count); AbilityCardsMenu (reveal top cards, draw extra, extra shuffle, activate/inactivate, drag-reorder, remove); card zoom - Modifier decks: ModifierDeckWidget (tap to draw, face-up revealed top card, empty-box class icon for the current character's own deck, discard stack); ModifierDeckHeader (bad omen, corrosive spew, ±1/−2/+0, imbue 1/2, reveal with the Cassandra 8-button cap, save/don't-save revealed cards, removed count, Hail perk, CS sanctuary/party cards, faction icons, bless/curse and the empower/enfeeble counters); ModifierDeckMenu (draw-pile drag-reorder + send-to-bottom/shuffle/remove, discard remove/return-top, removed pile with return, faction grid with gray-out, perks menu with the Frosthaven opt-in); card zoom - Loot deck: LootDeckWidget (player-gated draw, current-character icon, discard stack, hidden when both piles empty); LootCardsMenu (set owner, per-character loot totals, add card, enhance with the reference material/herb/coin splits, special cards 1418/1419, return top/bottom) - Bottom DeckArea: loot deck left; the Character Decks toggle with the reference open-state cycling (oneOpen/allOpen/noOpen per round state; one-deck view for the current character during playTurns); ally deck behind shouldShowAlliesDeck; global deck - Pure helper modules ported from the reference: rules.ts (FH card styling, inactive-for-rule, ally-deck gate, deck resolution), modifierDeck.ts (pile derivations, faction cards), perks.ts (active perk set, card-text tokens, descriptions, add/remove gating), cards/lootCard.ts (values + per-character totals) - App wiring: campaign data loaded on currentCampaign change (guarded against out-of-order fetches); ability/AMD/loot menus and zooms driven by live-derived state so open menus track pile changes; Escape closes every dialog Server: - /i18n/ static mount: the in-game ability-text translation files the card renderer resolves (the reference TranslationService data) - Loot deck JSON gains pools (pool card ids per pool — the client derives card gfx from pool key + index and reads the enhancements map; ids only, since pool cards are the same live instances that mutate in the piles) - Modifier deck JSON gains removables (the counter totals the header reads) plus load-time round-trip for saves written before the field existed Docs: - PLAN.md: Phase 3 and Phase 4 marked complete (corrected the 'character ability decks' mislabel — ability decks are monster-only), progress log entries for M3 and M4 svelte-check 0 errors; web tests 177/177; build OK; dart analyze 0 errors; dart test 592/592; scripts/ci.sh green.
Diffstat (limited to 'web/src/lib/game/line')
-rw-r--r--web/src/lib/game/line/buildAbility.ts87
-rw-r--r--web/src/lib/game/line/frosthavenConverter.ts199
-rw-r--r--web/src/lib/game/line/images.ts20
-rw-r--r--web/src/lib/game/line/lineParser.ts389
-rw-r--r--web/src/lib/game/line/lineStyle.ts52
-rw-r--r--web/src/lib/game/line/statApplier.ts350
-rw-r--r--web/src/lib/game/line/statCalculator.ts140
-rw-r--r--web/src/lib/game/line/tokens.ts95
-rw-r--r--web/src/lib/game/line/types.ts155
9 files changed, 1487 insertions, 0 deletions
diff --git a/web/src/lib/game/line/buildAbility.ts b/web/src/lib/game/line/buildAbility.ts
new file mode 100644
index 0000000..45c6e7a
--- /dev/null
+++ b/web/src/lib/game/line/buildAbility.ts
@@ -0,0 +1,87 @@
+/**
+ * The ability-card rendering pipeline (PORTING.md §8b): pre-translate the
+ * card's lines with the in-game `t()`, run them through {@link parseLines}
+ * (expand → convert → per-line stat application → layout), and return the
+ * structured tree the Svelte renderer walks. Also builds the {@link
+ * StatMonster} the stat applier needs from the monster model + live standees.
+ */
+
+import { gt } from '$lib/i18n/gameI18n';
+import { parseLines } from './lineParser';
+import type { MonsterAbilityCard, MonsterType } from '$lib/protocol/types';
+import type { MonsterData } from '$lib/data/gameData';
+import type { ColumnNode } from './types';
+import type { StatBlock, StatLevel, StatMonster } from './statApplier';
+
+export interface AbilityRenderOptions {
+ /** Frosthaven style (icon-only tokens, sub-line boxes). */
+ fh: boolean;
+ /** Left-aligned boss stat card layout. */
+ left?: boolean;
+ /** Resolve stats per line (the reference's `!noCalculation`). */
+ applyStats?: boolean;
+ /** Force the elite/normal split (the reference's `calculateAll`). */
+ applyAll?: boolean;
+ scale?: number;
+ /** The monster is a flyer (move token → flying graphic). */
+ flying?: boolean;
+}
+
+type StatSource = {
+ health?: number | string;
+ move?: number | string;
+ attack?: number | string;
+ range?: number;
+ attributes?: string[];
+};
+
+function toBlock(source: StatSource | undefined): StatBlock | undefined {
+ if (!source) return undefined;
+ return {
+ health: source.health,
+ move: source.move,
+ attack: source.attack,
+ range: source.range,
+ attributes: source.attributes
+ };
+}
+
+/**
+ * The stat-applier view of a monster at [level], for the standees currently
+ * in play. Built from the edition's level stats + the live standee types.
+ */
+export function statMonsterFor(
+ monster: MonsterData,
+ level: number,
+ standeeTypes: MonsterType[],
+ isActive: boolean
+): StatMonster {
+ const raw = monster.levels.find((l) => l.level === level) ?? monster.levels[0];
+ const statLevel: StatLevel = {
+ normal: toBlock(raw?.normal as StatSource | undefined),
+ elite: toBlock(raw?.elite as StatSource | undefined),
+ boss: toBlock(raw?.boss as StatSource | undefined)
+ };
+ return { level: statLevel, standeeTypes, isActive };
+}
+
+/** The full ability-card line tree (lines pre-translated, then parsed). */
+export function buildAbilityCardTree(
+ card: MonsterAbilityCard,
+ stat: StatMonster | null,
+ opts: AbilityRenderOptions
+): ColumnNode {
+ const lines = card.lines.map(gt);
+ return parseLines(lines, {
+ left: opts.left ?? false,
+ applyStats: opts.applyStats ?? false,
+ applyAll: opts.applyAll ?? false,
+ align: opts.left ? 'left' : 'center',
+ frosthavenStyle: opts.fh,
+ scale: opts.scale ?? 1,
+ monster: stat,
+ flying: opts.flying ?? false,
+ bossStatCard: opts.left ?? false,
+ translate: gt
+ });
+}
diff --git a/web/src/lib/game/line/frosthavenConverter.ts b/web/src/lib/game/line/frosthavenConverter.ts
new file mode 100644
index 0000000..534efd9
--- /dev/null
+++ b/web/src/lib/game/line/frosthavenConverter.ts
@@ -0,0 +1,199 @@
+/**
+ * Frosthaven-style line conversion (client port of the reference
+ * `FrosthavenConverter`, PORTING.md §8b). Pure string → string: expands
+ * embedded newlines, rewrites keywords into token/line markers, and tracks the
+ * sub-line / conditional / element-use state so the line parser can lay lines
+ * out as the reference does (sub-lines boxed, element-use blocks, …).
+ */
+
+const LOOKBACK = 2;
+
+/** Split lines containing `\n`, propagating the `^` / `^^` prefix. */
+export function expandEmbeddedNewlines(lines: string[]): string[] {
+ const result: string[] = [];
+ for (const line of lines) {
+ if (!line.includes('\n')) {
+ result.push(line);
+ continue;
+ }
+ const parts = line.split('\n');
+ result.push(parts[0]);
+ const outerPrefix = parts[0].startsWith('^^')
+ ? '^^'
+ : parts[0].startsWith('^')
+ ? '^'
+ : '';
+ for (let i = 1; i < parts.length; i++) result.push(outerPrefix + parts[i]);
+ }
+ return result;
+}
+
+/** The keyword → token/line-marker rewrite + sub-line state machine. */
+export function convertLinesToFH(lines: string[], applyStats: boolean): string[] {
+ const retVal: string[] = [];
+ let isSubLine = false;
+ let isReallySubLine = false;
+ let isConditional = false;
+ let isElementUse = false;
+
+ for (let i = 0; i < lines.length; i++) {
+ let startOfConditional = false;
+ let line = lines[i];
+
+ if (line === '[newLine]') line = '';
+
+ if (
+ (line === '[r]' || line === '[s]') &&
+ lines[i + 1]?.includes('%use')
+ ) {
+ isElementUse = true;
+ isConditional = true;
+ startOfConditional = true;
+ }
+ if ((line === '[/r]' || line === '[/s]') && isConditional) {
+ isConditional = false;
+ isElementUse = false;
+ }
+
+ if (i > 0 && lines[i - 1].includes('%use')) startOfConditional = true;
+ if (
+ i > 1 &&
+ lines[i - LOOKBACK].includes('%use') &&
+ (lines[i - 1] === '[r]' || lines[i - 1] === '[s]' || lines[i - 1] === '[c]')
+ ) {
+ startOfConditional = true;
+ }
+
+ line = line.replaceAll('Affect', 'Target');
+ line = line.replaceAll('damage', '%damage%');
+ line = line.replaceAll('%damage%d', 'damaged');
+ if (!applyStats) {
+ line = line.replaceAll(' - ', '-');
+ line = line.replaceAll(' + ', '+');
+ }
+ line = line.replaceAll('% ', '%');
+
+ if (line.startsWith('*')) {
+ if (isReallySubLine) retVal.push('[subLineEnd]');
+ isReallySubLine = false;
+ isSubLine = false;
+ isConditional = false;
+ isElementUse = false;
+ }
+
+ const isSubLineCandidate =
+ line.startsWith('^') &&
+ (line[1] === '%' ||
+ line.startsWith('^Self') ||
+ line.startsWith('^-') ||
+ line.startsWith('^+') ||
+ line.startsWith('^Advantage') ||
+ line.startsWith('^Target') ||
+ line.startsWith('^%target%') ||
+ line.startsWith('^Normal') ||
+ line.startsWith('^all') ||
+ (line.startsWith('^All') &&
+ !line.startsWith('^All attacks') &&
+ !line.startsWith('^All targets')));
+
+ if (line.startsWith('^') && isSubLine && !startOfConditional) {
+ if (isSubLineCandidate) {
+ if (
+ !isReallySubLine &&
+ (!isConditional ||
+ (isElementUse &&
+ !line.startsWith('^Perform') &&
+ !line.startsWith('^^for each')))
+ ) {
+ retVal.push('[subLineStart]');
+ isReallySubLine = true;
+ }
+
+ if (
+ isElementUse &&
+ (lines[i - 1]?.includes('use') ||
+ (lines[i - LOOKBACK]?.includes('use') &&
+ lines[i - 1]?.includes('[c]'))) &&
+ !line.startsWith('^Target') &&
+ !line.startsWith('^all') &&
+ !line.startsWith('^All') &&
+ !line.includes('instead')
+ ) {
+ line = line.substring(1);
+ if (retVal[retVal.length - 1] === '[subLineStart]') {
+ retVal.pop();
+ }
+ isReallySubLine = false;
+ }
+ line = '!' + line;
+ line = line.replace(/Self/, 'self').replace(/All/, 'all');
+
+ if (retVal[retVal.length - 1] === '[subLineStart]') {
+ retVal[retVal.length - 1] = '![subLineStart]';
+ }
+ } else {
+ isSubLine = false;
+ }
+ }
+
+ if (line.startsWith('^') && isReallySubLine) {
+ if (retVal[retVal.length - 1] !== '[subLineStart]') {
+ retVal.push('!^[lineBreak]');
+ }
+ line = '!' + line;
+ } else if (
+ !line.startsWith('!') &&
+ !line.startsWith('*') &&
+ !line.startsWith('^')
+ ) {
+ if (!isSubLine && !line.includes('%use%')) {
+ isSubLine = true;
+ } else if (isReallySubLine) {
+ retVal.push('[subLineEnd]');
+ isReallySubLine = false;
+ isSubLine = false;
+ }
+ }
+
+ // Use iconography instead of words (applied to every line, last).
+ line = line.replaceAll('Target', '%target%');
+ retVal.push(line);
+ }
+
+ if (isReallySubLine && (!isConditional || isElementUse)) {
+ retVal.push('[subLineEnd]');
+ }
+ return retVal;
+}
+
+/** Whether the token's graphic should overflow its line (FH condition icons). */
+export function shouldOverflow(frosthavenStyle: boolean, iconToken: string): boolean {
+ if (!frosthavenStyle) return false;
+ const exact = [
+ 'pierce',
+ 'brittle',
+ 'curse',
+ 'enfeeble',
+ 'bless',
+ 'invisible',
+ 'strengthen',
+ 'bane',
+ 'push',
+ 'pull',
+ 'poison',
+ 'wound',
+ 'infect',
+ 'chill',
+ 'disarm',
+ 'immobilize',
+ 'stun',
+ 'impair',
+ 'safeguard',
+ 'muddle'
+ ];
+ return (
+ exact.includes(iconToken) ||
+ iconToken.includes('poison') ||
+ iconToken.includes('wound')
+ );
+}
diff --git a/web/src/lib/game/line/images.ts b/web/src/lib/game/line/images.ts
new file mode 100644
index 0000000..78c10ac
--- /dev/null
+++ b/web/src/lib/game/line/images.ts
@@ -0,0 +1,20 @@
+/**
+ * Ability-icon image URLs. The Dart server serves the reference app's
+ * `assets/images/abilities/` under `/images/abilities/`. In Frosthaven style a
+ * token's graphic gets the `_fh` suffix when the base token has a
+ * Gloomhaven/Frosthaven variant pair (the reference's `hasGHVersion`); the
+ * decision uses the base token, not the `_black`-suffixed filename.
+ */
+
+import { hasGHVersion } from './tokens';
+
+/** The icon URL for [gfx] (already resolved to its base / `_black` / flyer form). */
+export function abilityImage(gfx: string, baseToken: string, frosthavenStyle: boolean): string {
+ const suffix = frosthavenStyle && hasGHVersion(baseToken) ? '_fh' : '';
+ return `/images/abilities/${gfx}${suffix}.png`;
+}
+
+/** The divider graphic (`divider_fh.png`, or the boss variant for left cards). */
+export function dividerImage(boss: boolean): string {
+ return boss ? '/images/abilities/divider_boss_fh.png' : '/images/abilities/divider_fh.png';
+}
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 };
diff --git a/web/src/lib/game/line/lineStyle.ts b/web/src/lib/game/line/lineStyle.ts
new file mode 100644
index 0000000..6d10482
--- /dev/null
+++ b/web/src/lib/game/line/lineStyle.ts
@@ -0,0 +1,52 @@
+/**
+ * Resolved font metrics for an ability-line segment (the reference `LineStyles`,
+ * PORTING.md §8b). The web card is centre-aligned and non-left, matching the
+ * reference's ability-card `createLines` call; only the Frosthaven/Gloomhaven
+ * split and the elite color vary. Sizes are in px at `scale` 1 — the renderer
+ * multiplies by the card's `scale`.
+ */
+
+import type { LineStyle } from './types';
+
+export interface ResolvedLine {
+ /** Font size in px at scale 1. */
+ size: number;
+ /** Unitless line-height. */
+ height: number;
+ color: string;
+}
+
+const WHITE = '#ffffff';
+const BLACK = '#000000';
+const ELITE = '#ffe600'; // Colors.yellow
+
+export function resolveStyle(
+ style: LineStyle,
+ frosthavenStyle: boolean,
+ left: boolean
+): ResolvedLine {
+ const color = left ? BLACK : WHITE;
+ switch (style) {
+ case 'normal':
+ return { size: frosthavenStyle ? 13.1 : 12.56, height: frosthavenStyle ? 0.84 : 0.85, color };
+ case 'mid':
+ return { size: frosthavenStyle ? 9.52 : 8.8, height: frosthavenStyle ? 1.0 : 0.85, color };
+ case 'midSquished':
+ return { size: frosthavenStyle ? 9.52 : 8.8, height: 0.8, color };
+ case 'small':
+ return { size: 8.0, height: 0.8, color };
+ case 'elite':
+ return { size: frosthavenStyle ? 13.1 : 12.56, height: frosthavenStyle ? 0.84 : 0.85, color: ELITE };
+ case 'eliteSmall':
+ return { size: 8.0, height: 1.0, color: ELITE };
+ case 'eliteMid':
+ return { size: frosthavenStyle ? 9.52 : 8.8, height: frosthavenStyle ? 1.0 : 0.85, color: ELITE };
+ case 'divider':
+ return { size: 6.4, height: 0.7, color };
+ case 'dividerThin':
+ return { size: 4.8, height: 0.1, color };
+ case 'special':
+ // The reference renders this as transparent Majalla text (a spacer).
+ return { size: 8.8, height: 1.0, color: 'transparent' };
+ }
+}
diff --git a/web/src/lib/game/line/statApplier.ts b/web/src/lib/game/line/statApplier.ts
new file mode 100644
index 0000000..1ce05dd
--- /dev/null
+++ b/web/src/lib/game/line/statApplier.ts
@@ -0,0 +1,350 @@
+/**
+ * Monster-stat substitution (client port of the reference `StatApplier`,
+ * PORTING.md §8b). Resolves `%attack% - 1` style lines against a monster's
+ * actual stats, producing the display strings the ability-card lines need:
+ * a normal value, an elite value (prefixed `!£` when both are shown), and any
+ * leftover line text (prefixed `!`). Stand-alone formulas (e.g. `C+L`) are
+ * evaluated in place.
+ *
+ * The engine keeps its own Dart copy; the client needs it to render ability
+ * cards faithfully. It operates on the monster's level stats (from `/data/`)
+ * and the standee types present, not on live state.
+ */
+
+import { calculateFormula } from './statCalculator';
+
+/** MonsterType index: 0 normal, 1 elite, 2 boss, 3 summon. */
+export type MonsterType = 0 | 1 | 2 | 3;
+const ELITE: MonsterType = 1;
+
+/** One stat block (`normal` / `elite` / a boss level's inline stats). */
+export interface StatBlock {
+ health?: number | string;
+ move?: number | string;
+ attack?: number | string;
+ range?: number;
+ attributes?: string[];
+}
+
+/** The monster's stats for its current level (already level-resolved). */
+export interface StatLevel {
+ normal?: StatBlock;
+ elite?: StatBlock;
+ /** Present when the level is a boss (its stats live inline on the level). */
+ boss?: StatBlock;
+}
+
+/** The data the applier needs about a monster. */
+export interface StatMonster {
+ level: StatLevel;
+ /** The `MonsterType` of each standee present. */
+ standeeTypes: MonsterType[];
+ /** Whether the monster row is the active one. */
+ isActive: boolean;
+}
+
+/** Formula + display context. */
+export interface StatApplierContext {
+ characterCount?: number;
+ level?: number;
+ /** The "no standees" setting (shows both stats when the monster is active). */
+ noStandees?: boolean;
+}
+
+/** Resolve a stat to a number, or null when a formula cannot be evaluated. */
+function calcStat(value: number | string | undefined, ctx: StatApplierContext): number | null {
+ if (value == null) return null;
+ if (typeof value === 'number') return value;
+ return calculateFormula(value, ctx);
+}
+
+/** The single characters the formula scanner treats as formula content. */
+const numberish = (ch: string): boolean => /^[\d ()xCL/*+-]+$/.test(ch);
+
+/** Pull the `{token: nr}` pairs out of a stat block's display attributes. */
+function parseTokens(attributes: string[] | undefined, ctx: StatApplierContext): Record<string, number> {
+ const map: Record<string, number> = {};
+ for (let item of attributes ?? []) {
+ const sizeMod = item.charAt(0);
+ if (sizeMod === '^' || (sizeMod === '*' && item.length > 1)) {
+ item = item.substring(1);
+ }
+ if (item.charAt(0) === '%') {
+ for (let i = 1; i < item.length; i++) {
+ if (item.charAt(i) === '%') {
+ const token = item.substring(1, i);
+ let number = 0;
+ if (i !== item.length - 1) {
+ for (let j = i + 2; j < item.length; j++) {
+ if (item.charAt(j) === ' ' || j === item.length - 1) {
+ const nr = item.substring(i + 1, j + 1);
+ const res = calculateFormula(nr, ctx);
+ if (res != null) number = res;
+ break;
+ }
+ }
+ }
+ if (token === 'target' && number === 0) continue;
+ map[token] = number;
+ break; // only one token per attribute line
+ }
+ }
+ }
+ }
+ return map;
+}
+
+/** The token values for the monster's normal or elite stats. */
+function getStatTokens(
+ monster: StatMonster,
+ isElite: boolean,
+ ctx: StatApplierContext
+): Record<string, number> {
+ const { normal, elite, boss } = monster.level;
+ if (boss != null) {
+ if (isElite) return {};
+ return parseTokens(boss.attributes, ctx);
+ }
+ const data = isElite ? elite : normal;
+ if (data == null) return {};
+ return parseTokens(data.attributes, ctx);
+}
+
+/** The condition tokens appended after an attack line (all but the stats). */
+const nonConditionStat = (item: string): boolean =>
+ /[a-z]/.test(item) &&
+ item !== 'shield' &&
+ item !== 'retaliate' &&
+ item !== 'range' &&
+ item !== 'heal' &&
+ item !== 'jump';
+
+function applyStatForToken(
+ formula: string,
+ line: string,
+ sizeModifier: string,
+ startIndex: number,
+ endIndex: number,
+ monster: StatMonster,
+ showNormal: boolean,
+ showElite: boolean,
+ lastToken: string,
+ normalTokens: Record<string, number>,
+ eliteTokens: Record<string, number>,
+ ctx: StatApplierContext
+): string[] {
+ if (!showElite && !showNormal) return [line];
+
+ const retVal: string[] = [];
+ const tokens: string[] = [];
+ const eTokens: string[] = [];
+ let normalValue = 0;
+ let eliteValue = 0;
+ let skipCalculation = false;
+ const normalBlock = monster.level.boss ?? monster.level.normal;
+ const eliteBlock = monster.level.elite;
+
+ if (lastToken === 'attack') {
+ if (normalBlock == null) return [];
+ const calc = calcStat(normalBlock.attack, ctx);
+ if (calc != null) normalValue = calc;
+ else skipCalculation = true;
+ if (eliteBlock != null) {
+ const ec = calcStat(eliteBlock.attack, ctx);
+ if (ec != null) eliteValue = ec;
+ }
+ for (const item of Object.keys(normalTokens)) {
+ if (nonConditionStat(item)) tokens.push(`%${item}%`);
+ }
+ for (const item of Object.keys(eliteTokens)) {
+ if (nonConditionStat(item)) eTokens.push(`%${item}%`);
+ }
+ } else if (lastToken === 'range') {
+ if ((normalBlock?.range ?? 0) !== 0) {
+ normalValue = normalBlock?.range ?? 0;
+ if (eliteBlock != null) eliteValue = eliteBlock.range ?? 0;
+ }
+ } else if (lastToken === 'move') {
+ normalValue = calcStat(normalBlock?.move, ctx) ?? 0;
+ if (eliteBlock != null) eliteValue = calcStat(eliteBlock.move, ctx) ?? 0;
+ } else if (lastToken === 'shield') {
+ if (eliteBlock != null && eliteTokens.shield != null) eliteValue = eliteTokens.shield;
+ if (normalBlock != null && normalTokens.shield != null) normalValue = normalTokens.shield;
+ } else if (lastToken === 'retaliate') {
+ if (eliteBlock != null && eliteTokens.retaliate != null) eliteValue = eliteTokens.retaliate;
+ if (normalBlock != null && normalTokens.retaliate != null)
+ normalValue = normalTokens.retaliate;
+ }
+
+ let normalResult = formula;
+ if (!skipCalculation) {
+ const res = calculateFormula(`${formula}+${normalValue}`, ctx);
+ if (res != null) normalResult = (res < 0 ? 0 : res).toString();
+ else skipCalculation = true;
+ }
+
+ let newStartOfLine = line.substring(0, startIndex);
+ if (showNormal) {
+ newStartOfLine += normalResult;
+ if (!skipCalculation) {
+ for (const item of tokens) {
+ newStartOfLine += `|${item}`;
+ const key = item.substring(1, item.length - 1);
+ const value = normalTokens[key] ?? 0;
+ if (value > 0) newStartOfLine += String(value);
+ }
+ }
+ }
+
+ // Special case: uncalculable and only elites ("heed the pigs").
+ if (eliteBlock != null && skipCalculation && showElite && !showNormal) {
+ newStartOfLine += normalResult;
+ }
+
+ if (eliteBlock != null && !skipCalculation && showElite) {
+ if (showNormal) newStartOfLine += '/';
+ retVal.push(newStartOfLine);
+ const eliteResult =
+ calculateFormula(`${formula}+${eliteValue}`, ctx) ?? 0;
+ const clamped = eliteResult < 0 ? 0 : eliteResult;
+ let eliteString = `!${sizeModifier}£${clamped}`;
+ for (const item of eTokens) {
+ eliteString += `|${item}`;
+ const key = item.substring(1, item.length - 1);
+ const value = eliteTokens[key]!;
+ if (value > 0) eliteString += String(value);
+ }
+ retVal.push(eliteString);
+ } else {
+ retVal.push(newStartOfLine);
+ }
+
+ if (endIndex < line.length) {
+ const leftOver = `!${sizeModifier}${line.substring(endIndex + 1, line.length)}`;
+ retVal.push(leftOver);
+ }
+ return retVal;
+}
+
+/**
+ * Apply the monster's stats to a line. Returns the list of display strings
+ * (usually one; more when an elite/normal split or trailing text is produced).
+ */
+export function applyMonsterStats(
+ lineInput: string,
+ sizeToken: string,
+ monster: StatMonster,
+ forceShowAll: boolean,
+ ctx: StatApplierContext = {}
+): string[] {
+ let showElite = false;
+ const noStandees = ctx.noStandees ?? false;
+ if ((noStandees && monster.isActive) || monster.standeeTypes.includes(ELITE)) {
+ showElite = true;
+ }
+ let showNormal = false;
+ if (
+ (noStandees && monster.isActive) ||
+ monster.standeeTypes.some((t) => t !== ELITE)
+ ) {
+ showNormal = true;
+ }
+ if (forceShowAll) {
+ showElite = true;
+ showNormal = true;
+ }
+
+ let line = lineInput;
+ let retVal: string[] = [];
+
+ const normalTokens = getStatTokens(monster, false, ctx);
+ const eliteTokens = getStatTokens(monster, true, ctx);
+
+ let lastToken = '';
+ let isInToken = false;
+ let tokenStartIndex = 0;
+
+ for (let i = 0; i < line.length; i++) {
+ if (line.charAt(i) === '%') {
+ if (!isInToken) {
+ isInToken = true;
+ tokenStartIndex = i + 1;
+ } else {
+ isInToken = false;
+ lastToken = line.substring(tokenStartIndex, i);
+ }
+ }
+
+ const isStart =
+ (!isInToken &&
+ (line.charAt(i) === '+' ||
+ line.charAt(i) === '-' ||
+ line.charAt(i) === 'C' ||
+ line.charAt(i) === 'L')) ||
+ line.charAt(i) === 'X' ||
+ ((numberish(line.charAt(i)) && lastToken === '') &&
+ (i === 0 || line.charAt(i - 1) === ' '));
+
+ if (isStart) {
+ let formula = line.charAt(i);
+ const startIndex = i;
+ let endIndex = i;
+
+ for (let j = i + 1; j < lineInput.length; j++) {
+ const val = lineInput.charAt(j);
+ if (numberish(val) || val === 'd') {
+ if (val !== ' ') formula += val;
+ endIndex = j;
+ } else {
+ i = j;
+ if (lineInput.charAt(i - 1) === ' ') {
+ i = j - 1;
+ endIndex -= 1;
+ }
+ if (i > 0 && lineInput.charAt(i - 1) === '(') {
+ i = j - 1;
+ endIndex -= 1;
+ formula = formula.substring(0, formula.length - 1);
+ if (i > 1 && lineInput.charAt(i - 2) === ' ') {
+ i = j - 1;
+ endIndex -= 1;
+ }
+ }
+ break;
+ }
+ }
+
+ if (
+ (formula.length > 1 && lastToken !== '') ||
+ formula.length > 2
+ ) {
+ if (lastToken !== '') {
+ retVal = applyStatForToken(
+ formula,
+ line,
+ sizeToken,
+ startIndex,
+ endIndex,
+ monster,
+ showNormal,
+ showElite,
+ lastToken,
+ normalTokens,
+ eliteTokens,
+ ctx
+ );
+ lastToken = '';
+ if (retVal.length > 0) return retVal;
+ } else {
+ const result = calculateFormula(formula, ctx);
+ if (result != null) {
+ const r = result < 0 ? 0 : result;
+ line = line.slice(0, startIndex) + String(r) + line.slice(endIndex + 1);
+ }
+ }
+ }
+ }
+ }
+
+ return [line];
+}
diff --git a/web/src/lib/game/line/statCalculator.ts b/web/src/lib/game/line/statCalculator.ts
new file mode 100644
index 0000000..1f7887b
--- /dev/null
+++ b/web/src/lib/game/line/statCalculator.ts
@@ -0,0 +1,140 @@
+/**
+ * Formula evaluation (client port of the reference `StatCalculator`, PORTING.md
+ * §8b). The engine keeps its own Dart copy for its internal use; the client
+ * needs the same substitution + arithmetic to resolve `%attack% - 1` style
+ * lines while rendering ability cards.
+ *
+ * Substitutes `C` (current character count, clamped to ≥ 2) and `L` (level),
+ * then evaluates with the reference parser: integer arithmetic where `/`
+ * rounds up (ceil) and `d` rounds down (floor), and `<` / `>` / `=` produce
+ * 1 / 0.
+ */
+
+export interface FormulaContext {
+ /** Current number of characters (clamped to a minimum of 2). */
+ characterCount?: number;
+ /** Current game level. */
+ level?: number;
+}
+
+/** The sentinel used past the end of the string (matches no real character). */
+const END = '\u0000';
+
+class FormulaParser {
+ private pos = -1;
+ private ch = END;
+
+ constructor(private readonly str: string) {}
+
+ /** Run the grammar and return the value, or null when unparseable. */
+ parse(): number | null {
+ try {
+ this.nextChar();
+ const result = this.parseCondition();
+ if (this.pos < this.str.length) return null;
+ return result;
+ } catch {
+ return null;
+ }
+ }
+
+ private nextChar(): void {
+ this.pos += 1;
+ this.ch = this.pos < this.str.length ? this.str.charAt(this.pos) : END;
+ }
+
+ private eat(charToEat: string): boolean {
+ while (this.ch === ' ') this.nextChar();
+ if (this.ch === charToEat) {
+ this.nextChar();
+ return true;
+ }
+ return false;
+ }
+
+ // Grammar (the reference StatCalculator):
+ // condition = expression | expression (<|>|=) expression
+ // expression = term | expression (+|-) term
+ // term = factor | term (*|x) factor | term (/) factor | term (d) factor
+ // factor = +factor | -factor | ( expression ) | number
+ //
+ // `*` and `x` both multiply; `/` rounds up, `d` rounds down; the
+ // comparison operators yield 1 (true) or 0 (false).
+
+ private parseCondition(): number {
+ let result = this.parseExpression();
+ for (;;) {
+ if (this.eat('<')) result = result < this.parseExpression() ? 1 : 0;
+ else if (this.eat('>')) result = result > this.parseExpression() ? 1 : 0;
+ else if (this.eat('=')) result = result === this.parseExpression() ? 1 : 0;
+ else return result;
+ }
+ }
+
+ private parseExpression(): number {
+ let result = this.parseTerm();
+ for (;;) {
+ if (this.eat('+')) result += this.parseTerm();
+ else if (this.eat('-')) result -= this.parseTerm();
+ else return result;
+ }
+ }
+
+ private parseTerm(): number {
+ let result = this.parseFactor();
+ for (;;) {
+ if (this.eat('*')) result *= this.parseFactor();
+ else if (this.eat('x')) result *= this.parseFactor();
+ else if (this.eat('/')) result = Math.ceil(result / this.parseFactor());
+ else if (this.eat('d')) result = Math.floor(result / this.parseFactor());
+ else return result;
+ }
+ }
+
+ private parseFactor(): number {
+ if (this.eat('+')) return this.parseFactor();
+ if (this.eat('-')) return -this.parseFactor();
+
+ if (this.eat('(')) {
+ const result = this.parseExpression();
+ if (!this.eat(')')) throw new Error("missing ')'");
+ return result;
+ }
+
+ const first = this.ch.codePointAt(0) ?? 0;
+ if (first >= 48 && first <= 57) {
+ const startPos = this.pos;
+ while (
+ this.ch !== END &&
+ this.ch.codePointAt(0)! >= 48 &&
+ this.ch.codePointAt(0)! <= 57
+ ) {
+ this.nextChar();
+ }
+ return parseInt(this.str.substring(startPos, this.pos), 10);
+ }
+
+ throw new Error(`unexpected: ${this.ch}`);
+ }
+}
+
+/** Evaluate a formula string (no C / L substitution). Null when malformed. */
+export function evalFormula(str: string): number | null {
+ return new FormulaParser(str).parse();
+}
+
+/**
+ * Substitute C / L from [ctx] (defaulting C=2, L=1) then evaluate. Mirrors the
+ * reference `StatCalculator.calculateFormula`; returns null when the result is
+ * not an integer.
+ */
+export function calculateFormula(
+ str: string,
+ ctx: FormulaContext = {}
+): number | null {
+ const C = Math.max(2, ctx.characterCount ?? 2);
+ const L = ctx.level ?? 1;
+ const formula = str.replaceAll('C', String(C)).replaceAll('L', String(L));
+ const result = evalFormula(formula);
+ return typeof result === 'number' ? result : null;
+}
diff --git a/web/src/lib/game/line/tokens.ts b/web/src/lib/game/line/tokens.ts
new file mode 100644
index 0000000..ed070ba
--- /dev/null
+++ b/web/src/lib/game/line/tokens.ts
@@ -0,0 +1,95 @@
+/**
+ * The ability-line token table and element check (the reference `LineBuilder`'s
+ * `tokens` map + `isElement`, PORTING.md §8b). Token keys are the `%token%`
+ * names used in card lines; values are the display labels (translated by the
+ * in-game `t()` at render time, so the English label is the key's translation).
+ */
+
+export const TOKENS: Record<string, string> = {
+ attack: 'Attack',
+ move: 'Move',
+ teleport: 'Teleport',
+ range: 'Range',
+ heal: 'Heal',
+ target: 'Target',
+ shield: 'Shield',
+ loot: 'Loot',
+ retaliate: 'Retaliate',
+ jump: 'Jump',
+ stun: 'STUN',
+ wound: 'WOUND',
+ disarm: 'DISARM',
+ immobilize: 'IMMOBILIZE',
+ poison: 'POISON',
+ invisible: 'INVISIBLE',
+ strengthen: 'STRENGTHEN',
+ muddle: 'MUDDLE',
+ regenerate: 'REGENERATE',
+ ward: 'WARD',
+ impair: 'IMPAIR',
+ bane: 'BANE',
+ brittle: 'BRITTLE',
+ chill: 'CHILL',
+ infect: 'INFECT',
+ rupture: 'RUPTURE',
+ push: 'PUSH',
+ pull: 'PULL',
+ pierce: 'PIERCE',
+ curse: 'CURSE',
+ enfeeble: 'ENFEEBLE',
+ empower: 'EMPOWER',
+ bless: 'BLESS',
+ safeguard: 'SAFEGUARD',
+ flip: 'ROLLING',
+ damage: 'damage',
+ and: 'and'
+};
+
+/** True when [name] is one of the five elements (or "any"). */
+export function isElement(name: string): boolean {
+ return (
+ name.includes('air') ||
+ name.includes('earth') ||
+ name.includes('fire') ||
+ name.includes('ice') ||
+ name.includes('dark') ||
+ name.includes('light') ||
+ name === 'any'
+ );
+}
+
+/**
+ * Tokens whose graphic has both a Gloomhaven and a Frosthaven variant
+ * (the reference `hasGHVersion` / `_ghVersionSet`). Only these get the `_fh`
+ * image suffix when the card renders in Frosthaven style; the rest reuse the
+ * single graphic.
+ */
+const GH_VERSION_SET = new Set([
+ 'attack',
+ 'damage',
+ 'disarm',
+ 'flying',
+ 'heal',
+ 'immobilize',
+ 'invisible',
+ 'jump',
+ 'loot',
+ 'move',
+ 'pierce',
+ 'poison',
+ 'push',
+ 'pull',
+ 'stun',
+ 'target',
+ 'range',
+ 'retaliate',
+ 'shield',
+ 'strengthen',
+ 'teleport',
+ 'use',
+ 'wound'
+]);
+
+export function hasGHVersion(name: string): boolean {
+ return GH_VERSION_SET.has(name);
+}
diff --git a/web/src/lib/game/line/types.ts b/web/src/lib/game/line/types.ts
new file mode 100644
index 0000000..bf1c14f
--- /dev/null
+++ b/web/src/lib/game/line/types.ts
@@ -0,0 +1,155 @@
+/**
+ * The structured tree produced by {@link parseLines} (the client port of the
+ * reference `LineBuilder.createLines`, PORTING.md §8b). The tree mirrors the
+ * reference's Flutter widget layout — a vertical stack of rows, each holding
+ * text / icon / element-use segments, with sub-line boxes, conditional (dotted)
+ * boxes, columns, row-groups, element images and dividers nested as the
+ * reference lays them out. The Svelte renderer walks this tree; it carries no
+ * theme-specific image paths so the renderer can pick the right assets.
+ */
+
+export type Align = 'left' | 'center' | 'right';
+
+/** The font-size / color treatment for a segment (the reference `LineStyles`). */
+export type LineStyle =
+ | 'normal'
+ | 'small'
+ | 'mid'
+ | 'midSquished'
+ | 'elite'
+ | 'eliteSmall'
+ | 'eliteMid'
+ | 'divider'
+ | 'dividerThin'
+ | 'special';
+
+// --- Leaf segments ---------------------------------------------------------
+
+/** A run of plain text (a card line's words). */
+export interface TextSeg {
+ kind: 'text';
+ text: string;
+ style: LineStyle;
+}
+
+/** An ability token (a `%token%` icon). `label` is the English display name
+ * (the renderer translates it via the in-game `t()`); `null` in Frosthaven
+ * style, where tokens render icon-only. */
+export interface TokenSeg {
+ kind: 'token';
+ /** The raw token key (e.g. `attack`, `poison`, `use`). */
+ token: string;
+ /** Resolved graphic key (e.g. `move` → `flying` for a flyer). */
+ gfx: string;
+ /** True when the graphic should overflow its line (FH condition icons). */
+ overflow: boolean;
+ /** True for the five elements (affects icon sizing). */
+ isElement: boolean;
+ style: LineStyle;
+}
+
+/** A "use element" overlay: an element icon with the `use` graphic + a colon. */
+export interface ElementUseSeg {
+ kind: 'elementUse';
+ element: string;
+ style: LineStyle;
+}
+
+// --- Structural nodes ------------------------------------------------------
+
+/** A vertical stack (the card body, or a `[c]…[/c]` column). */
+export interface ColumnNode {
+ kind: 'column';
+ align: Align;
+ children: Node[];
+}
+
+/** A single laid-out line. Children are segments plus any trailing sub-line /
+ * conditional / column / row-group the line carries. */
+export interface RowNode {
+ kind: 'row';
+ align: Align;
+ children: Node[];
+}
+
+/** A horizontal group of side-by-side content (an `[r]…[/r]` row-group). */
+export interface RowGroupNode {
+ kind: 'rowgroup';
+ align: Align;
+ children: Node[];
+}
+
+/** A gray rounded box holding sub-line rows (the FH sub-line background). */
+export interface SubLineNode {
+ kind: 'subline';
+ /** True when the card is a boss stat card (darker box). */
+ boss: boolean;
+ /** True when the box wraps a conditional (element-use) effect. */
+ conditional: boolean;
+ children: Node[];
+}
+
+/** A dotted-border box (the FH conditional / element-use graphic). */
+export interface ConditionalNode {
+ kind: 'conditional';
+ elementUse: boolean;
+ /** Whether the top "element" banner is drawn (the reference `belongs`). */
+ belongs: boolean;
+ boss: boolean;
+ children: Node[];
+}
+
+/** A standalone element image (a `¤ element` line). */
+export interface ImageNode {
+ kind: 'image';
+ gfx: string;
+ element: boolean;
+}
+
+/** A horizontal divider (`*....` line). */
+export interface DividerNode {
+ kind: 'divider';
+ thin: boolean;
+ boss: boolean;
+}
+
+export type Node =
+ | TextSeg
+ | TokenSeg
+ | ElementUseSeg
+ | ColumnNode
+ | RowNode
+ | RowGroupNode
+ | SubLineNode
+ | ConditionalNode
+ | ImageNode
+ | DividerNode;
+
+// --- Parser inputs ---------------------------------------------------------
+
+export interface LineBuildOptions {
+ /** Left-aligned (boss stat card) layout. */
+ left: boolean;
+ /** Resolve `%attack% - 1` against the monster's stats (per line). */
+ applyStats: boolean;
+ /** Force the elite/normal split even with no standees. */
+ applyAll: boolean;
+ align: Align;
+ /** True for Frosthaven-styled editions. */
+ frosthavenStyle: boolean;
+ /** The user's card scale factor (the reference `scale`). */
+ scale: number;
+ /** The monster, for stat application + the flyer `move`→`flying` swap. */
+ monster?: import('./statApplier').StatMonster | null;
+ /** True when the monster type is a flyer (move token → flying graphic). */
+ flying?: boolean;
+ /** True for a boss stat card (darker boxes, left dividers). */
+ bossStatCard?: boolean;
+ /**
+ * In-game translation for token display names (the reference translates
+ * them at parse time). The card's own lines are pre-translated by the
+ * caller before `parseLines` is called, so only the token labels need
+ * translating here. Defaults to the identity.
+ */
+ translate?: (s: string) => string;
+}