React Flow
This is an example of real-time collaborative React Flow.
App.tsx
1import { useCallback, useEffect, useMemo, useState } from 'react';2import { JSONArray, useDocument } from '@yorkie-js/react';3import {4 ReactFlow,5 Node,6 Edge,7 Background,8 Controls,9 Panel,10 NodeChange,11 EdgeChange,12 Connection,13 useReactFlow,14 XYPosition,15} from '@xyflow/react';16import ExampleHeader, { type Status } from './ExampleHeader';1718type Graph = {19 nodes: JSONArray<Node>;20 edges: JSONArray<Edge>;21};2223function App() {24 const { root, update, connection, loading, error } = useDocument<Graph>();25 // Selection and measured sizes are local UI state: they are never written26 // to the shared document, so each peer selects independently.27 const [local, setLocal] = useState<28 Record<string, Pick<Node, 'selected' | 'measured'>>29 >({});3031 const setLocalState = useCallback(32 (changes: Array<NodeChange | EdgeChange>) => {33 setLocal((prev) => {34 const next = { ...prev };35 for (const c of changes) {36 if (c.type === 'select') {37 next[c.id] = { ...next[c.id], selected: c.selected };38 } else if (c.type === 'dimensions' && c.dimensions) {39 next[c.id] = { ...next[c.id], measured: c.dimensions };40 } else if (c.type === 'remove') {41 delete next[c.id];42 }43 }44 return next;45 });46 },47 [],48 );4950 // Drop the local state of nodes and edges a peer removed.51 useEffect(() => {52 setLocal((prev) => {53 const ids = new Set([54 ...root.nodes.map((n) => n.id),55 ...root.edges.map((e) => e.id),56 ]);57 const stale = Object.keys(prev).filter((id) => !ids.has(id));58 if (stale.length === 0) return prev;59 const next = { ...prev };60 for (const id of stale) delete next[id];61 return next;62 });63 }, [root]);6465 const onNodesChange = useCallback(66 (changes: Array<NodeChange>) => {67 setLocalState(changes);68 update((r) => {69 for (const c of changes) {70 if (c.type === 'add') {71 r.nodes.push(c.item);72 continue;73 }74 if (c.type !== 'position' && c.type !== 'remove') continue;7576 const idx = r.nodes.findIndex((n) => n.id === c.id);77 if (idx === -1) continue;78 if (c.type === 'remove') {79 r.nodes.delete(idx);80 } else if (c.position) {81 r.nodes[idx].position = c.position;82 }83 }84 });85 },86 [setLocalState, update],87 );8889 const onEdgesChange = useCallback(90 (changes: Array<EdgeChange>) => {91 setLocalState(changes);92 update((r) => {93 for (const c of changes) {94 if (c.type !== 'remove') continue;95 const idx = r.edges.findIndex((e) => e.id === c.id);96 if (idx !== -1) r.edges.delete(idx);97 }98 });99 },100 [setLocalState, update],101 );102103 const onConnect = useCallback(104 (connection: Connection) => {105 update((r) => {106 r.edges.push({107 // Random IDs keep edges created by different peers from colliding.108 id:109 crypto.randomUUID?.() ??110 `${Date.now()}-${Math.random().toString(36).slice(2)}`,111 type: 'smoothstep',112 source: connection.source,113 target: connection.target,114 sourceHandle: connection.sourceHandle,115 targetHandle: connection.targetHandle,116 });117 });118 },119 [update],120 );121122 const addNode = useCallback(123 (position: XYPosition) => {124 update((r) => {125 r.nodes.push({126 id:127 crypto.randomUUID?.() ??128 `${Date.now()}-${Math.random().toString(36).slice(2)}`,129 data: { label: `Node ${r.nodes.length + 1}` },130 position,131 });132 });133 },134 [update],135 );136137 // Merge the local state into the shared nodes and edges. `root` is a new138 // object after every change, local or remote.139 const nodes = useMemo(140 () => root.nodes.map((n) => ({ ...n, ...local[n.id] })),141 [root, local],142 );143 const edges = useMemo(144 () => root.edges.map((e) => ({ ...e, ...local[e.id] })),145 [root, local],146 );147148 let status: Status = 'offline';149 if (error) status = 'error';150 else if (loading) status = 'connecting';151 else if (connection === 'connected') status = 'connected';152153 return (154 <div className="layout">155 <ExampleHeader title="React Flow" status={status} />156 {error ? (157 <p className="state-message" role="alert">158 Couldn't reach the Yorkie server at{' '}159 {import.meta.env.VITE_YORKIE_API_ADDR}. Check that it's running, then160 reload.161 </p>162 ) : loading ? (163 <p className="state-message">Loading the shared graph…</p>164 ) : (165 <main className="canvas">166 <ReactFlow167 nodes={nodes}168 edges={edges}169 onNodesChange={onNodesChange}170 onEdgesChange={onEdgesChange}171 onConnect={onConnect}172 fitView173 fitViewOptions={{ maxZoom: 1 }}174 >175 <Background gap={10} size={1} />176 <Controls />177 <AddNodeButton onAdd={addNode} />178 </ReactFlow>179 </main>180 )}181 </div>182 );183}184185/**186 * `AddNodeButton` adds a node at the center of the visible canvas.187 */188function AddNodeButton({ onAdd }: { onAdd: (position: XYPosition) => void }) {189 const { screenToFlowPosition } = useReactFlow();190191 return (192 <Panel position="top-left">193 <button194 type="button"195 className="button button--primary"196 onClick={(e) => {197 const pane = e.currentTarget198 .closest('.react-flow')!199 .getBoundingClientRect();200 onAdd(201 screenToFlowPosition({202 x: pane.x + pane.width / 2 - 75,203 y: pane.y + pane.height / 2 - 20,204 }),205 );206 }}207 >208 <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">209 <path210 d="M8 3v10M3 8h10"211 stroke="currentColor"212 strokeWidth="1.5"213 strokeLinecap="round"214 />215 </svg>216 Add node217 </button>218 </Panel>219 );220}221222export default App;
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1