1- import React , { useCallback , useMemo , useRef , useState } from 'react' ;
1+ import React , {
2+ useCallback ,
3+ useMemo ,
4+ useRef ,
5+ useEffect ,
6+ useState ,
7+ } from 'react' ;
28import { connect } from 'react-redux' ;
39import type { DataModelingState } from '../store/reducer' ;
410import {
@@ -24,6 +30,7 @@ import {
2430 type NodeProps ,
2531 type EdgeProps ,
2632 useDiagram ,
33+ applyLayout ,
2734} from '@mongodb-js/diagramming' ;
2835import type { Edit , StaticModel } from '../services/data-model-storage' ;
2936import { UUID } from 'bson' ;
@@ -125,6 +132,7 @@ const DiagramEditor: React.FunctionComponent<{
125132 const isDarkMode = useDarkMode ( ) ;
126133 const diagramContainerRef = useRef < HTMLDivElement | null > ( null ) ;
127134 const diagram = useDiagram ( ) ;
135+ const [ nodes , setNodes ] = useState < NodeProps [ ] > ( [ ] ) ;
128136
129137 const setDiagramContainerRef = useCallback (
130138 ( ref : HTMLDivElement | null ) => {
@@ -198,8 +206,26 @@ const DiagramEditor: React.FunctionComponent<{
198206 } ) ;
199207 } , [ model ?. relationships ] ) ;
200208
201- const nodes = useMemo ( ( ) => {
202- return ( model ?. collections ?? [ ] ) . map (
209+ const applyInitialLayout = useCallback (
210+ async ( storedNodes : NodeProps [ ] ) => {
211+ console . log ( 'INITIAL STATE: applying layout' ) ;
212+ try {
213+ const { nodes : positionedNodes } = await applyLayout (
214+ storedNodes ,
215+ edges ,
216+ 'STAR'
217+ ) ;
218+ // TODO: save the new positions to the model
219+ setNodes ( positionedNodes ) ;
220+ } catch ( err ) {
221+ console . error ( 'Error applying layout:' , err ) ;
222+ }
223+ } ,
224+ [ setNodes ]
225+ ) ;
226+
227+ useEffect ( ( ) => {
228+ const storedNodes = ( model ?. collections ?? [ ] ) . map (
203229 ( coll ) : NodeProps => ( {
204230 id : coll . ns ,
205231 type : 'collection' ,
@@ -224,12 +250,16 @@ const DiagramEditor: React.FunctionComponent<{
224250 } ;
225251 }
226252 ) ,
227- measured : {
228- width : 100 ,
229- height : 200 ,
230- } ,
231253 } )
232254 ) ;
255+ const isInitialState = storedNodes . every (
256+ ( node ) => node . position . x === - 1 && node . position . y === - 1
257+ ) ;
258+ if ( isInitialState ) {
259+ void applyInitialLayout ( storedNodes ) ;
260+ return ;
261+ }
262+ setNodes ( storedNodes ) ;
233263 } , [ model ?. collections ] ) ;
234264
235265 let content ;
0 commit comments