Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Component | Graph: Layout recalculation and persistency fix #396

Merged
merged 6 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React, { useEffect, useMemo, useState } from 'react'
import { VisSingleContainer, VisGraph } from '@unovis/react'
import { GraphLayoutType } from '@unovis/ts'
import { generateNodeLinkData } from '@src/utils/data'

export const title = 'Dynamic Layout'
export const subTitle = 'Select Layout From Dropdown'

export const component = (): JSX.Element => {
const [data, setData] = useState(generateNodeLinkData(50))
const layouts = Object.values(GraphLayoutType)
const initial = GraphLayoutType.Circular
const [layout, setLayout] = useState<string>(initial)

// Generate new data every 2 seconds
useEffect(() => {
setTimeout(() => {
const newData = generateNodeLinkData(10 + Math.floor(Math.random() * 50))

// Adding some random x, y values to the nodes for `GraphLayoutType.Precalculated`
newData.nodes.forEach(n => {
n.x = Math.random() * 1000
n.y = Math.random() * 1000
})

setData(newData)
}, 2000)
}, [data])

const forceLayoutSettings = useMemo(() => ({
fixNodePositionAfterSimulation: true,
}), [])

return (
<>
<select onChange={e => setLayout(e.target.value)} defaultValue={initial}>
{layouts.map(l => <option key={l} value={l}>{l}</option>)}
</select>
<VisSingleContainer data={data} height={900}>
<VisGraph layoutType={layout} forceLayoutSettings={forceLayoutSettings}/>
</VisSingleContainer>
</>
)
}

29 changes: 27 additions & 2 deletions packages/ts/src/components/graph/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { GraphInputLink, GraphInputNode } from 'types/graph'
import { Spacing } from 'types/spacing'

// Utils
import { isNumber, clamp, shallowDiff, isFunction, getBoolean } from 'utils/data'
import { isNumber, clamp, shallowDiff, isFunction, getBoolean, isPlainObject } from 'utils/data'
import { smartTransition } from 'utils/d3'

// Local Types
Expand Down Expand Up @@ -85,6 +85,7 @@ export class Graph<
private _prevWidth: number
private _prevHeight: number
private _shouldRecalculateLayout = false
private _currentLayoutType: GraphLayoutType | undefined
private _layoutCalculationPromise: Promise<boolean> | undefined

private _shouldFitLayout: boolean
Expand Down Expand Up @@ -160,6 +161,7 @@ export class Graph<

this._shouldRecalculateLayout = this._shouldRecalculateLayout || this._shouldLayoutRecalculate()
this._shouldFitLayout = this._shouldFitLayout || this._shouldRecalculateLayout
if (this._shouldFitLayout) this._isAutoFitDisabled = false
this._shouldSetPanels = true
}

Expand Down Expand Up @@ -350,8 +352,16 @@ export class Graph<

private async _calculateLayout (): Promise<boolean> {
const { config, datamodel } = this

const firstRender = this._isFirstRender

// If the layout type has changed, we need to reset the node positions if they were fixed before
if (this._currentLayoutType !== config.layoutType) {
for (const node of datamodel.nodes) {
delete node._state.fx
delete node._state.fy
}
}

switch (config.layoutType) {
case GraphLayoutType.Precalculated:
break
Expand Down Expand Up @@ -385,6 +395,7 @@ export class Graph<
this.config.onLayoutCalculated?.(datamodel.nodes, datamodel.links)

this._shouldRecalculateLayout = false
this._currentLayoutType = config.layoutType as GraphLayoutType

return firstRender
}
Expand Down Expand Up @@ -729,6 +740,20 @@ export class Graph<
if (Object.keys(dagreSettingsDiff).length) return true
}

if (prevConfig.layoutType === GraphLayoutType.Elk) {
if (isPlainObject(prevConfig.layoutElkSettings) && isPlainObject(config.layoutElkSettings)) {
// Do a deeper comparison if `config.layoutElkSettings` is an object
const elkSettingsDiff = shallowDiff(
prevConfig.layoutElkSettings as Record<string, string>,
config.layoutElkSettings as Record<string, string>
)
return Boolean(Object.keys(elkSettingsDiff).length)
} else {
// Otherwise, do a simple `===` comparison
return prevConfig.layoutElkSettings !== config.layoutElkSettings
}
}

if (
prevConfig.layoutType === GraphLayoutType.Parallel ||
prevConfig.layoutType === GraphLayoutType.ParallelHorizontal ||
Expand Down
28 changes: 20 additions & 8 deletions packages/ts/src/components/graph/modules/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { graphlib, Node } from 'dagre'
import { GraphDataModel } from 'data-models/graph'

// Utils
import { without, clamp, groupBy, unique, sortBy, getString, getNumber, getValue, merge, isFunction } from 'utils/data'
import { without, clamp, groupBy, unique, sortBy, getString, getNumber, getValue, merge, isFunction, isNil } from 'utils/data'

// Types
import { GraphInputLink, GraphInputNode } from 'types/graph'
Expand All @@ -19,7 +19,7 @@ import { GraphNode, GraphLink, GraphForceSimulationNode } from '../types'
import { GraphConfigInterface } from '../config'

// Helpers
import { getMaxNodeSize, configuredNodeSize, getNodeSize, getAverageNodeSize, getX, getY } from './node/helper'
import { getMaxNodeSize, configuredNodeSize, getNodeSize, getAverageNodeSize } from './node/helper'
import {
DEFAULT_ELK_SETTINGS,
adjustElkHierarchyCoordinates,
Expand Down Expand Up @@ -413,11 +413,19 @@ export async function applyLayoutForce<N extends GraphInputNode, L extends Graph

const { nonConnectedNodes, connectedNodes, nodes, links } = datamodel


// Apply fx and fy to nodes if present before running the simulation
nodes.forEach((d: GraphForceSimulationNode<N, L>) => {
d.fx = getX(d)
d.fy = getY(d)
})
if (forceLayoutSettings.fixNodePositionAfterSimulation) {
nodes.forEach((d: GraphForceSimulationNode<N, L>) => {
d.fx = isNil(d._state.fx) ? undefined : d._state.fx
d.fy = isNil(d._state.fy) ? undefined : d._state.fy
})
} else {
nodes.forEach((d: GraphForceSimulationNode<N, L>) => {
delete d._state.fx
delete d._state.fy
})
}

const simulation = forceSimulation(layoutNonConnectedAside ? connectedNodes : nodes)
.force('link', forceLink(links)
Expand All @@ -444,9 +452,13 @@ export async function applyLayoutForce<N extends GraphInputNode, L extends Graph
simulation.tick()
}

// Fix node positions if requested
// Fix node positions to `_state` if requested.
// And remove fx and fy from the node datum if present to make sure the nodes are not fixed
// if the layout was changed to a different layout and then back to force
if (forceLayoutSettings.fixNodePositionAfterSimulation) {
nodes.forEach(d => {
nodes.forEach((d: GraphForceSimulationNode<N, L>) => {
delete d.fx
delete d.fy
d._state.fx = d.x
d._state.fy = d.y
})
Expand Down
Loading