Charts and graphs · @jengacore/node-graph
NodeGraph
React Flow in the jengacore tokens with dagre auto-layout: nodes, edges, minimap, controls, focusable nodes with onNodeOpen, and a read-only mode.
Focus a node and press Enter, or double-click it.
Transfer flow: 7 nodes and 7 links, listed after the graph.
- Quote requested, payer wallet: leads to Sanctions screening
- Sanctions screening, rules engine: leads to Funds reserved (clear), Manual review (hit)
- Manual review, analyst queue: leads to Funds reserved (released), Transfer rejected (confirmed)
- Funds reserved, payer bank: leads to Transfer committed
- Transfer committed, switch: leads to Settlement window
- Transfer rejected, notify payer: no outgoing links
- Settlement window, end of day: no outgoing links
Install
terminal
npx shadcn@latest add @jengacore/node-graphWithout the namespace configured: npx shadcn@latest add https://ui.jengacore.com/r/<new-york-v4|base-nova>/node-graph.json
Registry dependencies
npm packages
@xyflow/react@12.12.0@dagrejs/dagre@3.1.1
Source
components/jc/node-graph.tsx
"use client"
import * as React from "react"
import dagre from "@dagrejs/dagre"
import {
Background,
Controls,
Handle,
MarkerType,
MiniMap,
Position,
ReactFlow,
ReactFlowProvider,
applyNodeChanges,
type Edge,
type Node,
type NodeProps,
} from "@xyflow/react"
import "@xyflow/react/dist/style.css"
import { cn } from "@/lib/utils"
export type GraphTone = "default" | "primary" | "info" | "warning" | "danger" | "muted"
export type GraphNode = {
id: string
label: string
/** One short line under the label: a type, an owner, a count. */
detail?: string
tone?: GraphTone
}
export type GraphEdge = {
id?: string
source: string
target: string
/** Short text on the edge: "on approval", "3 calls". */
label?: string
/** Draw the edge animated and dashed (a flow in progress). */
animated?: boolean
}
export type GraphDirection = "TB" | "LR"
type JcNodeData = { label: string; detail?: string; tone: GraphTone; direction: GraphDirection; readOnly: boolean }
type JcNode = Node<JcNodeData, "jc">
const NODE_W = 184
const NODE_H = 52
const TONE: Record<GraphTone, string> = {
default: "border-border-strong",
primary: "border-primary",
info: "border-info",
warning: "border-warning",
danger: "border-destructive",
muted: "border-border border-dashed text-muted-foreground",
}
const TONE_MARK: Record<GraphTone, string> = {
default: "bg-muted-foreground",
primary: "bg-primary",
info: "bg-info",
warning: "bg-warning",
danger: "bg-destructive",
muted: "bg-border-strong",
}
function JcGraphNode({ data }: NodeProps<JcNode>) {
const lr = data.direction === "LR"
// Handles are where edges attach; in read-only mode they are invisible and cannot start a connection.
const handle = cn("size-2! border-0! bg-border-strong!", data.readOnly && "pointer-events-none! opacity-0!")
return (
<div
className={cn(
"flex h-full w-full flex-col justify-center gap-0.5 rounded-md border-[1.5px] bg-card px-3 text-card-foreground shadow-card",
TONE[data.tone]
)}
>
<Handle type="target" position={lr ? Position.Left : Position.Top} className={handle} isConnectable={!data.readOnly} />
<div className="flex min-w-0 items-center gap-2">
<span aria-hidden className={cn("size-2 shrink-0 rounded-full", TONE_MARK[data.tone])} />
<span className="truncate text-[13px] leading-[18px] font-medium">{data.label}</span>
</div>
{data.detail ? <span className="truncate pl-4 font-mono text-[11px] leading-4 text-muted-foreground">{data.detail}</span> : null}
<Handle type="source" position={lr ? Position.Right : Position.Bottom} className={handle} isConnectable={!data.readOnly} />
</div>
)
}
const NODE_TYPES = { jc: JcGraphNode }
/**
* React Flow's own parts in the jengacore tokens. Its stylesheet is unlayered, so it would beat Tailwind's layered
* utilities; these rules are scoped to the wrapper, which also out-ranks it.
*/
const FLOW_CSS = `
[data-slot=node-graph] .react-flow__node:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
[data-slot=node-graph] .react-flow__node.selected > div { box-shadow: 0 0 0 2px var(--ring); }
[data-slot=node-graph] .react-flow__controls-button { width: 28px; height: 28px; }
[data-slot=node-graph] .react-flow__controls-button svg { fill: currentColor; }
[data-slot=node-graph] .react-flow__attribution { background: color-mix(in srgb, var(--card) 85%, transparent); }
[data-slot=node-graph] .react-flow__attribution a { color: var(--muted-foreground); }
[data-slot=node-graph] .react-flow__edge-textbg { fill: var(--card); }
[data-slot=node-graph] .react-flow__edge-text { fill: var(--muted-foreground); font-size: 11px; }
`
/** Positions from dagre: ranks top to bottom (TB) or left to right (LR), nodes of one rank side by side. */
export function layoutGraph(nodes: readonly GraphNode[], edges: readonly GraphEdge[], direction: GraphDirection = "TB") {
const g = new dagre.graphlib.Graph()
g.setGraph({ rankdir: direction, nodesep: 28, ranksep: 56, marginx: 8, marginy: 8 })
g.setDefaultEdgeLabel(() => ({}))
for (const n of nodes) g.setNode(n.id, { width: NODE_W, height: NODE_H })
for (const e of edges) if (g.hasNode(e.source) && g.hasNode(e.target)) g.setEdge(e.source, e.target)
dagre.layout(g)
return new Map(
nodes.map((n) => {
const p = g.node(n.id)
// dagre gives the centre; React Flow wants the top-left corner.
return [n.id, { x: (p?.x ?? 0) - NODE_W / 2, y: (p?.y ?? 0) - NODE_H / 2 }] as const
})
)
}
const edgeId = (e: GraphEdge) => e.id ?? `${e.source}->${e.target}`
/**
* A themed React Flow graph laid out by dagre: nodes, edges with arrows, a minimap, zoom controls and a dotted
* background, all in the jengacore tokens (Light, Dark and High contrast follow the page). Every node is focusable;
* Enter or a double click calls `onNodeOpen`. `readOnly` removes every edit affordance: no dragging, no connecting,
* no selection box, no deleting, and the handles are hidden. A visually hidden list repeats the nodes and their links
* for screen readers.
*/
export function NodeGraph(props: NodeGraphProps) {
return (
<ReactFlowProvider>
<NodeGraphInner {...props} />
</ReactFlowProvider>
)
}
export type NodeGraphProps = {
nodes: readonly GraphNode[]
edges: readonly GraphEdge[]
direction?: GraphDirection
readOnly?: boolean
onNodeOpen?: (node: GraphNode) => void
/** Accessible name of the graph: "Payment flow". */
label: string
minimap?: boolean
controls?: boolean
className?: string
}
function NodeGraphInner({ nodes, edges, direction = "TB", readOnly = false, onNodeOpen, label, minimap = true, controls = true, className }: NodeGraphProps) {
const descId = `${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}-graph-desc`
const byId = React.useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes])
const openable = Boolean(onNodeOpen)
const laidOut = React.useMemo<JcNode[]>(() => {
const positions = layoutGraph(nodes, edges, direction)
return nodes.map((n) => ({
id: n.id,
type: "jc",
position: positions.get(n.id) ?? { x: 0, y: 0 },
width: NODE_W,
height: NODE_H,
ariaLabel: `${n.label}${n.detail ? `, ${n.detail}` : ""}`,
// A node that opens on Enter is a button to assistive technology; otherwise React Flow's default group.
ariaRole: openable ? ("button" as const) : ("group" as const),
data: { label: n.label, detail: n.detail, tone: n.tone ?? "default", direction, readOnly },
draggable: !readOnly,
connectable: !readOnly,
deletable: false,
}))
}, [nodes, edges, direction, readOnly, openable])
// Local positions so a drag sticks until the graph itself changes.
const [rfNodes, setRfNodes] = React.useState(laidOut)
React.useEffect(() => setRfNodes(laidOut), [laidOut])
const rfEdges = React.useMemo<Edge[]>(
() =>
edges
.filter((e) => byId.has(e.source) && byId.has(e.target))
.map((e) => ({
id: edgeId(e),
source: e.source,
target: e.target,
label: e.label,
animated: e.animated,
type: "smoothstep",
deletable: false,
focusable: false,
markerEnd: { type: MarkerType.ArrowClosed, width: 16, height: 16, color: "var(--muted-foreground)" },
ariaLabel: `${byId.get(e.source)?.label} to ${byId.get(e.target)?.label}${e.label ? `, ${e.label}` : ""}`,
})),
[edges, byId]
)
const open = (id: string | undefined) => {
const node = id ? byId.get(id) : undefined
if (node && onNodeOpen) onNodeOpen(node)
}
return (
<div
data-slot="node-graph"
className={cn(
"relative h-[420px] w-full overflow-hidden rounded-lg border border-border bg-card contrast:border-input",
className
)}
onKeyDown={(event) => {
// A node with the button role opens on Enter and Space, as a button does.
if (event.key !== "Enter" && !(event.key === " " && onNodeOpen)) return
const el = (event.target as HTMLElement).closest<HTMLElement>(".react-flow__node")
if (!el) return
event.preventDefault()
open(el.dataset.id)
}}
>
<style>{FLOW_CSS}</style>
<ReactFlow<JcNode>
nodes={rfNodes}
edges={rfEdges}
nodeTypes={NODE_TYPES}
// Measured sizes, positions and selection come back as changes; nodes are never added or removed here.
onNodesChange={(changes) =>
setRfNodes((current) => applyNodeChanges(changes.filter((c) => c.type === "dimensions" || c.type === "position" || c.type === "select"), current))
}
onNodeDoubleClick={(_, node) => open(node.id)}
fitView
fitViewOptions={{ padding: 0.15 }}
minZoom={0.25}
maxZoom={2}
nodesDraggable={!readOnly}
nodesConnectable={false}
nodesFocusable
edgesFocusable={false}
elementsSelectable={!readOnly}
selectionOnDrag={false}
deleteKeyCode={null}
selectionKeyCode={readOnly ? null : "Shift"}
multiSelectionKeyCode={readOnly ? null : undefined}
zoomOnDoubleClick={false}
aria-label={label}
aria-describedby={descId}
ariaLabelConfig={{
"node.a11yDescription.default": onNodeOpen ? "Press Enter to open this node." : "Use Tab to move between nodes.",
"node.a11yDescription.keyboardDisabled": onNodeOpen ? "Press Enter to open this node." : "Use Tab to move between nodes.",
"controls.ariaLabel": "Zoom controls",
"minimap.ariaLabel": "Overview of the whole graph",
}}
style={
{
"--xy-background-color": "var(--card)",
"--xy-background-pattern-color": "var(--border)",
"--xy-edge-stroke": "var(--muted-foreground)",
"--xy-edge-stroke-selected": "var(--ring)",
"--xy-edge-stroke-width": "1.5",
"--xy-edge-label-background-color": "var(--card)",
"--xy-edge-label-color": "var(--muted-foreground)",
"--xy-node-border-radius": "6px",
"--xy-controls-button-background-color": "var(--card)",
"--xy-controls-button-background-color-hover": "var(--muted)",
"--xy-controls-button-color": "var(--foreground)",
"--xy-controls-button-color-hover": "var(--foreground)",
"--xy-controls-button-border-color": "var(--border)",
"--xy-controls-box-shadow": "var(--shadow-card, none)",
"--xy-minimap-background-color": "var(--muted)",
"--xy-minimap-mask-background-color": "color-mix(in srgb, var(--background) 60%, transparent)",
"--xy-minimap-mask-stroke-color": "var(--ring)",
"--xy-minimap-node-background-color": "var(--border-strong)",
"--xy-minimap-node-stroke-color": "transparent",
"--xy-attribution-background-color": "transparent",
"--xy-selection-background-color": "color-mix(in srgb, var(--ring) 12%, transparent)",
"--xy-selection-border": "1px dashed var(--ring)",
} as React.CSSProperties
}
>
<Background gap={16} size={1} />
{controls ? <Controls showInteractive={false} /> : null}
{minimap ? <MiniMap pannable zoomable nodeBorderRadius={6} /> : null}
</ReactFlow>
<div className="sr-only">
<p id={descId}>{`${label}: ${nodes.length} nodes and ${rfEdges.length} links, listed after the graph.`}</p>
<ul aria-label={`${label}: nodes and links`}>
{nodes.map((n) => {
const out = edges.filter((e) => e.source === n.id && byId.has(e.target))
return (
<li key={n.id}>
{n.label}
{n.detail ? `, ${n.detail}` : ""}
{out.length ? `: leads to ${out.map((e) => `${byId.get(e.target)?.label}${e.label ? ` (${e.label})` : ""}`).join(", ")}` : ": no outgoing links"}
</li>
)
})}
</ul>
</div>
</div>
)
}