@@ -17,17 +17,22 @@ import {
1717 ReactFlowProvider ,
1818} from "@xyflow/react" ;
1919import "@xyflow/react/dist/style.css" ;
20- import { usePages } from "@/hooks/usePages" ;
21- import { NoteNode } from "./NoteNode" ;
2220import * as Y from "yjs" ;
21+ import ELK from "elkjs" ;
2322import { SocketIOProvider } from "y-socket.io" ;
24- import { cn } from "@/lib/utils" ;
2523import { useQueryClient } from "@tanstack/react-query" ;
24+
25+ import { CollaborativeCursors } from "../CursorView" ;
26+ import { NoteNode } from "./NoteNode" ;
27+
28+ import { usePages } from "@/hooks/usePages" ;
29+ import { cn } from "@/lib/utils" ;
2630import useYDocStore from "@/store/useYDocStore" ;
2731import { useCollaborativeCursors } from "@/hooks/useCursor" ;
28- import { CollaborativeCursors } from "../CursorView" ;
2932import { calculateBestHandles } from "@/lib/calculateBestHandles" ;
3033
34+ const elk = new ELK ( ) ;
35+
3136const proOptions = { hideAttribution : true } ;
3237
3338export interface YNode extends Node {
@@ -196,6 +201,47 @@ function Flow({ className }: CanvasProps) {
196201 } ) ;
197202 } , [ pages , ydoc ] ) ;
198203
204+ const performLayout = async ( ) => {
205+ const graph = {
206+ id : "root" ,
207+ layoutOptions : {
208+ "elk.algorithm" : "force" ,
209+ } ,
210+ children : nodes . map ( ( node ) => ( {
211+ id : node . id ,
212+ width : 160 , // 실제 노드 너비로 변경하기 (node.width)
213+ height : 40 , // 실제 노드 높이로 변경하기 (node.height)
214+ } ) ) ,
215+ edges : edges . map ( ( edge ) => ( {
216+ id : edge . id ,
217+ sources : [ edge . source ] ,
218+ targets : [ edge . target ] ,
219+ } ) ) ,
220+ } ;
221+
222+ const layout = await elk . layout ( graph ) ;
223+
224+ const updatedNodes = nodes . map ( ( node ) => {
225+ const layoutNode = layout ! . children ! . find ( ( n ) => n . id === node . id ) ;
226+
227+ return {
228+ ...node ,
229+ position : {
230+ x : layoutNode ! . x as number ,
231+ y : layoutNode ! . y as number ,
232+ } ,
233+ } ;
234+ } ) ;
235+
236+ const nodesMap = ydoc . getMap ( "nodes" ) ;
237+
238+ updatedNodes . forEach ( ( updateNode ) => {
239+ nodesMap . set ( updateNode . id , updateNode ) ;
240+ } ) ;
241+
242+ setNodes ( updatedNodes ) ;
243+ } ;
244+
199245 const handleNodesChange = useCallback (
200246 ( changes : NodeChange [ ] ) => {
201247 if ( ! ydoc ) return ;
@@ -335,6 +381,9 @@ function Flow({ className }: CanvasProps) {
335381 selectNodesOnDrag = { false }
336382 >
337383 < Controls />
384+ < div className = "fixed bottom-5 left-16 z-30 h-4 w-4 text-neutral-50 hover:cursor-pointer" >
385+ < button onClick = { performLayout } > Sort</ button >
386+ </ div >
338387 < MiniMap />
339388 < Background variant = { BackgroundVariant . Dots } gap = { 12 } size = { 1 } />
340389 < CollaborativeCursors cursors = { cursors } />
0 commit comments