import type { Flow, FlowEdge, FlowNode, FlowShape } from "../ir.ts";
const SAFE_ASCII = /^[A-Za-z0-9 !'()+,\-./=?[\]{}:;_]$/;
const LEAN_MATH = /^[⊢∀∃∈∉∧∨¬→↔←≤≥≠⟨⟩·▸×…′─]$/;
const GREEK = /^[\u0391-\u03A9\u03B1-\u03C9]$/;
const SUB_SUPER =
/^[\u2080-\u208E\u2090-\u209C\u1D62-\u1D6A\u2070\u00B9\u00B2\u00B3\u2074-\u2079]$/;
const WHITE = /\p{White_Space}/u;
const PLACEHOLDER = /[fl°¶ß]/;
const isControl = (code: number): boolean => code <= 0x1f || (code >= 0x7f && code <= 0x9f);
const DIRECTION = /(direction)\s+(?=LR|RL|TB|BT|TD)/gi;
const C4 = /C4(?=Container|Component|Dynamic|Deployment)/g;
function isSafeChar(ch: string): boolean {
if (PLACEHOLDER.test(ch)) return false;
return SAFE_ASCII.test(ch) || LEAN_MATH.test(ch) || GREEK.test(ch) || SUB_SUPER.test(ch);
}
export function encodeText(text: string): string {
let out = "";
for (let i = 0; i < text.length;) {
const code = text.codePointAt(i)!;
const width = code > 0xffff ? 2 : 1;
i += width;
if (code >= 0xd800 && code <= 0xdfff) {
out += "#65533;";
continue;
}
const ch = String.fromCodePoint(code);
if (ch === " ") {
out += " ";
} else if (WHITE.test(ch)) {
out += " ";
} else if (isControl(code)) {
continue;
} else if (isSafeChar(ch)) {
out += ch;
} else {
out += `#${code};`;
}
}
const normalized = out.replace(/ +/g, " ").trim();
if (!normalized) return "#32;";
return normalized
.replace(/\[(?=\[)/g, "#91;")
.replace(/\](?=\])/g, "#93;")
.replace(/-(?=-)/g, "#45;")
.replace(DIRECTION, "$1#32;")
.replace(C4, "C#52;");
}
export function encodeLines(lines: readonly string[]): string {
const encoded = lines.map(encodeText).filter((line) => line.length > 0);
if (encoded.length === 0) return "#32;";
return encoded.join("
");
}
function encodeTitle(title: string): string {
let out = "";
for (let i = 0; i < title.length;) {
const code = title.codePointAt(i)!;
const width = code > 0xffff ? 2 : 1;
i += width;
if (code >= 0xd800 && code <= 0xdfff) continue;
const ch = String.fromCodePoint(code);
if (WHITE.test(ch)) out += " ";
else if (isControl(code) || PLACEHOLDER.test(ch)) continue;
else if (ch === "<" || ch === ">" || ch === "&" || ch === '"' || ch === "\\") out += " ";
else out += ch;
}
return out.replace(/ +/g, " ").trim();
}
function nodeDecl(node: FlowNode): string {
const label = `"${encodeLines(node.lines)}"`;
const shape: FlowShape = node.shape;
switch (shape) {
case "box":
return `${node.id}[${label}]`;
case "round":
return `${node.id}(${label})`;
case "hexagon":
return `${node.id}{{${label}}}`;
case "circle":
return `${node.id}((${label}))`;
case "stub":
return `${node.id}([${label}])`;
default: {
const _exhaustive: never = shape;
return _exhaustive;
}
}
}
function edgeDecl(edge: FlowEdge): string {
const arrow = edge.thick ? "==>" : edge.dotted ? "-.->" : "-->";
if (edge.label === undefined) return `${edge.from} ${arrow} ${edge.to}`;
return `${edge.from} ${arrow}|"${encodeText(edge.label)}"| ${edge.to}`;
}
const CLASS_STYLES: Readonly> = {
target: "fill:#e8f2ff,stroke:#1680f3,stroke-width:2.5px,color:#0d4ea6",
goalRoot: "fill:#e8f2ff,stroke:#1680f3,stroke-width:2px,color:#0d4ea6",
subRoot: "fill:#eef2ff,stroke:#6366f1,stroke-width:2px,color:#3730a3",
termRoot: "fill:#f0fdfa,stroke:#0d9488,stroke-width:2px,color:#115e59",
closed: "fill:#e9f7ef,stroke:#229954,stroke-width:1.5px,color:#145a32",
sorry: "fill:#ffecee,stroke:#e72e3b,stroke-width:2.5px,color:#cd2834",
error: "fill:#ffecee,stroke:#e72e3b,stroke-width:2.5px,color:#cd2834",
open: "fill:#fff3e6,stroke:#e8730c,stroke-width:2.5px,color:#b85a06",
axiom: "fill:#fff3e6,stroke:#e8730c,stroke-width:2.5px,color:#b85a06",
native: "fill:#ffecee,stroke:#e72e3b,stroke-width:2.5px,color:#cd2834",
restsOn: "fill:#fff3e6,stroke:#e8730c,stroke-width:2.5px,color:#b85a06",
doubtPath: "stroke:#e72e3b,stroke-width:2.5px",
folded: "fill:#f3ecff,stroke:#8b5cf6,stroke-width:1.5px,color:#5b21b6",
stub: "fill:#f4f4f5,stroke:#71717a,stroke-width:1.5px,stroke-dasharray:5 3,color:#52525b",
note: "fill:#fafafa,stroke:#d4d4d8,stroke-width:1px,color:#52525b",
};
export function renderFlowLines(flow: Flow): string[] {
const lines: string[] = [];
if (flow.title) {
const safeTitle = encodeTitle(flow.title);
if (safeTitle) lines.push("---", `title: ${JSON.stringify(safeTitle)}`, "---");
}
lines.push("flowchart TD");
const grouped = new Set();
const nodeById = new Map();
for (const node of flow.nodes) nodeById.set(node.id, node);
for (const [i, group] of flow.groups.entries()) {
const members = group.nodes.filter((id) => nodeById.has(id) && !grouped.has(id));
if (members.length === 0) continue;
lines.push(` subgraph g${i} ["${encodeText(group.title)}"]`);
for (const id of members) {
grouped.add(id);
lines.push(` ${nodeDecl(nodeById.get(id)!)}`);
}
lines.push(" end");
}
for (const node of flow.nodes) {
if (!grouped.has(node.id)) lines.push(` ${nodeDecl(node)}`);
}
for (const edge of flow.edges) lines.push(` ${edgeDecl(edge)}`);
const usedClasses = new Set();
const classAssignments: string[] = [];
for (const node of flow.nodes) {
for (const cls of node.classes) {
usedClasses.add(cls);
classAssignments.push(` class ${node.id} ${cls}`);
}
}
if (flow.legend.length > 0) {
lines.push(` subgraph lg ["Legend"]`);
for (const [i, entry] of flow.legend.entries()) {
const lid = `lg${i}`;
lines.push(` ${lid}["${encodeText(entry.text)}"]`);
usedClasses.add(entry.cls);
classAssignments.push(` class ${lid} ${entry.cls}`);
}
lines.push(" end");
}
for (const cls of Object.keys(CLASS_STYLES)) {
if (usedClasses.has(cls)) lines.push(` classDef ${cls} ${CLASS_STYLES[cls]}`);
}
for (const line of classAssignments) lines.push(line);
return lines;
}
export const renderFlow = (flow: Flow): string => renderFlowLines(flow).join("\n");