feat(frontend): schema-linking viewer (mermaid+table) + markdown view
TDD: SchemaLinkingViewer with mocked renderMermaid, toggle flowchart↔table, ≤45 element cap with Italian notice. MarkdownView renders mermaid fences. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Generated
+2524
-10
File diff suppressed because it is too large
Load Diff
@@ -17,9 +17,12 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"mermaid": "^11.16.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import type { Components } from "react-markdown";
|
||||
import { renderMermaid } from "./mermaid";
|
||||
|
||||
function MermaidBlock({ code }: { code: string }) {
|
||||
const [svg, setSvg] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
renderMermaid(code)
|
||||
.then(setSvg)
|
||||
.catch((e: unknown) =>
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
);
|
||||
}, [code]);
|
||||
|
||||
if (error) return <pre className="text-red-500 text-xs">{error}</pre>;
|
||||
if (!svg) return <pre className="text-xs opacity-50">{code}</pre>;
|
||||
// eslint-disable-next-line react/no-danger
|
||||
return <div dangerouslySetInnerHTML={{ __html: svg }} />;
|
||||
}
|
||||
|
||||
const components: Components = {
|
||||
code({ className, children }) {
|
||||
const lang = /language-(\w+)/.exec(className ?? "")?.[1];
|
||||
const code = String(children).replace(/\n$/, "");
|
||||
if (lang === "mermaid") {
|
||||
return <MermaidBlock code={code} />;
|
||||
}
|
||||
return (
|
||||
<code className={className}>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
},
|
||||
pre({ children }) {
|
||||
return <pre className="overflow-auto rounded bg-muted p-3 text-sm">{children}</pre>;
|
||||
},
|
||||
};
|
||||
|
||||
export function MarkdownView({ source }: { source: string }) {
|
||||
return (
|
||||
<div className="markdown-view overflow-auto max-h-[60vh] prose prose-sm dark:prose-invert p-3">
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
|
||||
{source}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { SchemaLinkingViewer } from "./SchemaLinkingViewer";
|
||||
|
||||
vi.mock("./mermaid", () => ({
|
||||
renderMermaid: vi.fn().mockResolvedValue('<svg data-testid="mm"></svg>'),
|
||||
}));
|
||||
|
||||
const smallLinking = {
|
||||
question: "quante ordini?",
|
||||
candidates: [
|
||||
{ kind: "table" as const, name: "orders", decision: "promoted" as const },
|
||||
{ kind: "column" as const, name: "orders.id", decision: "promoted" as const },
|
||||
{ kind: "table" as const, name: "users", decision: "excluded" as const },
|
||||
],
|
||||
joins: [{ from: "orders", to: "orders.id" }],
|
||||
excluded: [{ kind: "table" as const, name: "users" }],
|
||||
open_questions: [],
|
||||
};
|
||||
|
||||
const bigLinking = {
|
||||
question: "grossa query",
|
||||
candidates: Array.from({ length: 46 }, (_, i) => ({
|
||||
kind: "table" as const,
|
||||
name: `table_${i}`,
|
||||
decision: "promoted" as const,
|
||||
})),
|
||||
joins: [],
|
||||
excluded: [],
|
||||
open_questions: [],
|
||||
};
|
||||
|
||||
test("(a) default renders the mermaid container (mocked svg appears)", async () => {
|
||||
render(<SchemaLinkingViewer linking={smallLinking} />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("mm")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
test("(b) clicking toggle switches to table listing a promoted table name", async () => {
|
||||
render(<SchemaLinkingViewer linking={smallLinking} />);
|
||||
// wait for mermaid to load
|
||||
await waitFor(() => expect(screen.getByTestId("mm")).toBeInTheDocument());
|
||||
|
||||
const toggle = screen.getByRole("button", { name: /tabella/i });
|
||||
await userEvent.click(toggle);
|
||||
|
||||
expect(screen.getByText("orders")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("mm")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("(c) oversized linking (>45) shows cap notice", () => {
|
||||
render(<SchemaLinkingViewer linking={bigLinking} />);
|
||||
expect(
|
||||
screen.getByText(/troppi elementi per il grafico/i)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { renderMermaid } from "./mermaid";
|
||||
|
||||
const CAP = 45;
|
||||
|
||||
export interface Candidate {
|
||||
kind: "table" | "column";
|
||||
name: string;
|
||||
decision: "promoted" | "excluded" | "pending";
|
||||
signals?: Record<string, unknown>;
|
||||
evidence?: string[];
|
||||
}
|
||||
|
||||
export interface Join {
|
||||
from: string;
|
||||
to: string;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface SchemaLinking {
|
||||
question?: string;
|
||||
candidates: Candidate[];
|
||||
joins: Join[];
|
||||
excluded: { kind: string; name: string }[];
|
||||
open_questions: string[];
|
||||
}
|
||||
|
||||
function buildFlowchart(candidates: Candidate[], joins: Join[]): string {
|
||||
const promoted = candidates.filter((c) => c.decision === "promoted");
|
||||
const nodeId = (name: string) => name.replace(/[^a-zA-Z0-9]/g, "_");
|
||||
|
||||
const lines: string[] = ["flowchart TB"];
|
||||
|
||||
for (const c of promoted) {
|
||||
const id = nodeId(c.name);
|
||||
const tooltip = c.evidence?.length
|
||||
? ` %% ${c.evidence[0]}`
|
||||
: c.signals && Object.keys(c.signals).length
|
||||
? ` %% ${Object.keys(c.signals).join(", ")}`
|
||||
: "";
|
||||
const shape = c.kind === "table" ? `[${c.name}]` : `(${c.name})`;
|
||||
lines.push(` ${id}${shape}${tooltip}`);
|
||||
}
|
||||
|
||||
const promotedNames = new Set(promoted.map((c) => c.name));
|
||||
for (const j of joins) {
|
||||
if (promotedNames.has(j.from) && promotedNames.has(j.to)) {
|
||||
lines.push(` ${nodeId(j.from)} --> ${nodeId(j.to)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function buildHierarchicalRows(candidates: Candidate[]) {
|
||||
const promoted = candidates.filter((c) => c.decision === "promoted");
|
||||
const tables = promoted.filter((c) => c.kind === "table");
|
||||
const columns = promoted.filter((c) => c.kind === "column");
|
||||
|
||||
// Group columns under their table (column name format: "table.column")
|
||||
const grouped: { table: Candidate; columns: Candidate[] }[] = tables.map(
|
||||
(t) => ({
|
||||
table: t,
|
||||
columns: columns.filter((col) => col.name.startsWith(t.name + ".")),
|
||||
})
|
||||
);
|
||||
|
||||
// Orphan columns not attached to any promoted table
|
||||
const attachedCols = new Set(
|
||||
grouped.flatMap((g) => g.columns.map((c) => c.name))
|
||||
);
|
||||
const orphans = columns.filter((c) => !attachedCols.has(c.name));
|
||||
|
||||
return { grouped, orphans };
|
||||
}
|
||||
|
||||
export function SchemaLinkingViewer({ linking }: { linking: SchemaLinking }) {
|
||||
const oversized = linking.candidates.length > CAP;
|
||||
const [view, setView] = useState<"chart" | "table">(
|
||||
oversized ? "table" : "chart"
|
||||
);
|
||||
const [svg, setSvg] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== "chart" || oversized) return;
|
||||
let cancelled = false;
|
||||
const def = buildFlowchart(linking.candidates, linking.joins);
|
||||
renderMermaid(def).then((s) => {
|
||||
if (!cancelled) setSvg(s);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [view, linking, oversized]);
|
||||
|
||||
const { grouped, orphans } = buildHierarchicalRows(linking.candidates);
|
||||
|
||||
return (
|
||||
<div className="schema-linking-viewer">
|
||||
<div className="flex gap-2 mb-2">
|
||||
<button
|
||||
onClick={() => setView("chart")}
|
||||
disabled={oversized}
|
||||
className={view === "chart" ? "font-bold" : ""}
|
||||
>
|
||||
Grafico
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setView("table")}
|
||||
className={view === "table" ? "font-bold" : ""}
|
||||
>
|
||||
Tabella
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{oversized && (
|
||||
<p className="text-sm text-amber-600">
|
||||
Troppi elementi per il grafico, usa la tabella
|
||||
</p>
|
||||
)}
|
||||
|
||||
{view === "chart" && !oversized && (
|
||||
<div
|
||||
className="mermaid-container overflow-auto"
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{ __html: svg }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{view === "table" && (
|
||||
<table className="w-full text-sm border-collapse">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left border-b py-1">Nome</th>
|
||||
<th className="text-left border-b py-1">Tipo</th>
|
||||
<th className="text-left border-b py-1">Perché</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{grouped.map(({ table, columns: cols }) => (
|
||||
<React.Fragment key={table.name}>
|
||||
<tr className="font-semibold bg-muted/30">
|
||||
<td className="py-1 pl-1">{table.name}</td>
|
||||
<td>tabella</td>
|
||||
<td className="text-xs text-muted-foreground">
|
||||
{table.evidence?.[0] ?? ""}
|
||||
</td>
|
||||
</tr>
|
||||
{cols.map((col) => (
|
||||
<tr key={col.name} className="pl-4">
|
||||
<td className="py-0.5 pl-4 text-muted-foreground">
|
||||
{col.name}
|
||||
</td>
|
||||
<td>colonna</td>
|
||||
<td className="text-xs text-muted-foreground">
|
||||
{col.evidence?.[0] ?? ""}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</React.Fragment>
|
||||
))}
|
||||
{orphans.map((col) => (
|
||||
<tr key={col.name}>
|
||||
<td className="py-0.5 pl-1 text-muted-foreground">
|
||||
{col.name}
|
||||
</td>
|
||||
<td>colonna</td>
|
||||
<td className="text-xs text-muted-foreground">
|
||||
{col.evidence?.[0] ?? ""}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
let _initialized = false;
|
||||
|
||||
export async function renderMermaid(def: string): Promise<string> {
|
||||
const mermaid = (await import("mermaid")).default;
|
||||
if (!_initialized) {
|
||||
mermaid.initialize({ startOnLoad: false, theme: "default" });
|
||||
_initialized = true;
|
||||
}
|
||||
const id = `mermaid-${Math.random().toString(36).slice(2)}`;
|
||||
const { svg } = await mermaid.render(id, def);
|
||||
return svg;
|
||||
}
|
||||
Reference in New Issue
Block a user