// Helpers for the Translations page, ported from babyboo messageContent, messagePlaceholders and // messageImportPreview, trimmed to area A. /** The stored `content` JSON (locale -> text) as a record; malformed content is `{}`, never a throw. */ export function parseContent(content: string | null | undefined): Record { if (!content) return {}; try { const parsed = JSON.parse(content); return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record) : {}; } catch { return {}; } } /** * The content to save: the stored text with the edited languages applied. A blank field is dropped, * and languages the form did not show (e.g. Tastefully's Malay) are kept as stored. */ export function buildContent(stored: string | null | undefined, edited: Record): string { const out: Record = { ...parseContent(stored) }; for (const [code, value] of Object.entries(edited)) { const v = value.trim(); if (v) out[code] = v; else delete out[code]; } return JSON.stringify(out); } const tokens = (text: string) => new Set(text.match(/\{[A-Za-z0-9_]+\}/g) ?? []); /** Placeholders compared as sets: `missing` are in English but not in `other`, `extra` the reverse. */ export function placeholderMismatch(english: string, other: string): { missing: string[]; extra: string[] } { const en = tokens(english); const ot = tokens(other); return { missing: [...en].filter((x) => !ot.has(x)).sort(), extra: [...ot].filter((x) => !en.has(x)).sort() }; } export interface MessageRow { id?: number; code: string; area?: string; content: string; description?: string | null; } export interface ImportPreviewRow { code: string; action: "create" | "update"; currentEn?: string; incomingEn?: string; } /** Matches by code ignoring case, never by id, as the backend import does. */ export function buildImportPreview(rows: MessageRow[], existing: MessageRow[]): ImportPreviewRow[] { const byCode = new Map(); for (const m of existing) if (!byCode.has(m.code.toLowerCase())) byCode.set(m.code.toLowerCase(), m); return rows.map((r) => { const cur = byCode.get(r.code.toLowerCase()); const incomingEn = parseContent(r.content).en_US; return cur ? { code: r.code, action: "update", currentEn: parseContent(cur.content).en_US, incomingEn } : { code: r.code, action: "create", incomingEn }; }); }