fix(core): properly reset state and retain reactivity

Signed-off-by: braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
braks
2023-05-10 14:04:53 +02:00
committed by Braks
parent e5591ee1df
commit 6f3c22ee66
+43 -4
View File
@@ -657,6 +657,8 @@ export function useActions(
const setState: Actions['setState'] = (options) => { const setState: Actions['setState'] = (options) => {
const opts = options instanceof Function ? options(state) : options const opts = options instanceof Function ? options(state) : options
// these options will be set using the appropriate methods
const skip: (keyof typeof opts)[] = [ const skip: (keyof typeof opts)[] = [
'modelValue', 'modelValue',
'nodes', 'nodes',
@@ -669,6 +671,17 @@ export function useActions(
'defaultEdgeOptions', 'defaultEdgeOptions',
] ]
// these options cannot be set after initialization
const exclude: (keyof typeof opts)[] = [
'd3Zoom',
'd3Selection',
'd3ZoomHandler',
'viewportRef',
'vueFlowRef',
'dimensions',
'hooks',
]
// we need to set the default opts before setting any elements so the options are applied to the elements on first render // we need to set the default opts before setting any elements so the options are applied to the elements on first render
if (isDef(opts.defaultEdgeOptions)) { if (isDef(opts.defaultEdgeOptions)) {
state.defaultEdgeOptions = opts.defaultEdgeOptions state.defaultEdgeOptions = opts.defaultEdgeOptions
@@ -708,9 +721,11 @@ export function useActions(
} }
Object.keys(opts).forEach((o) => { Object.keys(opts).forEach((o) => {
const option = opts[o as keyof typeof opts] const key = o as keyof State
if (!skip.includes(o as keyof typeof opts) && isDef(option)) { const option = opts[key]
;(<any>state)[o] = option
if (![...skip, ...exclude].includes(key) && isDef(option)) {
;(<any>state)[key] = option
} }
}) })
@@ -824,7 +839,31 @@ export function useActions(
project: (position) => viewportHelper.project(position), project: (position) => viewportHelper.project(position),
toObject, toObject,
updateNodeInternals, updateNodeInternals,
$reset: () => {}, $reset: () => {
const resetState = useState()
state.edges = []
state.nodes = []
// reset the zoom state
if (state.d3Zoom && state.d3Selection) {
const updatedTransform = zoomIdentity
.translate(resetState.defaultViewport.x ?? 0, resetState.defaultViewport.y ?? 0)
.scale(clamp(resetState.defaultViewport.zoom ?? 1, resetState.minZoom, resetState.maxZoom))
const bbox = state.viewportRef!.getBoundingClientRect()
const extent: CoordinateExtent = [
[0, 0],
[bbox.width, bbox.height],
]
const constrainedTransform = state.d3Zoom.constrain()(updatedTransform, extent, resetState.translateExtent)
state.d3Zoom.transform(state.d3Selection, constrainedTransform)
}
setState(resetState)
},
$destroy: () => {}, $destroy: () => {},
} }
} }