Graph
import { GraphForceProjector, SVG } from '@dxos/react-ui-graph';import * as GraphModel from '@dxos/graph/GraphModel';npm install @dxos/react-ui-graph @dxos/graphGraph draws the nodes and edges of a GraphModel from @dxos/graph. A projector decides where each node goes.
The force projector pulls linked nodes together and pushes the rest apart. Use it when the graph has no natural order, such as people and the teams they belong to. The package has other projectors for trees, rings and layers.
Graph draws inside SVG.Root. Import the package’s styles,
@dxos/react-ui-graph/styles/graph.css, once in your app.
| Prop | Type | Effect |
|---|---|---|
model |
GraphModel |
Sets the nodes and edges |
projector |
GraphProjector |
Places the nodes. Make your own after SVG.Root mounts. A GraphForceProjector by default |
renderer |
GraphRenderer |
Draws the layout. One made from the props below by default |
labels |
{ text } |
Sets what to write beside each node |
attributes |
{ node, edge } |
Sets classes and data- attributes for each node and each edge |
subgraphs |
boolean |
Draws a hull around each group of more than two connected nodes |
renderNode |
(group, node) => void |
Draws a node, in place of the default circle |
applyNode |
(group, node) => void |
Runs for each node after its position changes |
highlightOnHover |
boolean |
Colors a hovered node’s edges and dims the rest |
edgeOpacity |
number |
Sets the opacity of the edges |
drag |
boolean |
Lets the user move a node |
arrows |
boolean |
Ends edges in arrowheads |
onSelect |
(node, event) => void |
The user clicked a node |
onInspect |
(node | null, event) => void |
The pointer entered a node, or left it |
onPointerMove |
(point, event) => void |
The pointer moved over the graph. point is in the nodes’ coordinates |
onPointerLeave |
(event) => void |
The pointer left the graph |
Draw a graph
Section titled “Draw a graph”You build the model first, then draw it:
addNodetakes anid, and optionally atypeand anydata.addEdgetakes asourceand atarget.SVG.Zoomlets the user zoom and pan.SVG.Graphdraws the model.
The projector needs the SVG context, so make it in an effect after SVG.Root mounts.
Example (Drawing people and their teams)
import { function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.
useEffect, function useMemo<T>(factory: () => T, deps: React.DependencyList): T
useMemo will only recompute the memoized value when one of the deps has changed.
useMemo, function useRef<T>(initialValue: T): React.RefObject<T> (+2 overloads)
useRef returns a mutable ref object whose .current property is initialized to the passed argument
(initialValue). The returned object will persist for the full lifetime of the component.
Note that useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable
value around similar to how you’d use instance fields in classes.
useRef, function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.
useState } from 'react';import * as import GraphModel
GraphModel from '@dxos/graph/GraphModel';import { class GraphForceProjector<NodeData = any>
D3 force directed graph layout using d3 simulation..
GraphForceProjector, type type GraphProps<Node extends GraphNode.Any = any, Edge extends GraphEdge.Any = any> = Omit<Pick<GraphRendererOptions<Node>, "labels" | "subgraphs" | "attributes" | "renderNode" | "highlightOnHover" | "applyNode" | "edgeOpacity"> & { model?: GraphModel.GraphModel<Node, Edge>; projector?: GraphProjector<Node>; renderer?: GraphRenderer<Node>; drag?: boolean; arrows?: boolean; onSelect?: (node: GraphLayoutNode<Node>, event: MouseEvent) => void; onInspect?: (node: GraphLayoutNode<Node> | null, event: MouseEvent) => void; onPointerMove?: (point: ModelPoint, event: PointerEvent) => void; onPointerLeave?: (event: PointerEvent) => void;}, "className"> & { ...;}
GraphProps, const SVG: SVG
SVG, type class SVGContext
Contains a reference to the root SVG element and objects and configuration required by child nodes.
SVGContext } from '@dxos/react-ui-graph';
const const TEAMS: Record<string, string[]>
TEAMS: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record<string, string[]> = { type Design: string[]
Design: ['Ada', 'Grace', 'Linus'], type Platform: string[]
Platform: ['Alan', 'Barbara', 'Ken', 'Dennis'], type Research: string[]
Research: ['Edsger', 'Donald', 'Tony'],};
/** A node per team and per person, an edge from each person to their team. */const const makeModel: () => GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
A node per team and per person, an edge from each person to their team.
makeModel = () => { const const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model = import GraphModel
GraphModel.const make: <{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>(options?: GraphModel.Options<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}> | undefined) => GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
make(); for (const [const team: string
team, const people: string[]
people] of var Object: ObjectConstructor
Provides functionality common to all JavaScript objects.
Object.ObjectConstructor.entries<string[]>(o: { [s: string]: string[];} | ArrayLike<string[]>): [string, string[]][] (+1 overload)
Returns an array of key/values of the enumerable own properties of an object
entries(const TEAMS: Record<string, string[]>
TEAMS)) { const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model.AbstractGraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any; }, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any; }, GraphModel<...>>.addNode(node: { readonly id: string; readonly type?: string | undefined; data?: any;}): { readonly id: string; readonly type?: string | undefined; data?: any;}
addNode({ id: string
id: const team: string
team, type?: string | undefined
type: 'team', data?: any
data: { label: string
label: const team: string
team } }); for (const const person: string
person of const people: string[]
people) { const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model.AbstractGraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any; }, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any; }, GraphModel<...>>.addNode(node: { readonly id: string; readonly type?: string | undefined; data?: any;}): { readonly id: string; readonly type?: string | undefined; data?: any;}
addNode({ id: string
id: const person: string
person, type?: string | undefined
type: 'person', data?: any
data: { label: string
label: const person: string
person } }); const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model.AbstractGraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any; }, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any; }, GraphModel<...>>.addEdge(edge: MakeOptional<{ readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}, "id">): { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}
addEdge({ source: string
source: const person: string
person, target: string
target: const team: string
team }); } } return const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model;};
const const labels: LabelOptions<any> | undefined
labels: type GraphProps<Node extends GraphNode.Any = any, Edge extends GraphEdge.Any = any> = Omit<Pick<GraphRendererOptions<Node>, "labels" | "subgraphs" | "attributes" | "renderNode" | "highlightOnHover" | "applyNode" | "edgeOpacity"> & { model?: GraphModel.GraphModel<Node, Edge>; projector?: GraphProjector<Node>; renderer?: GraphRenderer<Node>; drag?: boolean; arrows?: boolean; onSelect?: (node: GraphLayoutNode<Node>, event: MouseEvent) => void; onInspect?: (node: GraphLayoutNode<Node> | null, event: MouseEvent) => void; onPointerMove?: (point: ModelPoint, event: PointerEvent) => void; onPointerLeave?: (event: PointerEvent) => void;}, "className"> & { ...;}
GraphProps['labels'] = { text: (node: GraphLayoutNode<any>, highlight?: boolean) => string | undefined
text: (node: GraphLayoutNode<any>
node) => node: GraphLayoutNode<any>
node.data?: any
data?.any
data?.any
label ?? node: GraphLayoutNode<any>
node.id: string
id,};
/** A node's `data-color` picks its fill from the graph styles; here, one color for teams and one for people. */const const attributes: AttributesOptions<any, any> | undefined
A node's data-color picks its fill from the graph styles; here, one color for teams and one for people.
attributes: type GraphProps<Node extends GraphNode.Any = any, Edge extends GraphEdge.Any = any> = Omit<Pick<GraphRendererOptions<Node>, "labels" | "subgraphs" | "attributes" | "renderNode" | "highlightOnHover" | "applyNode" | "edgeOpacity"> & { model?: GraphModel.GraphModel<Node, Edge>; projector?: GraphProjector<Node>; renderer?: GraphRenderer<Node>; drag?: boolean; arrows?: boolean; onSelect?: (node: GraphLayoutNode<Node>, event: MouseEvent) => void; onInspect?: (node: GraphLayoutNode<Node> | null, event: MouseEvent) => void; onPointerMove?: (point: ModelPoint, event: PointerEvent) => void; onPointerLeave?: (event: PointerEvent) => void;}, "className"> & { ...;}
GraphProps['attributes'] = { node?: ((node: GraphLayoutNode<any>) => { classes?: Record<string, boolean>; data?: Record<string, string | undefined>;}) | undefined
node: (node: GraphLayoutNode<any>
node) => ({ data?: Record<string, string | undefined> | undefined
data: { color: string
color: node: GraphLayoutNode<any>
node.data?: any
data?.any
type === 'team' ? 'sky' : 'amber' }, }),};
/** People and their teams, laid out by force: hover a node for its name, drag it, or scroll to zoom. */export const const TeamGraph: () => React.JSX.Element
People and their teams, laid out by force: hover a node for its name, drag it, or scroll to zoom.
TeamGraph = () => { const const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model = useMemo<GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>>(factory: () => GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>, deps: React.DependencyList): GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
useMemo will only recompute the memoized value when one of the deps has changed.
useMemo(const makeModel: () => GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
A node per team and per person, an edge from each person to their team.
makeModel, []); // The projector needs the SVG context, which exists only once `SVG.Root` has mounted. const const svgRef: React.RefObject<SVGContext | null>
svgRef = useRef<SVGContext>(initialValue: SVGContext | null): React.RefObject<SVGContext | null> (+2 overloads)
useRef returns a mutable ref object whose .current property is initialized to the passed argument
(initialValue). The returned object will persist for the full lifetime of the component.
Note that useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable
value around similar to how you’d use instance fields in classes.
useRef<class SVGContext
Contains a reference to the root SVG element and objects and configuration required by child nodes.
SVGContext>(null); const [const projector: GraphForceProjector<any> | undefined
projector, const setProjector: React.Dispatch<React.SetStateAction<GraphForceProjector<any> | undefined>>
setProjector] = useState<GraphForceProjector<any>>(): [GraphForceProjector<any> | undefined, React.Dispatch<React.SetStateAction<GraphForceProjector<any> | undefined>>] (+1 overload)
Returns a stateful value, and a function to update it.
useState<class GraphForceProjector<NodeData = any>
D3 force directed graph layout using d3 simulation..
GraphForceProjector>(); function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.
useEffect(() => { if (const svgRef: React.RefObject<SVGContext | null>
svgRef.RefObject<SVGContext | null>.current: SVGContext | null
The current value of the ref.
current) { const setProjector: (value: React.SetStateAction<GraphForceProjector<any> | undefined>) => void
setProjector( new new GraphForceProjector<any>(context: SVGContext, options?: GraphForceProjectorOptions | undefined, _selection?: SelectionModel, layout?: GraphLayout<any> | undefined): GraphForceProjector<any>
D3 force directed graph layout using d3 simulation..
GraphForceProjector(const svgRef: React.RefObject<SVGContext | null>
svgRef.RefObject<SVGContext | null>.current: SVGContext
The current value of the ref.
current, { forces?: ForceOptions | undefined
forces: { point?: boolean | ForcePositioningOptions | undefined
point: { strength?: number | undefined
strength: 0.05 } }, }), ); } }, []);
return ( <const SVG: SVG
SVG.type Root: React.ForwardRefExoticComponent<Omit<React.PropsWithChildren<SVGContextOptions & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">>, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue;} & React.RefAttributes<SVGContext>>
Root RefAttributes<SVGContext>.ref?: React.Ref<SVGContext> | undefined
Allows getting a ref to the component instance.
Once the component unmounts, React will set ref.current to null
(or call the ref with null if you passed a callback ref).
ref={const svgRef: React.RefObject<SVGContext | null>
svgRef}> <const SVG: SVG
SVG.type Markers: ({ arrowSize, classNames }: MarkersProps) => React.JSX.Element
Markers /> <const SVG: SVG
SVG.type Zoom: React.MemoExoticComponent<({ extent, classNames, children }: ZoomProps) => React.JSX.Element>
Zoom extent?: ZoomExtent | undefined
extent={[1 / 2, 2]}> <const SVG: SVG
SVG.type Graph: <Node extends Any = any, Edge extends Any = any>(props: GraphProps<Node, Edge> & { ref?: React.Ref<GraphController>;}) => React.JSX.Element
Graph model?: GraphModel.GraphModel<any, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}> | undefined
model={const model: GraphModel.GraphModel<{ readonly id: string; readonly type?: string | undefined; data?: any;}, { readonly id: string; readonly type?: string | undefined; readonly source: string; readonly target: string; data?: any;}>
model} projector?: GraphProjector<any, any> | undefined
projector={const projector: GraphForceProjector<any> | undefined
projector} drag?: boolean | undefined
drag labels?: LabelOptions<any> | undefined
labels={const labels: LabelOptions<any>
labels} attributes?: AttributesOptions<any, any> | undefined
attributes={const attributes: AttributesOptions<any, any>
A node's data-color picks its fill from the graph styles; here, one color for teams and one for people.
attributes} /> </const SVG: SVG
SVG.type Zoom: React.MemoExoticComponent<({ extent, classNames, children }: ZoomProps) => React.JSX.Element>
Zoom> </const SVG: SVG
SVG.type Root: React.ForwardRefExoticComponent<Omit<React.PropsWithChildren<SVGContextOptions & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">>, "className"> & { classNames?: import("@dxos/ui-types").ClassNameValue;} & React.RefAttributes<SVGContext>>
Root> );};
labels reads each node’s name back from the data that addNode took, and attributes reads the node’s type to
pick its color. The useEffect makes the GraphForceProjector from the context in svgRef.
The story at the top of this page runs this example.