Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ If your change is subsystem-specific, you MUST also read the relevant deep-dive

<!-- END:livemaid-architecture-rules -->

<!-- BEGIN:implementation-principles -->

# Implementation Principles

- Do not preserve backward compatibility. Remove obsolete paths instead of adding compatibility layers, fallbacks, or migrations.
- Choose the simplest implementation that fully meets the current requirements. Avoid speculative abstractions, configuration, and indirection.
- Grow the system in layers. Start from the smallest version that works end to end, and add each new capability on top of a product that already works. Never trade a working product for unfinished complexity.
- Keep components modular and concerns clearly separated.
- Prefer established, well-maintained libraries when they reduce overall complexity or improve reliability. Do not reimplement common functionality without a clear reason.
- Lean on the dependencies already in the project before writing your own implementation or adding packages. Do not assume a library lacks a capability without checking its documentation and types.
- Make architectural decisions for the long term. Do not accept a stopgap that only works for now and is meant to be replaced later.

<!-- END:implementation-principles -->

<!-- BEGIN:nextjs-agent-rules -->

# This is NOT the Next.js you know
Expand Down
121 changes: 24 additions & 97 deletions src/components/editor/EditorCodePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Editor, { type OnMount, type BeforeMount, type Monaco } from "@monaco-edi
import { useTheme } from "next-themes";
import { useCallback, useEffect, useRef } from "react";
import { registerMermaidLanguage } from "@/lib/diagrams/mermaidMonarch";
import { formatMermaidSource } from "@/lib/mermaid-format";
import { Copy, AlignLeft } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
Expand Down Expand Up @@ -93,107 +94,33 @@ export function EditorCodePanel({
}, [code]);

