SQL Viewer
Shows TulipFarm tables as SQL: one card per table, one row per column, and a line for each join. Hover or click a table or a foreign key to light up its joins. Up to four tables show at once; the rest wait behind a "+N tables" card.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/sql-viewer.jsonCopies SQL Viewer and the components it uses (Button) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/sql-viewer. 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
Add the components it uses: Button.
Copy and paste the following code into your project.
'use client'; import { Background, getSmoothStepPath, Handle, Panel, Position, ReactFlow, ReactFlowProvider, useInternalNode, useNodesState, type Edge, type EdgeProps, type FitViewOptions, type InternalNode, type Node, type NodeMouseHandler, type NodeProps, } from '@xyflow/react'; import { createContext, useCallback, useContext, useEffect, useId, useMemo, useState, type FocusEvent, type HTMLAttributes, type KeyboardEvent, } from 'react'; import { FingerprintIcon } from '@/lib/sprout/icons/fingerprint-icon'; import { KeyIcon } from '@/lib/sprout/icons/key-icon'; import { LayersIcon } from '@/lib/sprout/icons/layers-icon'; import { LinkIcon } from '@/lib/sprout/icons/link-icon'; import { cn } from '@/lib/sprout/classes'; import { FitOnResize, flowMaxZoom, flowMinZoom, useKeyboardView, useViewportMobile, ZoomControls, } from '@/lib/sprout/flow'; import { Button } from '@/components/ui/button'; export const sqlViewerLayoutNames = ['auto', 'horizontal', 'vertical'] as const; export type SqlViewerLayout = (typeof sqlViewerLayoutNames)[number]; export type SqlViewerCardinality = 'one' | 'many'; export interface SqlViewerOption { id: string; label: string; retired: boolean; } export type SqlViewerField = { id: string; label: string; required: boolean; } & ( | { kind: 'text'; maxLength: number } | { kind: 'numeric'; precision: number; scale: number } | { kind: 'boolean' } | { kind: 'date' } | { kind: 'timestamp'; timezone?: 'UTC' } | { kind: 'single-select' | 'multi-select'; options: readonly SqlViewerOption[]; } | { kind: 'relationship'; targetTableId: string; cardinality: SqlViewerCardinality; inverseCardinality: SqlViewerCardinality; reverse?: { fieldId: string; label: string } | null; onDelete?: 'restrict'; } | { kind: 'file'; cardinality: SqlViewerCardinality; access?: 'independent'; } ); export interface SqlViewerUniqueKey { id: string; fieldIds: readonly string[]; } export interface SqlViewerTable { id: string; label: string; owningTeamId?: string; fields: readonly SqlViewerField[]; uniqueKeys?: readonly SqlViewerUniqueKey[]; } type Direction = 'horizontal' | 'vertical'; type Side = 'left' | 'right'; type TableNode = Node<{ table: SqlViewerTable; tone: number }, 'table'>; type GroupNode = Node<{ label: string; tone: number; count: number }, 'group'>; type MoreNode = Node<{ tables: SqlViewerTable[] }, 'more'>; type ViewerNode = TableNode | GroupNode | MoreNode; type JoinEdge = Edge< { join: string; description: string; sourceMany: boolean; targetMany: boolean; }, 'join' >; interface Focus { table: string; field?: string | undefined; } const moreId = '~more'; const groupId = (key: string) => `~group:${key}`; const cardWidth = 272; const cardChrome = 4; const headerHeight = 40; const rowHeight = 28; const keysChrome = 36; const keyHeight = 26; const colGap = 104; const rowGap = 32; const groupPad = 20; const groupHeader = 44; const groupGap = 56; const wrapWidth = 1400; const tones = 5; const fitAll: FitViewOptions = { padding: '5.4%', maxZoom: 1 }; const compositeKeys = (table: SqlViewerTable) => (table.uniqueKeys ?? []).filter(key => key.fieldIds.length > 1); const cardHeight = (table: SqlViewerTable) => { const keys = compositeKeys(table).length; return cardChrome + headerHeight + (table.fields.length + 1) * rowHeight + (keys ? keysChrome + keys * keyHeight : 0); }; function columnType(field: SqlViewerField) { switch (field.kind) { case 'text': return `varchar(${field.maxLength})`; case 'numeric': return `numeric(${field.precision},${field.scale})`; case 'timestamp': return 'timestamptz'; case 'single-select': return 'enum'; case 'multi-select': return 'enum[]'; case 'relationship': return field.cardinality === 'one' ? 'uuid' : 'uuid[]'; case 'file': return field.cardinality === 'one' ? 'file' : 'file[]'; default: return field.kind; } } function joinText(from: string, field: string, to: string, many: boolean): string { return many ? `${to}.id = ANY(${from}.${field})` : `${from}.${field} = ${to}.id`; } interface Block { key: string | null; label: string; tables: SqlViewerTable[]; } function arrange( visible: readonly SqlViewerTable[], hidden: readonly SqlViewerTable[], groups: Readonly<Record<string, string>> | undefined, direction: Direction, ): ViewerNode[] { const blocks: Block[] = []; for (const table of visible) { const team = table.owningTeamId; const key = team !== undefined && groups?.[team] ? team : null; let block = blocks.find(candidate => candidate.key === key); if (!block) { block = { key, label: key ? groups![key]! : '', tables: [] }; blocks.push(block); } block.tables.push(table); } const nodes: ViewerNode[] = []; let cursorX = 0; let cursorY = 0; let lineHeight = 0; let right = 0; let bottom = 0; let tone = 0; for (const block of blocks) { const ids = new Set(block.tables.map(table => table.id)); const depth = new Map(block.tables.map(table => [table.id, 0])); if (direction === 'horizontal') { for (let pass = 0; pass < block.tables.length; pass++) { let moved = false; for (const table of block.tables) for (const field of table.fields) { if (field.kind !== 'relationship') continue; const target = field.targetTableId; const next = depth.get(table.id)! + 1; if (target !== table.id && ids.has(target) && next > depth.get(target)! && next < block.tables.length) { depth.set(target, next); moved = true; } } if (!moved) break; } } const columnBottoms = new Map<number, number>(); const placed = block.tables.map(table => { const column = depth.get(table.id)!; const y = columnBottoms.get(column) ?? 0; columnBottoms.set(column, y + cardHeight(table) + rowGap); return { table, x: column * (cardWidth + colGap), y }; }); const innerWidth = Math.max(...placed.map(item => item.x)) + cardWidth; const innerHeight = Math.max(...columnBottoms.values()) - rowGap; const framed = block.key !== null; const width = framed ? innerWidth + groupPad * 2 : innerWidth; const height = framed ? innerHeight + groupHeader + groupPad : innerHeight; if (direction === 'horizontal' && cursorX > 0 && cursorX + width > wrapWidth) { cursorX = 0; cursorY += lineHeight + groupGap; lineHeight = 0; } const blockTone = framed ? (tone++ % tones) + 1 : 0; const parent = framed ? groupId(block.key!) : undefined; if (framed) nodes.push({ id: parent!, type: 'group', position: { x: cursorX, y: cursorY }, width, height, data: { label: block.label, tone: blockTone, count: block.tables.length, }, dragHandle: '.sprout-sql-group-label', focusable: false, selectable: false, }); for (const item of placed) nodes.push({ id: item.table.id, type: 'table', position: framed ? { x: groupPad + item.x, y: groupHeader + item.y } : { x: cursorX + item.x, y: cursorY + item.y }, ...(parent ? { parentId: parent, expandParent: true } : {}), data: { table: item.table, tone: blockTone }, ariaRole: 'group', ariaLabel: `${item.table.label} table, ${item.table.fields.length + 1} columns`, domAttributes: { 'aria-roledescription': 'table card' }, }); right = Math.max(right, cursorX + width); bottom = Math.max(bottom, cursorY + height); if (direction === 'horizontal') { cursorX += width + groupGap; lineHeight = Math.max(lineHeight, height); } else { cursorY += height + groupGap; } } if (hidden.length) nodes.push({ id: moreId, type: 'more', position: direction === 'horizontal' ? { x: right + colGap, y: 0 } : { x: 0, y: bottom + groupGap }, data: { tables: [...hidden] }, focusable: false, }); return nodes; } function joins(visible: readonly SqlViewerTable[], hidden: readonly SqlViewerTable[]): JoinEdge[] { const shown = new Set(visible.map(table => table.id)); const collapsed = new Set(hidden.map(table => table.id)); const labels = new Map([...visible, ...hidden].map(table => [table.id, table.label])); const node = (id: string) => (shown.has(id) ? id : collapsed.has(id) ? moreId : null); const edges: JoinEdge[] = []; for (const table of [...visible, ...hidden]) for (const field of table.fields) { if (field.kind !== 'relationship') continue; const source = node(table.id); const target = node(field.targetTableId); if (!source || !target || (source === moreId && target === moreId)) continue; const to = labels.get(field.targetTableId)!; const sourceMany = field.inverseCardinality === 'many'; const targetMany = field.cardinality === 'many'; edges.push({ id: `${table.id}/${field.id}`, type: 'join', source, sourceHandle: source === moreId ? 'out:right' : `${field.id}:right`, target, targetHandle: target === moreId ? 'in:left' : 'id:left', data: { join: joinText(table.label, field.label, to, targetMany), description: `${table.label}.${field.label} joins ${to}.id, ${ sourceMany ? 'many' : 'one' } to ${targetMany ? 'many' : 'one'}`, sourceMany, targetMany, }, }); } return edges; } interface ViewerState { focus: Focus | null; related: ReadonlySet<string>; activeEdges: ReadonlySet<string>; hover: (focus: Focus | null) => void; pin: (focus: Focus) => void; expand: () => void; } const ViewerContext = createContext<ViewerState | null>(null); const useViewer = () => useContext(ViewerContext)!; function sideHandles(type: 'source' | 'target', id: string) { return ( <> <Handle id={`${id}:left`} type={type} position={Position.Left} isConnectable={false} className="sprout-sql-handle" /> <Handle id={`${id}:right`} type={type} position={Position.Right} isConnectable={false} className="sprout-sql-handle" /> </> ); } function TableCard({ id, data: { table, tone } }: NodeProps<TableNode>) { const viewer = useViewer(); const composite = compositeKeys(table); const unique = new Set((table.uniqueKeys ?? []).filter(key => key.fieldIds.length === 1).map(key => key.fieldIds[0])); const labels = new Map(table.fields.map(field => [field.id, field.label])); const focused = viewer.focus?.table === id; return ( <section data-slot="sql-table" data-tone={tone} data-dimmed={viewer.focus && !viewer.related.has(id) ? '' : undefined} data-active={focused ? '' : undefined} className="sprout-sql-table" onMouseLeave={() => viewer.hover(null)} > <header className="sprout-sql-table-header"> <h3 className="sprout-sql-table-title" title={table.label}> {table.label} </h3> </header> <ul className="sprout-sql-columns"> <li className="sprout-sql-column" data-key="primary"> {sideHandles('target', 'id')} <span className="sprout-sql-column-icon"> <KeyIcon size="xs" role="img" aria-label="Primary key" /> </span> <span className="sprout-sql-column-name">id</span> <span className="sprout-sql-column-type">uuid</span> </li> {table.fields.map(field => { const join = field.kind === 'relationship'; const type = columnType(field); return ( <li key={field.id} className="sprout-sql-column" data-join={join ? '' : undefined} data-active={focused && viewer.focus?.field === field.id ? '' : undefined} title={ field.kind === 'single-select' || field.kind === 'multi-select' ? field.options .filter(option => !option.retired) .map(option => option.label) .join(' · ') : undefined } onMouseEnter={join ? () => viewer.hover({ table: id, field: field.id }) : undefined} onMouseLeave={join ? () => viewer.hover({ table: id }) : undefined} onClick={ join ? event => { event.stopPropagation(); viewer.pin({ table: id, field: field.id }); } : undefined } > {join && sideHandles('source', field.id)} <span className="sprout-sql-column-icon"> {join ? ( <LinkIcon size="xs" role="img" aria-label="Foreign key" /> ) : unique.has(field.id) ? ( <FingerprintIcon size="xs" role="img" aria-label="Unique" /> ) : null} </span> <span className="sprout-sql-column-name" title={field.label}> {field.label} </span> <span className="sprout-sql-column-type"> {type} {!field.required && ( <> <span aria-hidden="true">?</span> <span className="sprout-sql-sr-only">, nullable</span> </> )} </span> </li> ); })} </ul> {composite.length > 0 && ( <div className="sprout-sql-keys"> <p className="sprout-sql-keys-title">Unique keys</p> <ul className="sprout-sql-keys-list"> {composite.map(key => ( <li key={key.id} className="sprout-sql-key"> <FingerprintIcon size="xs" aria-hidden="true" /> <span>{key.fieldIds.map(field => labels.get(field) ?? field).join(', ')}</span> </li> ))} </ul> </div> )} </section> ); } function GroupFrame({ data: { label, tone, count } }: NodeProps<GroupNode>) { return ( <section data-slot="sql-group" data-tone={tone} aria-label={`${label}, ${count} ${count === 1 ? 'table' : 'tables'}`} className="sprout-sql-group" > <header className="sprout-sql-group-label"> <LayersIcon size="sm" aria-hidden="true" /> <span className="sprout-sql-group-name">{label}</span> <span className="sprout-sql-group-count">{count}</span> </header> </section> ); } function MoreCard({ data: { tables } }: NodeProps<MoreNode>) { const { expand } = useViewer(); const names = tables.slice(0, 3).map(table => table.label); const rest = tables.length - names.length; return ( <div data-slot="sql-more" className="sprout-sql-more"> {sideHandles('target', 'in')} {sideHandles('source', 'out')} <span aria-hidden="true" className="sprout-sql-more-sheet" /> <span aria-hidden="true" className="sprout-sql-more-sheet" /> <button type="button" className="nodrag sprout-sql-more-button" onClick={expand} aria-label={`Show ${tables.length} more ${ tables.length === 1 ? 'table' : 'tables' }: ${tables.map(table => table.label).join(', ')}`} > <span className="sprout-sql-more-count"> +{tables.length} {tables.length === 1 ? 'table' : 'tables'} </span> <span className="sprout-sql-more-names"> {names.join(', ')} {rest > 0 && ` and ${rest} more`} </span> <span className="sprout-sql-more-action">Show all</span> </button> </div> ); } function handlePoint(node: InternalNode, type: 'source' | 'target', id: string) { const handle = node.internals.handleBounds?.[type]?.find(candidate => candidate.id === id); if (!handle) return null; return { x: node.internals.positionAbsolute.x + handle.x + handle.width / 2, y: node.internals.positionAbsolute.y + handle.y + handle.height / 2, }; } function endMark(x: number, y: number, side: Side, many: boolean) { const out = side === 'right' ? 1 : -1; return many ? `M ${x + out * 12} ${y} L ${x} ${y - 6} M ${x + out * 12} ${y} L ${x} ${y + 6}` : `M ${x + out * 9} ${y - 5} L ${x + out * 9} ${y + 5}`; } function JoinLine({ id, source, target, sourceHandleId, targetHandleId, data }: EdgeProps<JoinEdge>) { const from = useInternalNode(source); const to = useInternalNode(target); const viewer = useViewer(); if (!from || !to || !data || !sourceHandleId || !targetHandleId) return null; const fromLeft = from.internals.positionAbsolute.x; const toLeft = to.internals.positionAbsolute.x; const fromRight = fromLeft + (from.measured.width ?? 0); const toRight = toLeft + (to.measured.width ?? 0); const [sourceSide, targetSide]: [Side, Side] = fromRight + 24 <= toLeft ? ['right', 'left'] : toRight + 24 <= fromLeft ? ['left', 'right'] : ['right', 'right']; const base = (handle: string) => handle.slice(0, handle.lastIndexOf(':')); const start = handlePoint(from, 'source', `${base(sourceHandleId)}:${sourceSide}`); const end = handlePoint(to, 'target', `${base(targetHandleId)}:${targetSide}`); if (!start || !end) return null; const position = (side: Side) => (side === 'right' ? Position.Right : Position.Left); const [path] = getSmoothStepPath({ sourceX: start.x, sourceY: start.y, sourcePosition: position(sourceSide), targetX: end.x, targetY: end.y, targetPosition: position(targetSide), borderRadius: 10, offset: 28, }); const active = viewer.activeEdges.has(id); return ( <path d={`${path} ${endMark(start.x, start.y, sourceSide, data.sourceMany)} ${endMark( end.x, end.y, targetSide, data.targetMany, )}`} className="react-flow__edge-path sprout-sql-join" data-active={active ? '' : undefined} data-dimmed={viewer.focus && !active ? '' : undefined} /> ); } const nodeTypes = { table: TableCard, group: GroupFrame, more: MoreCard }; const edgeTypes = { join: JoinLine }; const keyboardHint = "Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables; Enter pins a table's joins."; function ViewerFlow({ layoutNodes, edges, direction, label, hintId, expanded, setExpanded, collapsible, maxVisible, }: { layoutNodes: ViewerNode[]; edges: JoinEdge[]; direction: Direction; label: string; hintId: string; expanded: boolean; setExpanded: (expanded: boolean) => void; collapsible: boolean; maxVisible: number; }) { const [nodes, setNodes, onNodesChange] = useNodesState<ViewerNode>(layoutNodes); useEffect(() => setNodes(layoutNodes), [layoutNodes, setNodes]); const [hovered, setHovered] = useState<Focus | null>(null); const [pinned, setPinned] = useState<Focus | null>(null); const focus = hovered ?? pinned; const pin = useCallback( (next: Focus) => setPinned(current => (current?.table === next.table && current.field === next.field ? null : next)), [], ); const state = useMemo<ViewerState>(() => { const activeEdges = new Set<string>(); const related = new Set<string>(); if (focus) { related.add(focus.table); for (const edge of edges) { const hit = focus.field ? edge.id === `${focus.table}/${focus.field}` : edge.source === focus.table || edge.target === focus.table; if (!hit) continue; activeEdges.add(edge.id); related.add(edge.source).add(edge.target); } } return { focus, related, activeEdges, hover: setHovered, pin, expand: () => setExpanded(true), }; }, [focus, edges, pin, setExpanded]); const shownEdges = useMemo( () => state.activeEdges.size ? edges.map(edge => (state.activeEdges.has(edge.id) ? { ...edge, zIndex: 1000 } : edge)) : edges, [edges, state.activeEdges], ); const fitFirst = useMemo<FitViewOptions>( () => direction === 'vertical' && layoutNodes[0] ? { padding: '2.8%', maxZoom: 1, nodes: [{ id: layoutNodes[0].id }] } : fitAll, [direction, layoutNodes], ); const keyboardView = useKeyboardView(fitAll); const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { const target = event.target as HTMLElement; const id = target.dataset['id']; if ((event.key === 'Enter' || event.key === ' ') && target.classList.contains('react-flow__node-table') && id) { event.preventDefault(); pin({ table: id }); return; } if (event.key === 'Escape' && pinned) { setPinned(null); return; } keyboardView(event); }; const onFocus = (event: FocusEvent<HTMLDivElement>) => { const id = event.target.dataset['id']; if (event.target.classList.contains('react-flow__node-table') && id) setHovered({ table: id }); }; const onNodeMouseEnter: NodeMouseHandler<ViewerNode> = (_, node) => { if (node.type === 'table') setHovered({ table: node.id }); }; const onNodeClick: NodeMouseHandler<ViewerNode> = (_, node) => { if (node.type === 'table') pin({ table: node.id }); }; return ( <ViewerContext.Provider value={state}> <ReactFlow<ViewerNode, JoinEdge> className="sprout-schema-flow sprout-sql-flow" data-slot="sql-viewer-viewport" data-focus={focus ? '' : undefined} aria-label={label} aria-describedby={hintId} tabIndex={0} onKeyDown={onKeyDown} onFocus={onFocus} onBlur={() => setHovered(null)} nodes={nodes} edges={shownEdges} onNodesChange={onNodesChange} nodeTypes={nodeTypes} edgeTypes={edgeTypes} onNodeMouseEnter={onNodeMouseEnter} onNodeClick={onNodeClick} onPaneClick={() => setPinned(null)} fitView fitViewOptions={fitFirst} minZoom={flowMinZoom} maxZoom={flowMaxZoom} 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={layoutNodes} fit={fitFirst} /> {collapsible && expanded && ( <Panel position="top-left" data-slot="sql-viewer-collapse"> <Button variant="secondary" size="sm" onClick={() => { setPinned(null); setExpanded(false); }} > Show {maxVisible} tables </Button> </Panel> )} {state.activeEdges.size > 0 && ( <Panel position="bottom-left" data-slot="sql-viewer-joins" aria-hidden="true" className="sprout-sql-joins"> {edges .filter(edge => state.activeEdges.has(edge.id)) .slice(0, 3) .map(edge => ( <code key={edge.id} className="sprout-sql-join-text"> {edge.data!.join} </code> ))} {state.activeEdges.size > 3 && ( <span className="sprout-sql-joins-more">and {state.activeEdges.size - 3} more</span> )} </Panel> )} <ZoomControls position={direction === 'vertical' ? 'top-right' : 'bottom-right'} fit={fitAll} className="sprout-schema-controls" slot="sql-viewer-controls" /> </ReactFlow> </ViewerContext.Provider> ); } export interface SqlViewerProps extends Omit<HTMLAttributes<HTMLDivElement>, 'role' | 'children'> { tables: readonly SqlViewerTable[]; label: string; groups?: Readonly<Record<string, string>> | undefined; maxVisible?: number | undefined; layout?: SqlViewerLayout | undefined; } export function SqlViewer({ tables, label, groups, maxVisible = 4, layout = 'auto', className, ...props }: SqlViewerProps) { const mobile = useViewportMobile(); const direction: Direction = layout === 'auto' ? (mobile ? 'vertical' : 'horizontal') : layout; const hintId = useId(); const [expanded, setExpanded] = useState(false); const limit = Math.max(1, Math.floor(maxVisible)); const collapsible = tables.length > limit; const [visible, hidden] = useMemo( () => (collapsible && !expanded ? [tables.slice(0, limit), tables.slice(limit)] : [tables, []]), [tables, limit, collapsible, expanded], ); const layoutNodes = useMemo(() => arrange(visible, hidden, groups, direction), [visible, hidden, groups, direction]); const edges = useMemo(() => joins(visible, hidden), [visible, hidden]); const descriptions = joins(tables, []); return ( <div {...props} role="figure" aria-label={label} data-slot="sql-viewer" data-layout={direction} className={cn('sprout-sql-viewer', className)} > <p id={hintId} className="sprout-sql-sr-only"> {keyboardHint} </p> {descriptions.length > 0 && ( <ul aria-label="Joins" className="sprout-sql-sr-only"> {descriptions.map(edge => ( <li key={edge.id}>{edge.data!.description}</li> ))} </ul> )} {tables.length === 0 ? ( <p className="sprout-sql-empty">No tables to show</p> ) : ( <ReactFlowProvider key={direction}> <ViewerFlow layoutNodes={layoutNodes} edges={edges} direction={direction} label={label} hintId={hintId} expanded={expanded} setExpanded={setExpanded} collapsible={collapsible} maxVisible={limit} /> </ReactFlowProvider> )} </div> ); }And the files it imports:
lib/sprout/icons/add-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/fingerprint-icon.tsxlib/sprout/icons/key-icon.tsxlib/sprout/icons/layers-icon.tsxlib/sprout/icons/link-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-sql-viewer { --sprout-sql-mono: ui-monospace, SFMono-Regular, Menlo, monospace; 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-sql-flow.light, .sprout-sql-flow.dark { --sprout-indigo: inherit; --sprout-green: inherit; --sprout-orange: inherit; --sprout-red: inherit; --sprout-sky: inherit; --sprout-purple: inherit; --sprout-yellow: inherit; --sprout-teal: inherit; --sprout-blue: inherit; --sprout-tan: inherit; --sprout-chart-1: inherit; --sprout-chart-2: inherit; --sprout-chart-3: inherit; --sprout-chart-4: inherit; --sprout-chart-5: inherit; --sprout-chart-6: inherit; --sprout-chart-7: inherit; --sprout-chart-8: inherit; --sprout-chart-9: inherit; --sprout-chart-10: inherit; } .sprout-sql-viewer [data-tone] { --sprout-sql-tone: var(--sprout-primary); } .sprout-sql-viewer [data-tone="1"] { --sprout-sql-tone: var(--sprout-chart-1); } .sprout-sql-viewer [data-tone="2"] { --sprout-sql-tone: var(--sprout-chart-2); } .sprout-sql-viewer [data-tone="3"] { --sprout-sql-tone: var(--sprout-chart-3); } .sprout-sql-viewer [data-tone="4"] { --sprout-sql-tone: var(--sprout-chart-4); } .sprout-sql-viewer [data-tone="5"] { --sprout-sql-tone: var(--sprout-chart-5); } .sprout-sql-flow .react-flow__node-group { pointer-events: none; } .sprout-sql-handle.react-flow__handle { opacity: 0; pointer-events: none; border: 0; width: 6px; min-width: 0; height: 6px; min-height: 0; position: absolute; top: 50%; } .sprout-sql-handle.react-flow__handle-left { left: 0; transform: translate(-50%, -50%); } .sprout-sql-handle.react-flow__handle-right { right: 0; transform: translate(50%, -50%); } .sprout-sql-group { box-sizing: border-box; border: 1px solid color-mix(in oklab, var(--sprout-sql-tone) 45%, var(--sprout-line)); background: color-mix(in oklab, var(--sprout-sql-tone) 6%, transparent); border-radius: 14px; width: 100%; height: 100%; } .sprout-sql-group-label { height: 44px; color: color-mix(in oklab, var(--sprout-sql-tone) 70%, var(--sprout-text)); font-size: var(--sprout-text-xs); letter-spacing: .06em; text-transform: uppercase; pointer-events: all; cursor: grab; align-items: center; gap: 8px; padding: 0 20px; font-weight: 600; line-height: 1rem; display: inline-flex; } .sprout-sql-group-count { background: color-mix(in oklab, var(--sprout-sql-tone) 14%, transparent); font-variant-numeric: tabular-nums; letter-spacing: 0; text-align: center; border-radius: 999px; min-width: 18px; padding: 0 6px; } .sprout-sql-table { box-sizing: border-box; border: 1px solid var(--sprout-line); border-top: 3px solid var(--sprout-sql-tone); background: var(--sprout-surface); width: 272px; color: var(--sprout-text); box-shadow: var(--sprout-shadow-control); transition: opacity var(--sprout-motion-normal) var(--sprout-motion-ease), box-shadow var(--sprout-motion-fast) var(--sprout-motion-ease), border-color var(--sprout-motion-fast) var(--sprout-motion-ease); border-radius: 10px; overflow: hidden; } .sprout-sql-table[data-dimmed] { opacity: .38; } .sprout-sql-table[data-active], .react-flow__node.dragging .sprout-sql-table { box-shadow: var(--sprout-shadow-panel); } .sprout-sql-table[data-active] { border-color: color-mix(in oklab, var(--sprout-sql-tone) 55%, var(--sprout-line)); } .sprout-sql-table-header { box-sizing: border-box; border-bottom: 1px solid var(--sprout-line); background: color-mix(in oklab, var(--sprout-sql-tone) 9%, var(--sprout-surface)); justify-content: center; align-items: center; height: 40px; padding: 0 12px; display: flex; } .sprout-sql-table-title { min-width: 0; color: var(--sprout-text); font-size: var(--sprout-text-sm); text-overflow: ellipsis; white-space: nowrap; margin: 0; font-weight: 600; line-height: 1.25rem; overflow: hidden; } .sprout-sql-columns, .sprout-sql-keys-list { margin: 0; padding: 0; list-style: none; } .sprout-sql-column { box-sizing: border-box; align-items: center; gap: 8px; height: 28px; padding: 0 12px; font-size: .8125rem; line-height: 1.25rem; display: flex; position: relative; } .sprout-sql-column + .sprout-sql-column { box-shadow: inset 0 1px 0 color-mix(in oklab, var(--sprout-line) 60%, transparent); } .sprout-sql-column[data-join] { cursor: pointer; } .sprout-sql-column[data-active] { background: color-mix(in oklab, var(--sprout-primary) 8%, transparent); } @media (hover: hover) { .sprout-sql-column[data-join]:hover { background: color-mix(in oklab, var(--sprout-primary) 8%, transparent); } .sprout-sql-more-button:hover { border-color: var(--sprout-primary); transform: translate(-2px, -2px); } } .sprout-sql-column-icon { width: 12px; color: var(--sprout-muted); flex-shrink: 0; justify-content: center; display: flex; } .sprout-sql-column[data-key="primary"] .sprout-sql-column-icon { color: var(--sprout-warning); } .sprout-sql-column[data-join] .sprout-sql-column-icon { color: var(--sprout-primary); } .sprout-sql-column-name { text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; overflow: hidden; } .sprout-sql-column[data-key="primary"] .sprout-sql-column-name { font-weight: 600; } .sprout-sql-column-type { max-width: 50%; color: var(--sprout-muted); font-family: var(--sprout-sql-mono); text-overflow: ellipsis; white-space: nowrap; flex-shrink: 0; font-size: .6875rem; overflow: hidden; } .sprout-sql-keys { border-top: 1px solid var(--sprout-line); background: color-mix(in oklab, var(--sprout-hover) 40%, var(--sprout-surface)); } .sprout-sql-keys-title { box-sizing: border-box; height: 35px; color: var(--sprout-muted); letter-spacing: .06em; text-transform: uppercase; margin: 0; padding: 12px 12px 0; font-size: .6875rem; font-weight: 600; line-height: 1rem; } .sprout-sql-key { box-sizing: border-box; height: 26px; color: var(--sprout-muted); font-size: var(--sprout-text-xs); align-items: center; gap: 8px; padding: 0 12px; display: flex; } .sprout-sql-key > span { color: var(--sprout-text); text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } .sprout-sql-join { transition: stroke var(--sprout-motion-fast) var(--sprout-motion-ease), opacity var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-sql-flow .sprout-sql-join[data-active] { stroke: var(--sprout-primary); stroke-width: 1.75px; } .sprout-sql-join[data-dimmed] { opacity: .25; } .sprout-sql-joins { box-sizing: border-box; border: 1px solid color-mix(in oklab, var(--sprout-primary) 40%, var(--sprout-line)); background: var(--sprout-surface); max-width: calc(100% - 88px); box-shadow: var(--sprout-shadow-control); pointer-events: none; border-radius: 8px; flex-direction: column; gap: 4px; padding: 8px 10px; display: flex; } .sprout-sql-viewer[data-layout="vertical"] .sprout-sql-joins { max-width: calc(100% - 24px); } .sprout-sql-join-text { color: var(--sprout-text); font-family: var(--sprout-sql-mono); font-size: var(--sprout-text-xs); text-overflow: ellipsis; white-space: nowrap; line-height: 1rem; overflow: hidden; } .sprout-sql-joins-more { color: var(--sprout-muted); font-size: var(--sprout-text-xs); line-height: 1rem; } .sprout-sql-more { width: 240px; height: 132px; position: relative; } .sprout-sql-more-sheet { border: 1px solid var(--sprout-line); background: var(--sprout-surface); border-radius: 10px; position: absolute; inset: 0; } .sprout-sql-more-sheet:first-of-type { opacity: .5; transform: translate(10px, 10px); } .sprout-sql-more-sheet:nth-of-type(2) { opacity: .8; transform: translate(5px, 5px); } .sprout-sql-more-button { box-sizing: border-box; border: 1px dashed var(--sprout-border-strong); background: var(--sprout-surface); color: var(--sprout-text); font: inherit; text-align: left; cursor: pointer; box-shadow: var(--sprout-shadow-control); transition: transform var(--sprout-motion-fast) var(--sprout-motion-ease), border-color var(--sprout-motion-fast) var(--sprout-motion-ease); border-radius: 10px; flex-direction: column; justify-content: center; align-items: flex-start; gap: 4px; padding: 16px 18px; display: flex; position: absolute; inset: 0; } .sprout-sql-more-button:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 2px; } .sprout-sql-more-count { font-variant-numeric: tabular-nums; font-size: 1.125rem; font-weight: 600; line-height: 1.5rem; } .sprout-sql-more-names { color: var(--sprout-muted); font-size: var(--sprout-text-xs); -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-height: 1rem; display: -webkit-box; overflow: hidden; } .sprout-sql-more-action { color: var(--sprout-primary); font-size: var(--sprout-text-xs); margin-top: 6px; font-weight: 600; line-height: 1rem; } .sprout-sql-empty { color: var(--sprout-muted); font-size: var(--sprout-text-sm); margin: auto; } .sprout-sql-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: reduce) { .sprout-sql-table, .sprout-sql-join { transition: opacity var(--sprout-motion-normal) linear; } .sprout-sql-more-button { transition: none; } .sprout-sql-more-button:hover { transform: none; } } .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/sql-viewer. 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/sql-viewer.
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables; Enter pins a table's joins.
- Deals.customer_id joins Customers.id, many to one
- Deals.owner_id joins Employees.id, many to one
- Invoices.deal_id joins Deals.id, many to one
- Invoices.line_ids joins Line items.id, many to many
- Line items.product_id joins Products.id, many to one
- Employees.manager_id joins Employees.id, many to one
- Payments.invoice_id joins Invoices.id, many to one
Usage
import { SqlViewer } from "@tulipfarm/sprout/sql-viewer";
// Table documents straight from TulipFarm.
<SqlViewer
tables={tableDocuments}
groups={{ [salesTeamId]: "Sales", [billingTeamId]: "Billing" }}
label="Tables in Sales"
/>The viewer fills its parent and is at least 24rem tall. Give the parent a height, such as h-160, to show more.
Columns and types
Every table starts with id uuid, its primary key. Text shows as varchar(n), numbers as numeric(p,s), and timestamps as timestamptz. Selects show as enumand list their options on hover. Relationships show as uuidor uuid[] with a link icon. Optional columns end in?. Single-column unique keys show a fingerprint; keys over several columns are listed under "Unique keys".
Layouts
layout="auto" uses columns from 768px up and a stack below it. Columns place each joined table one step right of the table that points to it. Pass horizontal or vertical to fix the layout.
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables; Enter pins a table's joins.
- Deals.customer_id joins Customers.id, many to one
- Invoices.deal_id joins Deals.id, many to one
Arrow keys pan, plus and minus zoom, and 0 fits the diagram. Tab moves between tables; Enter pins a table's joins.
- Deals.customer_id joins Customers.id, many to one
- Invoices.deal_id joins Deals.id, many to one
Props
tables: TulipFarm table definitions or documents withid,label,owningTeamId,fields, anduniqueKeys. A relationship to a table that is not passed is not drawn.label: the accessible name of the viewer.groups: team names byowningTeamId. Each named team gets its own tinted frame.maxVisible: tables shown before the rest collapse. Default 4.layout:auto(default),horizontal, orvertical.
Keyboard and accessibility
Tab moves to the viewer, then to each table, then to the zoom controls. Focus on a table lights its joins; Enter pins them andEsc clears. The arrow keys pan, + and -zoom, and 0 fits everything. Every join is also listed for screen readers, such as "Deals.customer_id joins Customers.id, many to one".
Theme tokens
Uses --sprout-surface, --sprout-canvas,--sprout-line, --sprout-text,--sprout-muted, and --sprout-primary. Team frames cycle through --sprout-chart-1 to--sprout-chart-5.