Schema Diagram
Shows tables as cards, fields as rows, and links as lines between them. New, changed, and removed fields are marked so someone can review a proposed schema before it is applied. Tables sit in columns on wide screens and stack on phones.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/schema-diagram.jsonCopies Schema Diagram and the components it uses (Badge and Button) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/schema-diagram. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @hugeicons/core-free-icons @hugeicons/react @xyflow/reactAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Copy and paste the following code into your project.
'use client'; import { Background, BaseEdge, EdgeLabelRenderer, getSmoothStepPath, Handle, Position, ReactFlow, ReactFlowProvider, type Edge, type EdgeProps, type Node, type NodeProps, } from '@xyflow/react'; import { useId, useMemo, type HTMLAttributes } from 'react'; import { KeyIcon } from '@/lib/sprout/icons/key-icon'; import { cn } from '@/lib/sprout/classes'; import { FitOnResize, flowMaxZoom as maxZoom, flowMinZoom as minZoom, useKeyboardView, useViewportMobile, ZoomControls, } from '@/lib/sprout/flow'; import { Badge, type BadgeVariant } from '@/components/ui/badge'; export const schemaTableStateNames = ['new', 'changed', 'unchanged', 'linked'] as const; export const schemaChangeNames = ['added', 'changed', 'removed'] as const; export const schemaDiagramLayoutNames = ['auto', 'horizontal', 'vertical'] as const; export type SchemaTableState = (typeof schemaTableStateNames)[number]; export type SchemaChange = (typeof schemaChangeNames)[number]; export type SchemaDiagramLayout = (typeof schemaDiagramLayoutNames)[number]; export interface SchemaField { id: string; label: string; type: string; required: boolean; unique?: boolean | undefined; detail?: string | undefined; change?: SchemaChange | undefined; } export interface SchemaTable { id: string; label: string; state: SchemaTableState; fields: SchemaField[]; } export interface SchemaLink { id: string; source: string; field: string; target: string; label: string; } type Direction = 'horizontal' | 'vertical'; type TableNode = Node<{ table: SchemaTable; direction: Direction }, 'table'>; type LinkEdge = Edge<{ label: string }, 'link'>; const tableWidth = 264; const columnGap = 80; const rowGap = 48; const fitOptions = { padding: '6.5%', maxZoom: 1 } as const; const tableHeight = (table: SchemaTable) => 44 + (table.fields.length === 0 ? 32 : table.fields.reduce((sum, field) => sum + (field.detail ? 48 : 32), 0)); const stateBadge: Record<SchemaTableState, { label: string; variant: BadgeVariant } | null> = { new: { label: 'New', variant: 'success' }, changed: { label: 'Changed', variant: 'warning' }, linked: { label: 'Existing', variant: 'secondary' }, unchanged: null, }; function layout(tables: readonly SchemaTable[], links: readonly SchemaLink[], direction: Direction): TableNode[] { const node = (table: SchemaTable, x: number, y: number): TableNode => ({ id: table.id, type: 'table', position: { x, y }, data: { table, direction }, ariaRole: 'group', ariaLabel: `${table.label} table`, domAttributes: { 'aria-roledescription': 'table card' }, sourcePosition: direction === 'vertical' ? Position.Bottom : Position.Right, targetPosition: direction === 'vertical' ? Position.Top : Position.Left, }); if (direction === 'vertical') { const ordered: SchemaTable[] = []; const seen = new Set<string>(); const add = (table: SchemaTable | undefined) => { if (table && !seen.has(table.id)) { ordered.push(table); seen.add(table.id); } }; for (const link of links) for (const id of [link.source, link.target]) add(tables.find(table => table.id === id)); for (const table of tables) add(table); let y = 0; return ordered.map(table => { const placed = node(table, 0, y); y += tableHeight(table) + rowGap; return placed; }); } const depth = new Map(tables.map(table => [table.id, 0])); for (let pass = 0; pass < tables.length; pass++) { let moved = false; for (const link of links) { const next = (depth.get(link.source) ?? 0) + 1; if (link.source !== link.target && next > (depth.get(link.target) ?? 0) && next < tables.length) { depth.set(link.target, next); moved = true; } } if (!moved) break; } const columns = new Map<number, number>(); return tables.map(table => { const column = depth.get(table.id) ?? 0; const y = columns.get(column) ?? 0; columns.set(column, y + tableHeight(table) + rowGap); return node(table, column * (tableWidth + columnGap), y); }); } function TableCard({ data: { table, direction } }: NodeProps<TableNode>) { const badge = stateBadge[table.state]; const vertical = direction === 'vertical'; return ( <section data-slot="schema-table" data-state={table.state} className="sprout-schema-table"> <Handle type="target" position={vertical ? Position.Top : Position.Left} isConnectable={false} className="sprout-schema-handle sprout-schema-handle-target" /> <header className="sprout-schema-table-header"> <h3 className="sprout-schema-table-title" title={table.label}> {table.label} </h3> {badge && <Badge variant={badge.variant}>{badge.label}</Badge>} </header> {table.fields.length === 0 ? ( <p className="sprout-schema-table-empty">{table.state === 'linked' ? 'Fields not shown' : 'No fields'}</p> ) : ( <ul className="sprout-schema-fields"> {table.fields.map(field => ( <li key={field.id} data-slot="schema-field" data-change={field.change} className="sprout-schema-field"> <div className="sprout-schema-field-line"> <span className="sprout-schema-field-key"> {field.unique && <KeyIcon size="xs" aria-label="Unique" role="img" />} </span> <span className="sprout-schema-field-name" title={field.label}> {field.label} {field.required && ( <span className="sprout-schema-field-required"> <span aria-hidden="true"> *</span> <span className="sprout-schema-sr-only">, required</span> </span> )} </span> <span className="sprout-schema-field-type">{field.type}</span> {field.change && <span className="sprout-schema-sr-only">, {field.change}</span>} </div> {field.detail && ( <p className="sprout-schema-field-detail" title={field.detail}> {field.detail} </p> )} <Handle id={field.id} type="source" position={vertical ? Position.Bottom : Position.Right} isConnectable={false} className="sprout-schema-handle" /> </li> ))} </ul> )} </section> ); } function LinkLine({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, data, }: EdgeProps<LinkEdge>) { const [path, labelX, labelY] = getSmoothStepPath({ sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, borderRadius: 12, offset: 24, }); return ( <> <BaseEdge id={id} path={path} /> {data?.label && ( <EdgeLabelRenderer> <span aria-hidden="true" className="nodrag nopan sprout-schema-link-label" style={{ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`, }} > {data.label} </span> </EdgeLabelRenderer> )} </> ); } const nodeTypes = { table: TableCard }; const edgeTypes = { link: LinkLine }; const keyboardHint = 'Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.'; function DiagramFlow({ nodes, edges, direction, label, hintId, }: { nodes: TableNode[]; edges: LinkEdge[]; direction: Direction; label: string; hintId: string; }) { const onKeyDown = useKeyboardView(fitOptions); return ( <ReactFlow className="sprout-schema-flow" data-slot="schema-diagram-viewport" aria-label={label} aria-describedby={hintId} tabIndex={0} onKeyDown={onKeyDown} nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes} fitView fitViewOptions={fitOptions} minZoom={minZoom} maxZoom={maxZoom} nodesConnectable={false} elementsSelectable={false} edgesFocusable={false} ariaLabelConfig={{ 'node.a11yDescription.default': keyboardHint, 'node.a11yDescription.keyboardDisabled': keyboardHint, }} proOptions={{ hideAttribution: true }} > <Background gap={16} size={1} /> <FitOnResize nodes={nodes} fit={fitOptions} /> <ZoomControls position={direction === 'vertical' ? 'top-right' : 'bottom-right'} fit={fitOptions} className="sprout-schema-controls" slot="schema-diagram-controls" /> </ReactFlow> ); } export interface SchemaDiagramProps extends Omit<HTMLAttributes<HTMLDivElement>, 'role' | 'children'> { tables: readonly SchemaTable[]; links: readonly SchemaLink[]; label: string; layout?: SchemaDiagramLayout | undefined; } export function SchemaDiagram({ tables, links, label, layout: layoutName = 'auto', className, ...props }: SchemaDiagramProps) { const mobile = useViewportMobile(); const direction: Direction = layoutName === 'auto' ? (mobile ? 'vertical' : 'horizontal') : layoutName; const hintId = useId(); const nodes = useMemo(() => layout(tables, links, direction), [tables, links, direction]); const edges = useMemo(() => { const names = new Map(tables.map(table => [table.id, table])); return links.map((link): LinkEdge => { const source = names.get(link.source); const field = source?.fields.find(candidate => candidate.id === link.field); const from = `${source?.label ?? link.source}${field ? ` ${field.label}` : ''}`; return { id: link.id, type: 'link', source: link.source, sourceHandle: link.field, target: link.target, ariaLabel: `${from} links to ${names.get(link.target)?.label ?? link.target}: ${link.label}`, data: { label: link.label }, }; }); }, [tables, links]); return ( <div {...props} role="figure" aria-label={label} data-slot="schema-diagram" data-layout={direction} className={cn('sprout-schema-diagram', className)} > <p id={hintId} className="sprout-schema-sr-only"> {keyboardHint} </p> <ReactFlowProvider key={direction}> <DiagramFlow nodes={nodes} edges={edges} direction={direction} label={label} hintId={hintId} /> </ReactFlowProvider> </div> ); } export interface SchemaLegendProps extends Omit<HTMLAttributes<HTMLUListElement>, 'children'> {} export function SchemaLegend({ className, ...props }: SchemaLegendProps) { return ( <ul aria-label="Legend" data-slot="schema-legend" {...props} className={cn('sprout-schema-legend', className)}> {schemaChangeNames.map(change => ( <li key={change} className="sprout-schema-legend-item"> <span aria-hidden="true" data-change={change} className="sprout-schema-legend-swatch" /> {change[0]!.toUpperCase() + change.slice(1)} </li> ))} <li className="sprout-schema-legend-item"> <KeyIcon size="xs" aria-hidden="true" /> Unique </li> <li className="sprout-schema-legend-item">* Required</li> </ul> ); }And the files it imports:
lib/sprout/icons/add-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/key-icon.tsxlib/sprout/icons/minus-icon.tsxlib/sprout/icons/scan-icon.tsxlib/sprout/flow.tsx
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-schema-diagram { box-sizing: border-box; border: 1px solid var(--sprout-line); border-radius: var(--sprout-radius-panel); background: var(--sprout-canvas); width: 100%; min-width: 0; height: 100%; min-height: 24rem; color: var(--sprout-text); font-family: var(--sprout-font); flex: 1; display: flex; position: relative; overflow: hidden; } .sprout-schema-flow.light, .sprout-schema-flow.dark { --sprout-canvas: inherit; --sprout-surface: inherit; --sprout-hover: inherit; --sprout-active: inherit; --sprout-text: inherit; --sprout-muted: inherit; --sprout-line: inherit; --sprout-border: inherit; --sprout-border-strong: inherit; --sprout-input: inherit; --sprout-primary: inherit; --sprout-primary-hover: inherit; --sprout-primary-active: inherit; --sprout-primary-subtle: inherit; --sprout-on-primary: inherit; --sprout-focus: inherit; --sprout-danger: inherit; --sprout-danger-hover: inherit; --sprout-danger-subtle: inherit; --sprout-on-danger: inherit; --sprout-info: inherit; --sprout-info-subtle: inherit; --sprout-secondary: inherit; --sprout-success: inherit; --sprout-success-subtle: inherit; --sprout-warning: inherit; --sprout-warning-subtle: inherit; --sprout-overlay: inherit; } .sprout-schema-flow { direction: ltr; background: none; outline: none; flex: 1; width: 100%; height: 100%; min-height: 24rem; position: relative; overflow: hidden; } .sprout-schema-flow:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: -1px; border-radius: inherit; } .sprout-schema-flow .react-flow__container { width: 100%; height: 100%; position: absolute; top: 0; left: 0; } .sprout-schema-flow .react-flow__pane { z-index: 1; touch-action: none; } .sprout-schema-flow .react-flow__pane.draggable { cursor: grab; } .sprout-schema-flow .react-flow__pane.dragging { cursor: grabbing; } .sprout-schema-flow .react-flow__viewport { z-index: 2; transform-origin: 0 0; pointer-events: none; } .sprout-schema-flow .react-flow__renderer { z-index: 4; } .sprout-schema-flow .react-flow__background { z-index: -1; pointer-events: none; } .sprout-schema-flow .react-flow__background-pattern.dots { fill: var(--sprout-line); } .sprout-schema-flow .react-flow__edges { position: absolute; } .sprout-schema-flow .react-flow__edges svg { pointer-events: none; position: absolute; overflow: visible; } .sprout-schema-flow .react-flow__edge-path { fill: none; stroke: var(--sprout-muted); stroke-width: 1.25px; } .sprout-schema-flow .react-flow__edgelabel-renderer, .sprout-schema-flow .react-flow__viewport-portal { pointer-events: none; user-select: none; width: 100%; height: 100%; position: absolute; top: 0; left: 0; } .sprout-schema-flow .react-flow__nodes { transform-origin: 0 0; pointer-events: none; } .sprout-schema-flow .react-flow__node { box-sizing: border-box; transform-origin: 0 0; user-select: none; pointer-events: all; cursor: default; border-radius: 8px; outline: none; position: absolute; } .sprout-schema-flow .react-flow__node.draggable { cursor: grab; } .sprout-schema-flow .react-flow__node.dragging { cursor: grabbing; } .sprout-schema-flow .react-flow__node:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-schema-flow .react-flow__panel { z-index: 5; margin: 12px; position: absolute; } .sprout-schema-flow .react-flow__panel.top { top: 0; } .sprout-schema-flow .react-flow__panel.bottom { bottom: 0; } .sprout-schema-flow .react-flow__panel.right { right: 0; } .sprout-schema-flow .react-flow__panel.left { left: 0; } .sprout-schema-handle.react-flow__handle { opacity: 0; pointer-events: none; border: 0; width: 6px; min-width: 0; height: 6px; min-height: 0; position: absolute; } .sprout-schema-handle.react-flow__handle-left { top: 50%; left: 0; transform: translate(-50%, -50%); } .sprout-schema-handle.react-flow__handle-right { top: 50%; right: 0; transform: translate(50%, -50%); } .sprout-schema-handle.react-flow__handle-top { top: 0; left: 50%; transform: translate(-50%, -50%); } .sprout-schema-handle.react-flow__handle-bottom { bottom: 0; left: 50%; transform: translate(-50%, 50%); } .sprout-schema-handle-target.react-flow__handle-left { top: 22px; } .sprout-schema-table { box-sizing: border-box; border: 1px solid var(--sprout-line); background: var(--sprout-surface); width: 264px; color: var(--sprout-text); box-shadow: var(--sprout-shadow-control); border-top-width: 2px; border-radius: 8px; overflow: hidden; } .sprout-schema-table[data-state="new"] { border-top-color: var(--sprout-success); } .sprout-schema-table[data-state="changed"] { border-top-color: var(--sprout-warning); } .sprout-schema-table[data-state="linked"] { border-style: dashed; border-top-color: var(--sprout-line); } .react-flow__node.dragging .sprout-schema-table { box-shadow: var(--sprout-shadow-panel); } .sprout-schema-table-header { box-sizing: border-box; border-bottom: 1px solid var(--sprout-line); background: color-mix(in oklab, var(--sprout-hover) 45%, var(--sprout-surface)); align-items: center; gap: 8px; height: 44px; padding: 0 12px; display: flex; } .sprout-schema-table-title { min-width: 0; color: var(--sprout-text); font-size: var(--sprout-text-sm); text-overflow: ellipsis; white-space: nowrap; flex: 1; margin: 0; font-weight: 500; line-height: 1.25rem; overflow: hidden; } .sprout-schema-table-empty { color: var(--sprout-muted); font-size: var(--sprout-text-xs); margin: 0; padding: 8px 12px; line-height: 1rem; } .sprout-schema-fields { margin: 0; padding: 0; list-style: none; } .sprout-schema-field { border-bottom: 1px solid var(--sprout-line); padding: 6px 12px; position: relative; } .sprout-schema-field:last-child { border-bottom: 0; } .sprout-schema-field[data-change="added"] { background: var(--sprout-success-subtle); } .sprout-schema-field[data-change="changed"] { background: var(--sprout-warning-subtle); } .sprout-schema-field[data-change="removed"] { background: var(--sprout-danger-subtle); } .sprout-schema-field-line { align-items: center; gap: 8px; height: 20px; font-size: .8125rem; line-height: 1.25rem; display: flex; } .sprout-schema-field[data-change="removed"] .sprout-schema-field-line { text-decoration: line-through; } .sprout-schema-field-key { width: 12px; color: var(--sprout-muted); flex-shrink: 0; justify-content: center; display: flex; } .sprout-schema-field-name { min-width: 0; color: var(--sprout-text); text-overflow: ellipsis; white-space: nowrap; flex: 1; overflow: hidden; } .sprout-schema-field-required { color: var(--sprout-muted); } .sprout-schema-field-type { max-width: 45%; color: var(--sprout-muted); font-size: var(--sprout-text-xs); text-overflow: ellipsis; white-space: nowrap; flex-shrink: 0; overflow: hidden; } .sprout-schema-field-detail { color: var(--sprout-muted); font-size: var(--sprout-text-xs); text-overflow: ellipsis; white-space: nowrap; margin: 0; padding-left: 20px; line-height: 1rem; overflow: hidden; } .sprout-schema-link-label { box-sizing: border-box; border: 1px solid var(--sprout-line); background: var(--sprout-surface); max-width: 180px; color: var(--sprout-muted); font-family: var(--sprout-font); font-size: var(--sprout-text-xs); text-overflow: ellipsis; white-space: nowrap; pointer-events: none; border-radius: 6px; padding: 0 6px; line-height: 1rem; position: absolute; overflow: hidden; } .sprout-schema-controls { border: 1px solid var(--sprout-line); background: var(--sprout-surface); box-shadow: var(--sprout-shadow-control); border-radius: 8px; flex-direction: column; gap: 2px; padding: 2px; display: flex; } .sprout-schema-legend { color: var(--sprout-muted); font-family: var(--sprout-font); font-size: var(--sprout-text-xs); flex-wrap: wrap; align-items: center; gap: 4px 16px; margin: 0; padding: 0; line-height: 1rem; list-style: none; display: flex; } .sprout-schema-legend-item { align-items: center; gap: 6px; display: flex; } .sprout-schema-legend-swatch { border-radius: 2px; flex-shrink: 0; width: 10px; height: 10px; } .sprout-schema-legend-swatch[data-change="added"] { background: var(--sprout-success-subtle); box-shadow: 0 0 0 1px var(--sprout-success); } .sprout-schema-legend-swatch[data-change="changed"] { background: var(--sprout-warning-subtle); box-shadow: 0 0 0 1px var(--sprout-warning); } .sprout-schema-legend-swatch[data-change="removed"] { background: var(--sprout-danger-subtle); box-shadow: 0 0 0 1px var(--sprout-danger); } .sprout-schema-sr-only { clip-path: inset(50%); white-space: nowrap; border: 0; width: 1px; height: 1px; margin: -1px; padding: 0; position: absolute; overflow: hidden; } @media (prefers-reduced-motion: no-preference) { .sprout-schema-table { transition: box-shadow var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-schema-flow .react-flow__node { transition: outline-color var(--sprout-motion-fast) ease-out; } } }Import it from
@/components/ui/schema-diagram. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/schema-diagram.
Sales pipeline
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.
- Added
- Changed
- Removed
- Unique
- * Required
Usage
import { SchemaDiagram, SchemaLegend } from "@tulipfarm/sprout/schema-diagram";
const tables = [
{
id: "deals",
label: "Deals",
state: "new",
fields: [
{ id: "title", label: "Title", type: "text", required: true, unique: true },
{ id: "stage", label: "Stage", type: "select", required: true, detail: "Qualified · Won · Lost" },
{ id: "customer", label: "Customer", type: "link", required: true },
],
},
{
id: "customers",
label: "Customers",
state: "changed",
fields: [
{ id: "email", label: "Billing email", type: "text", required: true, change: "added" },
{ id: "fax", label: "Fax number", type: "text", required: false, change: "removed" },
],
},
];
const links = [
{ id: "customer", source: "deals", field: "customer", target: "customers", label: "N:1" },
];
<SchemaDiagram tables={tables} links={links} label="Schema diagram for Sales pipeline" />
<SchemaLegend />The diagram fills its parent and is at least 24rem tall. Give the parent a height, such as h-128, to show more.
Table states and field changes
state is new, changed, linked (an existing table shown only because a link points to it), or unchanged. A field's change is added, changed, or removed. Required fields show *, unique fields show a key, and detail adds a second line such as select options.
- Added
- Changed
- Removed
- Unique
- * Required
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.
Layouts
layout="auto" uses columns from 768px up and a stack below it. Columns place each linked table one step right of the table that links to it. The stack follows link order. Pass horizontal orvertical to fix the layout.
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.
Content and overflow
Cards are 264px wide. Long table names, field names, and details truncate, and hovering shows the full text. A linked table with no fields reads "Fields not shown"; any other empty table reads "No fields". Links can point back to their own table.
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables.
Props
tables:SchemaTable[]withid,label,state, andfields.links:SchemaLink[]from asourcetable'sfieldto atargettable, with a shortlabelsuch asN:1.label: the accessible name of the diagram.layout:auto(default),horizontal, orvertical.SchemaLegendrenders a labelled list and takes the props of aul.
Keyboard and accessibility
Tab moves to the diagram, then to each table card, then to the zoom controls. With the diagram or a card focused, the arrow keys pan (hold Shift to move faster), + and - zoom, and 0fits everything in view. Each card is a named group, each link is described as "Deals Customer links to Customers: N:1", and changes, required fields, and unique keys have text for screen readers, not only color. Zoom and pan animate for 120–180ms and stop animating when reduced motion is requested.
Loading, load errors, removed proposals, and approval status belong to your application. The playground above shows them with sample data.
Theme tokens
Uses --sprout-surface, --sprout-canvas, --sprout-line, --sprout-text, --sprout-muted, and the --sprout-success, --sprout-warning, and --sprout-danger pairs. Badges for table state use the Badge tokens.