const handleFormat = useCallback(() => {
const INDENT = " ";
const BLOCK_OPEN = new Set([
"subgraph",
"loop",
"alt",
"opt",
"par",
"critical",
"break",
"rect",
]);
const BLOCK_SAME = new Set(["else", "and", "option"]);
const BLOCK_CLOSE = "end";

const lines = code.split("\n");

// Extract and preserve YAML front matter (--- … ---) at the start.
let frontMatterLines: string[] = [];
let bodyStartIndex = 0;
if (lines.length > 0 && lines[0].trim() === "---") {
const endIndex = lines.findIndex((l, i) => i > 0 && l.trim() === "---");
if (endIndex > 0) {
frontMatterLines = lines.slice(0, endIndex + 1);
bodyStartIndex = endIndex + 1;
// Skip blank lines between front matter and body.
while (bodyStartIndex < lines.length && lines[bodyStartIndex].trim() === "") {
bodyStartIndex++;
}
}
}
const bodyLines = lines.slice(bodyStartIndex);

// Pass 1: trim trailing whitespace on every line.
const trimmed = bodyLines.map((l) => l.replace(/\s+$/, ""));

// Pass 2: collapse consecutive blank lines, keep leading/trailing blanks.
const collapsed: string[] = [];
let prevBlank = false;
for (const line of trimmed) {
const isBlank = line.trim() === "";
if (isBlank && prevBlank) continue;
collapsed.push(line);
prevBlank = isBlank;
}
while (collapsed.length > 0 && collapsed[0].trim() === "") collapsed.shift();
while (collapsed.length > 0 && collapsed[collapsed.length - 1].trim() === "") collapsed.pop();

// Pass 3: re-indent based on block depth.
let depth = 0;
const reformatted: string[] = [];
for (const rawLine of collapsed) {
const stripped = rawLine.trim();
if (stripped === "") {
reformatted.push("");
continue;
}

// Extract the first keyword (case-insensitive).
const firstWord = stripped.split(/\s+/)[0].toLowerCase();

// "end" closes a block — outdent BEFORE printing.
if (firstWord === BLOCK_CLOSE) {
depth = Math.max(0, depth - 1);
reformatted.push(INDENT.repeat(depth) + stripped);
continue;
}

// "else", "and", "option" are at the SAME level as their parent block.
if (BLOCK_SAME.has(firstWord)) {
reformatted.push(INDENT.repeat(Math.max(0, depth - 1)) + stripped);
continue;
try {
const result = formatMermaidSource(code);
if (result.status === "unchanged") {
toast.info("Already formatted");
return;
}

// Normal line — print at current depth.
reformatted.push(INDENT.repeat(depth) + stripped);

// If this line opens a block, increase depth for subsequent lines.
if (BLOCK_OPEN.has(firstWord)) {
depth++;
const editor = editorRef.current;
if (editor) {
const model = editor.getModel();
if (model) {
editor.pushUndoStop();
editor.executeEdits("format", [
{ range: model.getFullModelRange(), text: result.formatted, forceMoveMarkers: true },
]);
editor.pushUndoStop();
}
}
}

const bodyFormatted = reformatted.join("\n");
const frontMatter = frontMatterLines.length > 0 ? frontMatterLines.join("\n") + "\n" : "";
const formatted = frontMatter + bodyFormatted;
if (formatted === code) {
toast.info("Already formatted");
return;
}
const editor = editorRef.current;
if (editor) {
const model = editor.getModel();
if (model) {
editor.pushUndoStop();
editor.executeEdits("format", [
{ range: model.getFullModelRange(), text: formatted, forceMoveMarkers: true },
]);
handleCodeChange(result.formatted);
if (result.skippedIndentSensitive) {
toast.info(`Structural formatting skipped for ${result.diagramType} (indent is semantic)`);
} else {
toast.success("Code formatted");
}
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
toast.error(`Formatting failed: ${message}`);
}
handleCodeChange(formatted);
toast.success("Code formatted");
}, [code, handleCodeChange]);

return (
Expand Down
229 changes: 229 additions & 0 deletions src/lib/mermaid-format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
import { determineDiagramType } from "@/lib/diagrams/utils";

export type MermaidFormatStatus = "changed" | "unchanged";

export type MermaidFormatResult = {
formatted: string;
status: MermaidFormatStatus;
diagramType: string;
skippedIndentSensitive?: boolean;
};

const DEFAULT_INDENT = " ";

const BLOCK_OPEN = new Set([
"subgraph",
"box",
"loop",
"alt",
"opt",
"par",
"critical",
"break",
"rect",
]);

const BLOCK_SAME = new Set(["else", "and", "option"]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const INDENT_SENSITIVE = new Set(["mindmap", "timeline"]);

const BRACE_KEYWORD_OPEN = /^(?:class|state|namespace)\s+\S[\s\S]*\{\s*$/i;

/** ER entity bodies and similar: `CUSTOMER {` / `ORDER {` */
const BRACE_GENERIC_OPEN = /^[A-Za-z_][\w-]*\s*\{\s*$/;

const DIAGRAM_DECLARATIONS = new Set([
"flowchart",
"flowchart-elk",
"graph",
"sequencediagram",
"classdiagram",
"classdiagram-v2",
"erdiagram",
"statediagram",
"statediagram-v2",
"gitgraph",
"requirementdiagram",
"gantt",
"pie",
"journey",
"mindmap",
"timeline",
"quadrantchart",
"sankey",
"sankey-beta",
"xychart",
"xychart-beta",
"block",
"block-beta",
"architecture-beta",
"kanban",
"packet",
"packet-beta",
"radar",
"radar-beta",
"treemap",
"treemap-beta",
"zenuml",
"c4context",
"c4container",
"c4component",
"c4dynamic",
"c4deployment",
]);

function isBraceOpen(stripped: string): boolean {
return BRACE_KEYWORD_OPEN.test(stripped) || BRACE_GENERIC_OPEN.test(stripped);
}

function extractFrontMatter(lines: string[]): {
frontMatterLines: string[];
bodyStartIndex: number;
} {
if (lines.length === 0 || lines[0].trim() !== "---") {
return { frontMatterLines: [], bodyStartIndex: 0 };
}
const endIndex = lines.findIndex((l, i) => i > 0 && l.trim() === "---");
if (endIndex <= 0) {
return { frontMatterLines: [], bodyStartIndex: 0 };
}
let bodyStartIndex = endIndex + 1;
while (bodyStartIndex < lines.length && lines[bodyStartIndex].trim() === "") {
bodyStartIndex++;
}
return {
frontMatterLines: lines.slice(0, endIndex + 1),
bodyStartIndex,
};
}

function collapseBlankLines(lines: string[]): string[] {
const collapsed: string[] = [];
let prevBlank = false;
for (const line of lines) {
const isBlank = line.trim() === "";
if (isBlank && prevBlank) continue;
collapsed.push(line);
prevBlank = isBlank;
}
while (collapsed.length > 0 && collapsed[0].trim() === "") collapsed.shift();
while (collapsed.length > 0 && collapsed[collapsed.length - 1].trim() === "") {
collapsed.pop();
}
return collapsed;
}

function isDiagramDeclaration(stripped: string): boolean {
if (!stripped || stripped.startsWith("%%")) return false;
const firstWord = stripped.split(/\s+/)[0].toLowerCase();
return DIAGRAM_DECLARATIONS.has(firstWord);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
* Light cleanup for indent-sensitive diagrams: trim trailing whitespace and
* collapse blank lines without changing leading indentation of content.
*/
function lightCleanupPreserveIndent(bodyLines: string[]): string[] {
const trimmed = bodyLines.map((l) => l.replace(/\s+$/, ""));
return collapseBlankLines(trimmed);
}

function formatBody(bodyLines: string[], indentUnit: string): string[] {
const trimmed = bodyLines.map((l) => l.replace(/\s+$/, ""));
const collapsed = collapseBlankLines(trimmed);

let endBlockDepth = 0;
let braceDepth = 0;
let seenDiagramDecl = false;
const reformatted: string[] = [];

for (const rawLine of collapsed) {
const stripped = rawLine.trim();
if (stripped === "") {
reformatted.push("");
continue;
}

// Directives stay at column 0.
if (stripped.startsWith("%%{")) {
reformatted.push(stripped);
continue;
}

const firstWord = stripped.split(/\s+/)[0].toLowerCase();
const isDecl = isDiagramDeclaration(stripped);

if (stripped === "}") {
braceDepth = Math.max(0, braceDepth - 1);
} else if (firstWord === "end") {
endBlockDepth = Math.max(0, endBlockDepth - 1);
}

let depth: number;
if (isDecl) {
depth = 0;
} else {
const base = seenDiagramDecl ? 1 : 0;
if (BLOCK_SAME.has(firstWord)) {
depth = base + braceDepth + Math.max(0, endBlockDepth - 1);
} else if (stripped === "}") {
depth = base + braceDepth;
} else {
depth = base + braceDepth + endBlockDepth;
}
}

reformatted.push(indentUnit.repeat(depth) + stripped);

if (isDecl) {
seenDiagramDecl = true;
}
if (isBraceOpen(stripped)) {
braceDepth++;
} else if (BLOCK_OPEN.has(firstWord)) {
endBlockDepth++;
}
}

return reformatted;
}

/**
* Format Mermaid source for LiveMaid's editor Format action.
* Preserves YAML front matter. Indent-sensitive diagrams (mindmap/timeline) get
* light cleanup only and report `skippedIndentSensitive` so callers can explain
* that structural re-indentation is skipped.
*/
export function formatMermaidSource(
code: string,
options?: { indent?: string },
): MermaidFormatResult {
const indentUnit = options?.indent ?? DEFAULT_INDENT;
const diagramType = determineDiagramType(code);
const lines = code.split("\n");
const { frontMatterLines, bodyStartIndex } = extractFrontMatter(lines);
const bodyLines = lines.slice(bodyStartIndex);
const frontMatter = frontMatterLines.length > 0 ? frontMatterLines.join("\n") + "\n" : "";
const trailingNewline = code.endsWith("\n");
const newlineSuffix = trailingNewline ? "\n" : "";

if (INDENT_SENSITIVE.has(diagramType)) {
const cleaned = lightCleanupPreserveIndent(bodyLines);
const formatted = frontMatter + cleaned.join("\n") + newlineSuffix;
return {
formatted,
status: formatted === code ? "unchanged" : "changed",
diagramType,
skippedIndentSensitive: true,
};
}

const reformatted = formatBody(bodyLines, indentUnit);
const formatted = frontMatter + reformatted.join("\n") + newlineSuffix;

return {
formatted,
status: formatted === code ? "unchanged" : "changed",
diagramType,
};
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Loading
Loading