refactor(core): use node/edge id as only dependency for nodes/edges list (#1447)

* refactor(core): use node id to (re-)render nodes

* refactor(core): use edge id to (re-)render nodes

* chore(changeset): add

* chore(core): cleanup

* chore(core): cast cmp as any
This commit is contained in:
Braks
2024-06-06 10:45:38 +02:00
parent 8bc1c99252
commit 876b71dc19
7 changed files with 274 additions and 325 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@vue-flow/core": minor
---
Return non-nullable edge from `useEdge`
+5
View File
@@ -0,0 +1,5 @@
---
"@vue-flow/core": minor
---
Use node/edge id as the only dependency to render nodes/edges.
+110 -79
View File
@@ -1,9 +1,8 @@
import { computed, defineComponent, h, provide, ref } from 'vue' import { computed, defineComponent, getCurrentInstance, h, inject, provide, ref, resolveComponent, toRef } from 'vue'
import { useVModel } from '@vueuse/core' import type { Connection, EdgeComponent, HandleType, MouseTouchEvent } from '../../types'
import type { Connection, EdgeComponent, EdgeUpdatable, GraphEdge, HandleType, MouseTouchEvent } from '../../types'
import { ConnectionMode, Position } from '../../types' import { ConnectionMode, Position } from '../../types'
import { useEdgeHooks, useHandle, useVueFlow } from '../../composables' import { useEdge, useEdgeHooks, useHandle, useVueFlow } from '../../composables'
import { EdgeId, EdgeRef } from '../../context' import { EdgeId, EdgeRef, Slots } from '../../context'
import { import {
ARIA_EDGE_DESC_KEY, ARIA_EDGE_DESC_KEY,
ErrorCode, ErrorCode,
@@ -17,18 +16,12 @@ import EdgeAnchor from './EdgeAnchor'
interface Props { interface Props {
id: string id: string
type: EdgeComponent | ((...args: any[]) => any) | object | false
name: string
selectable?: boolean
focusable?: boolean
updatable?: EdgeUpdatable
edge: GraphEdge
} }
const EdgeWrapper = defineComponent({ const EdgeWrapper = defineComponent({
name: 'Edge', name: 'Edge',
compatConfig: { MODE: 3 }, compatConfig: { MODE: 3 },
props: ['name', 'type', 'id', 'updatable', 'selectable', 'focusable', 'edge'], props: ['id'],
setup(props: Props) { setup(props: Props) {
const { const {
id: vueFlowId, id: vueFlowId,
@@ -45,11 +38,18 @@ const EdgeWrapper = defineComponent({
isValidConnection, isValidConnection,
multiSelectionActive, multiSelectionActive,
disableKeyboardA11y, disableKeyboardA11y,
elementsSelectable,
edgesUpdatable,
edgesFocusable,
} = useVueFlow() } = useVueFlow()
const hooks = useEdgeHooks(props.edge, emits) const { edge } = useEdge(props.id)
const edge = useVModel(props, 'edge') const hooks = useEdgeHooks(edge, emits)
const slots = inject(Slots)
const instance = getCurrentInstance()
const mouseOver = ref(false) const mouseOver = ref(false)
@@ -63,11 +63,45 @@ const EdgeWrapper = defineComponent({
const edgeEl = ref<SVGElement | null>(null) const edgeEl = ref<SVGElement | null>(null)
const isSelectable = toRef(() => (typeof edge.selectable === 'undefined' ? elementsSelectable.value : edge.selectable))
const isUpdatable = toRef(() => (typeof edge.updatable === 'undefined' ? edgesUpdatable.value : edge.updatable))
const isFocusable = toRef(() => (typeof edge.focusable === 'undefined' ? edgesFocusable.value : edge.focusable))
provide(EdgeId, props.id) provide(EdgeId, props.id)
provide(EdgeRef, edgeEl) provide(EdgeRef, edgeEl)
const edgeClass = computed(() => (edge.value.class instanceof Function ? edge.value.class(edge.value) : edge.value.class)) const edgeClass = computed(() => (edge.class instanceof Function ? edge.class(edge) : edge.class))
const edgeStyle = computed(() => (edge.value.style instanceof Function ? edge.value.style(edge.value) : edge.value.style)) const edgeStyle = computed(() => (edge.style instanceof Function ? edge.style(edge) : edge.style))
const edgeCmp = computed(() => {
const name = edge.type || 'default'
const slot = slots?.[`edge-${name}`]
if (slot) {
return slot
}
let edgeType = edge.template ?? getEdgeTypes.value[name]
if (typeof edgeType === 'string') {
if (instance) {
const components = Object.keys(instance.appContext.components)
if (components && components.includes(name)) {
edgeType = resolveComponent(name, false) as EdgeComponent
}
}
}
if (edgeType && typeof edgeType !== 'string') {
return edgeType
}
emits.error(new VueFlowError(ErrorCode.EDGE_TYPE_MISSING, edgeType))
return false
})
const { handlePointerDown } = useHandle({ const { handlePointerDown } = useHandle({
nodeId, nodeId,
@@ -80,29 +114,29 @@ const EdgeWrapper = defineComponent({
}) })
return () => { return () => {
const sourceNode = findNode(edge.value.source) const sourceNode = findNode(edge.source)
const targetNode = findNode(edge.value.target) const targetNode = findNode(edge.target)
const pathOptions = 'pathOptions' in edge.value ? edge.value.pathOptions : {} const pathOptions = 'pathOptions' in edge ? edge.pathOptions : {}
if (!sourceNode && !targetNode) { if (!sourceNode && !targetNode) {
emits.error(new VueFlowError(ErrorCode.EDGE_SOURCE_TARGET_MISSING, edge.value.id, edge.value.source, edge.value.target)) emits.error(new VueFlowError(ErrorCode.EDGE_SOURCE_TARGET_MISSING, edge.id, edge.source, edge.target))
return null return null
} }
if (!sourceNode) { if (!sourceNode) {
emits.error(new VueFlowError(ErrorCode.EDGE_SOURCE_MISSING, edge.value.id, edge.value.source)) emits.error(new VueFlowError(ErrorCode.EDGE_SOURCE_MISSING, edge.id, edge.source))
return null return null
} }
if (!targetNode) { if (!targetNode) {
emits.error(new VueFlowError(ErrorCode.EDGE_TARGET_MISSING, edge.value.id, edge.value.target)) emits.error(new VueFlowError(ErrorCode.EDGE_TARGET_MISSING, edge.id, edge.target))
return null return null
} }
if (!edge.value || edge.value.hidden || sourceNode.hidden || targetNode.hidden) { if (!edge || edge.hidden || sourceNode.hidden || targetNode.hidden) {
return null return null
} }
@@ -113,7 +147,7 @@ const EdgeWrapper = defineComponent({
sourceNodeHandles = [...(sourceNode.handleBounds.source || []), ...(sourceNode.handleBounds.target || [])] sourceNodeHandles = [...(sourceNode.handleBounds.source || []), ...(sourceNode.handleBounds.target || [])]
} }
const sourceHandle = getHandle(sourceNodeHandles, edge.value.sourceHandle) const sourceHandle = getHandle(sourceNodeHandles, edge.sourceHandle)
let targetNodeHandles let targetNodeHandles
if (connectionMode.value === ConnectionMode.Strict) { if (connectionMode.value === ConnectionMode.Strict) {
@@ -122,7 +156,7 @@ const EdgeWrapper = defineComponent({
targetNodeHandles = [...(targetNode.handleBounds.target || []), ...(targetNode.handleBounds.source || [])] targetNodeHandles = [...(targetNode.handleBounds.target || []), ...(targetNode.handleBounds.source || [])]
} }
const targetHandle = getHandle(targetNodeHandles, edge.value.targetHandle) const targetHandle = getHandle(targetNodeHandles, edge.targetHandle)
const sourcePosition = sourceHandle ? sourceHandle.position : Position.Bottom const sourcePosition = sourceHandle ? sourceHandle.position : Position.Bottom
@@ -137,10 +171,10 @@ const EdgeWrapper = defineComponent({
targetPosition, targetPosition,
) )
edge.value.sourceX = sourceX edge.sourceX = sourceX
edge.value.sourceY = sourceY edge.sourceY = sourceY
edge.value.targetX = targetX edge.targetX = targetX
edge.value.targetY = targetY edge.targetY = targetY
return h( return h(
'g', 'g',
@@ -150,14 +184,14 @@ const EdgeWrapper = defineComponent({
'data-id': props.id, 'data-id': props.id,
'class': [ 'class': [
'vue-flow__edge', 'vue-flow__edge',
`vue-flow__edge-${props.type === false ? 'default' : props.name}`, `vue-flow__edge-${edgeCmp.value === false ? 'default' : edge.type || 'default'}`,
noPanClassName.value, noPanClassName.value,
edgeClass.value, edgeClass.value,
{ {
updating: mouseOver.value, updating: mouseOver.value,
selected: edge.value.selected, selected: edge.selected,
animated: edge.value.animated, animated: edge.animated,
inactive: !props.selectable, inactive: !isSelectable.value,
}, },
], ],
'onClick': onEdgeClick, 'onClick': onEdgeClick,
@@ -166,52 +200,49 @@ const EdgeWrapper = defineComponent({
'onMouseenter': onEdgeMouseEnter, 'onMouseenter': onEdgeMouseEnter,
'onMousemove': onEdgeMouseMove, 'onMousemove': onEdgeMouseMove,
'onMouseleave': onEdgeMouseLeave, 'onMouseleave': onEdgeMouseLeave,
'onKeyDown': props.focusable ? onKeyDown : undefined, 'onKeyDown': isFocusable.value ? onKeyDown : undefined,
'tabIndex': props.focusable ? 0 : undefined, 'tabIndex': isFocusable.value ? 0 : undefined,
'aria-label': 'aria-label': edge.ariaLabel === null ? undefined : edge.ariaLabel || `Edge from ${edge.source} to ${edge.target}`,
edge.value.ariaLabel === null 'aria-describedby': isFocusable.value ? `${ARIA_EDGE_DESC_KEY}-${vueFlowId}` : undefined,
? undefined 'role': isFocusable.value ? 'button' : 'img',
: edge.value.ariaLabel || `Edge from ${edge.value.source} to ${edge.value.target}`,
'aria-describedby': props.focusable ? `${ARIA_EDGE_DESC_KEY}-${vueFlowId}` : undefined,
'role': props.focusable ? 'button' : 'img',
}, },
[ [
updating.value updating.value
? null ? null
: h(props.type === false ? getEdgeTypes.value.default : props.type, { : h(edgeCmp.value === false ? getEdgeTypes.value.default : (edgeCmp.value as any), {
id: props.id, id: props.id,
sourceNode, sourceNode,
targetNode, targetNode,
source: edge.value.source, source: edge.source,
target: edge.value.target, target: edge.target,
type: edge.value.type, type: edge.type,
updatable: props.updatable, updatable: isUpdatable.value,
selected: edge.value.selected, selected: edge.selected,
animated: edge.value.animated, animated: edge.animated,
label: edge.value.label, label: edge.label,
labelStyle: edge.value.labelStyle, labelStyle: edge.labelStyle,
labelShowBg: edge.value.labelShowBg, labelShowBg: edge.labelShowBg,
labelBgStyle: edge.value.labelBgStyle, labelBgStyle: edge.labelBgStyle,
labelBgPadding: edge.value.labelBgPadding, labelBgPadding: edge.labelBgPadding,
labelBgBorderRadius: edge.value.labelBgBorderRadius, labelBgBorderRadius: edge.labelBgBorderRadius,
data: edge.value.data, data: edge.data,
events: { ...edge.value.events, ...hooks.on }, events: { ...edge.events, ...hooks.on },
style: edgeStyle.value, style: edgeStyle.value,
markerStart: `url('#${getMarkerId(edge.value.markerStart, vueFlowId)}')`, markerStart: `url('#${getMarkerId(edge.markerStart, vueFlowId)}')`,
markerEnd: `url('#${getMarkerId(edge.value.markerEnd, vueFlowId)}')`, markerEnd: `url('#${getMarkerId(edge.markerEnd, vueFlowId)}')`,
sourcePosition, sourcePosition,
targetPosition, targetPosition,
sourceX, sourceX,
sourceY, sourceY,
targetX, targetX,
targetY, targetY,
sourceHandleId: edge.value.sourceHandle, sourceHandleId: edge.sourceHandle,
targetHandleId: edge.value.targetHandle, targetHandleId: edge.targetHandle,
interactionWidth: edge.value.interactionWidth, interactionWidth: edge.interactionWidth,
...pathOptions, ...pathOptions,
}), }),
[ [
props.updatable === 'source' || props.updatable === true isUpdatable.value === 'source' || isUpdatable.value === true
? [ ? [
h( h(
'g', 'g',
@@ -231,7 +262,7 @@ const EdgeWrapper = defineComponent({
), ),
] ]
: null, : null,
props.updatable === 'target' || props.updatable === true isUpdatable.value === 'target' || isUpdatable.value === true
? [ ? [
h( h(
'g', 'g',
@@ -265,11 +296,11 @@ const EdgeWrapper = defineComponent({
} }
function onEdgeUpdate(event: MouseTouchEvent, connection: Connection) { function onEdgeUpdate(event: MouseTouchEvent, connection: Connection) {
hooks.emit.update({ event, edge: edge.value, connection }) hooks.emit.update({ event, edge, connection })
} }
function onEdgeUpdateEnd(event: MouseTouchEvent) { function onEdgeUpdateEnd(event: MouseTouchEvent) {
hooks.emit.updateEnd({ event, edge: edge.value }) hooks.emit.updateEnd({ event, edge })
updating.value = false updating.value = false
} }
@@ -280,28 +311,28 @@ const EdgeWrapper = defineComponent({
updating.value = true updating.value = true
nodeId.value = isSourceHandle ? edge.value.target : edge.value.source nodeId.value = isSourceHandle ? edge.target : edge.source
handleId.value = (isSourceHandle ? edge.value.targetHandle : edge.value.sourceHandle) ?? '' handleId.value = (isSourceHandle ? edge.targetHandle : edge.sourceHandle) ?? ''
edgeUpdaterType.value = isSourceHandle ? 'target' : 'source' edgeUpdaterType.value = isSourceHandle ? 'target' : 'source'
hooks.emit.updateStart({ event, edge: edge.value }) hooks.emit.updateStart({ event, edge })
handlePointerDown(event) handlePointerDown(event)
} }
function onEdgeClick(event: MouseEvent) { function onEdgeClick(event: MouseEvent) {
const data = { event, edge: edge.value } const data = { event, edge }
if (props.selectable) { if (isSelectable.value) {
nodesSelectionActive.value = false nodesSelectionActive.value = false
if (edge.value.selected && multiSelectionActive.value) { if (edge.selected && multiSelectionActive.value) {
removeSelectedEdges([edge.value]) removeSelectedEdges([edge])
edgeEl.value?.blur() edgeEl.value?.blur()
} else { } else {
addSelectedEdges([edge.value]) addSelectedEdges([edge])
} }
} }
@@ -309,23 +340,23 @@ const EdgeWrapper = defineComponent({
} }
function onEdgeContextMenu(event: MouseEvent) { function onEdgeContextMenu(event: MouseEvent) {
hooks.emit.contextMenu({ event, edge: edge.value }) hooks.emit.contextMenu({ event, edge })
} }
function onDoubleClick(event: MouseEvent) { function onDoubleClick(event: MouseEvent) {
hooks.emit.doubleClick({ event, edge: edge.value }) hooks.emit.doubleClick({ event, edge })
} }
function onEdgeMouseEnter(event: MouseEvent) { function onEdgeMouseEnter(event: MouseEvent) {
hooks.emit.mouseEnter({ event, edge: edge.value }) hooks.emit.mouseEnter({ event, edge })
} }
function onEdgeMouseMove(event: MouseEvent) { function onEdgeMouseMove(event: MouseEvent) {
hooks.emit.mouseMove({ event, edge: edge.value }) hooks.emit.mouseMove({ event, edge })
} }
function onEdgeMouseLeave(event: MouseEvent) { function onEdgeMouseLeave(event: MouseEvent) {
hooks.emit.mouseLeave({ event, edge: edge.value }) hooks.emit.mouseLeave({ event, edge })
} }
function onEdgeUpdaterSourceMouseDown(event: MouseEvent) { function onEdgeUpdaterSourceMouseDown(event: MouseEvent) {
@@ -337,7 +368,7 @@ const EdgeWrapper = defineComponent({
} }
function onKeyDown(event: KeyboardEvent) { function onKeyDown(event: KeyboardEvent) {
if (!disableKeyboardA11y.value && elementSelectionKeys.includes(event.key) && props.selectable) { if (!disableKeyboardA11y.value && elementSelectionKeys.includes(event.key) && isSelectable.value) {
const unselect = event.key === 'Escape' const unselect = event.key === 'Escape'
if (unselect) { if (unselect) {
+144 -105
View File
@@ -1,33 +1,41 @@
import { computed, defineComponent, h, nextTick, onMounted, provide, ref, toRef, watch } from 'vue' import {
import { until, useVModel } from '@vueuse/core' computed,
defineComponent,
getCurrentInstance,
h,
inject,
nextTick,
onMounted,
provide,
ref,
resolveComponent,
toRef,
watch,
} from 'vue'
import { until } from '@vueuse/core'
import { import {
ARIA_NODE_DESC_KEY, ARIA_NODE_DESC_KEY,
ErrorCode,
VueFlowError,
arrowKeyDiffs, arrowKeyDiffs,
calcNextPosition, calcNextPosition,
elementSelectionKeys, elementSelectionKeys,
getXYZPos, getXYZPos,
handleNodeClick, handleNodeClick,
} from '../../utils' } from '../../utils'
import type { GraphNode, HandleConnectable, NodeComponent } from '../../types' import { NodeId, NodeRef, Slots } from '../../context'
import { NodeId, NodeRef } from '../../context' import { isInputDOMNode, useDrag, useNode, useNodeHooks, useUpdateNodePositions, useVueFlow } from '../../composables'
import { isInputDOMNode, useDrag, useNodeHooks, useUpdateNodePositions, useVueFlow } from '../../composables' import type { NodeComponent } from '../../types'
interface Props { interface Props {
id: string id: string
draggable: boolean
selectable: boolean
connectable: HandleConnectable
focusable: boolean
type: NodeComponent | ((...args: any[]) => any) | object | false
name: string
node: GraphNode
resizeObserver: ResizeObserver resizeObserver: ResizeObserver
} }
const NodeWrapper = defineComponent({ const NodeWrapper = defineComponent({
name: 'Node', name: 'Node',
compatConfig: { MODE: 3 }, compatConfig: { MODE: 3 },
props: ['name', 'type', 'id', 'draggable', 'selectable', 'focusable', 'connectable', 'node', 'resizeObserver'], props: ['id', 'resizeObserver'],
setup(props: Props) { setup(props: Props) {
provide(NodeId, props.id) provide(NodeId, props.id)
@@ -38,7 +46,6 @@ const NodeWrapper = defineComponent({
nodesSelectionActive, nodesSelectionActive,
multiSelectionActive, multiSelectionActive,
emits, emits,
findNode,
removeSelectedNodes, removeSelectedNodes,
addSelectedNodes, addSelectedNodes,
updateNodeDimensions, updateNodeDimensions,
@@ -52,48 +59,86 @@ const NodeWrapper = defineComponent({
snapToGrid, snapToGrid,
snapGrid, snapGrid,
nodeDragThreshold, nodeDragThreshold,
getConnectedEdges, nodesDraggable,
elementsSelectable,
nodesConnectable,
nodesFocusable,
} = useVueFlow() } = useVueFlow()
const slots = inject(Slots)
const instance = getCurrentInstance()
const updateNodePositions = useUpdateNodePositions() const updateNodePositions = useUpdateNodePositions()
const node = useVModel(props, 'node') const { node, parentNode, connectedEdges } = useNode(props.id)
const parentNode = computed(() => findNode(node.value?.parentNode))
const connectedEdges = computed(() => getConnectedEdges(node.value ? [node.value] : []))
const nodeElement = ref<HTMLDivElement | null>(null) const nodeElement = ref<HTMLDivElement | null>(null)
provide(NodeRef, nodeElement) provide(NodeRef, nodeElement)
const { emit, on } = useNodeHooks(node.value, emits) const isDraggable = toRef(() => (typeof node.draggable === 'undefined' ? nodesDraggable.value : node.draggable))
const isSelectable = toRef(() => (typeof node.selectable === 'undefined' ? elementsSelectable.value : node.selectable))
const isConnectable = toRef(() => (typeof node.connectable === 'undefined' ? nodesConnectable.value : node.connectable))
const isFocusable = toRef(() => (typeof node.focusable === 'undefined' ? nodesFocusable.value : node.focusable))
const nodeCmp = computed(() => {
const name = node.type || 'default'
const slot = slots?.[`node-${name}`]
if (slot) {
return slot
}
let nodeType = node.template || getNodeTypes.value[name]
if (typeof nodeType === 'string') {
if (instance) {
const components = Object.keys(instance.appContext.components)
if (components && components.includes(name)) {
nodeType = resolveComponent(name, false) as NodeComponent
}
}
}
if (nodeType && typeof nodeType !== 'string') {
return nodeType
}
emits.error(new VueFlowError(ErrorCode.NODE_TYPE_MISSING, nodeType))
return false
})
const { emit, on } = useNodeHooks(node, emits)
const dragging = useDrag({ const dragging = useDrag({
id: props.id, id: props.id,
el: nodeElement, el: nodeElement,
disabled: () => !props.draggable, disabled: () => !isDraggable.value,
selectable: () => props.selectable, selectable: () => isSelectable.value,
dragHandle: () => node.value.dragHandle, dragHandle: () => node.dragHandle,
onStart(args) { onStart(args) {
// todo: remove intersections from here - they are not needed and only reduce performance // todo: remove intersections from here - they are not needed and only reduce performance
emit.dragStart({ ...args, intersections: getIntersectingNodes(node.value) }) emit.dragStart({ ...args, intersections: getIntersectingNodes(node) })
}, },
onDrag(args) { onDrag(args) {
emit.drag({ ...args, intersections: getIntersectingNodes(node.value) }) emit.drag({ ...args, intersections: getIntersectingNodes(node) })
}, },
onStop(args) { onStop(args) {
emit.dragStop({ ...args, intersections: getIntersectingNodes(node.value) }) emit.dragStop({ ...args, intersections: getIntersectingNodes(node) })
}, },
}) })
const getClass = computed(() => (node.value.class instanceof Function ? node.value.class(node.value) : node.value.class)) const getClass = computed(() => (node.class instanceof Function ? node.class(node) : node.class))
const getStyle = computed(() => { const getStyle = computed(() => {
const styles = (node.value.style instanceof Function ? node.value.style(node.value) : node.value.style) || {} const styles = (node.style instanceof Function ? node.style(node) : node.style) || {}
const width = node.value.width instanceof Function ? node.value.width(node.value) : node.value.width const width = node.width instanceof Function ? node.width(node) : node.width
const height = node.value.height instanceof Function ? node.value.height(node.value) : node.value.height const height = node.height instanceof Function ? node.height(node) : node.height
if (width) { if (width) {
styles.width = typeof width === 'string' ? width : `${width}px` styles.width = typeof width === 'string' ? width : `${width}px`
@@ -106,7 +151,7 @@ const NodeWrapper = defineComponent({
return styles return styles
}) })
const zIndex = toRef(() => Number(node.value.zIndex ?? getStyle.value.zIndex ?? 0)) const zIndex = toRef(() => Number(node.zIndex ?? getStyle.value.zIndex ?? 0))
onUpdateNodeInternals((updateIds) => { onUpdateNodeInternals((updateIds) => {
if (updateIds.includes(props.id)) { if (updateIds.includes(props.id)) {
@@ -116,7 +161,7 @@ const NodeWrapper = defineComponent({
onMounted(() => { onMounted(() => {
watch( watch(
() => node.value.hidden, () => node.hidden,
(isHidden = false, _, onCleanup) => { (isHidden = false, _, onCleanup) => {
if (!isHidden && nodeElement.value) { if (!isHidden && nodeElement.value) {
props.resizeObserver.observe(nodeElement.value) props.resizeObserver.observe(nodeElement.value)
@@ -132,7 +177,7 @@ const NodeWrapper = defineComponent({
) )
}) })
watch([() => node.value.type, () => node.value.sourcePosition, () => node.value.targetPosition], () => { watch([() => node.type, () => node.sourcePosition, () => node.targetPosition], () => {
nextTick(() => { nextTick(() => {
updateNodeDimensions([{ id: props.id, nodeElement: nodeElement.value as HTMLDivElement, forceUpdate: true }]) updateNodeDimensions([{ id: props.id, nodeElement: nodeElement.value as HTMLDivElement, forceUpdate: true }])
}) })
@@ -141,15 +186,15 @@ const NodeWrapper = defineComponent({
/** this watcher only updates XYZPosition (when dragging a parent etc) */ /** this watcher only updates XYZPosition (when dragging a parent etc) */
watch( watch(
[ [
() => node.value.position.x, () => node.position.x,
() => node.value.position.y, () => node.position.y,
() => parentNode.value?.computedPosition.x, () => parentNode.value?.computedPosition.x,
() => parentNode.value?.computedPosition.y, () => parentNode.value?.computedPosition.y,
() => parentNode.value?.computedPosition.z, () => parentNode.value?.computedPosition.z,
zIndex, zIndex,
() => node.value.selected, () => node.selected,
() => node.value.dimensions.height, () => node.dimensions.height,
() => node.value.dimensions.width, () => node.dimensions.width,
() => parentNode.value?.dimensions.height, () => parentNode.value?.dimensions.height,
() => parentNode.value?.dimensions.width, () => parentNode.value?.dimensions.width,
], ],
@@ -157,19 +202,19 @@ const NodeWrapper = defineComponent({
const xyzPos = { const xyzPos = {
x: newX, x: newX,
y: newY, y: newY,
z: nodeZIndex + (elevateNodesOnSelect.value ? (node.value.selected ? 1000 : 0) : 0), z: nodeZIndex + (elevateNodesOnSelect.value ? (node.selected ? 1000 : 0) : 0),
} }
if (typeof parentX !== 'undefined' && typeof parentY !== 'undefined') { if (typeof parentX !== 'undefined' && typeof parentY !== 'undefined') {
node.value.computedPosition = getXYZPos({ x: parentX, y: parentY, z: parentZ! }, xyzPos) node.computedPosition = getXYZPos({ x: parentX, y: parentY, z: parentZ! }, xyzPos)
} else { } else {
node.value.computedPosition = xyzPos node.computedPosition = xyzPos
} }
}, },
{ flush: 'post', immediate: true }, { flush: 'post', immediate: true },
) )
watch([() => node.value.extent, nodeExtent], ([nodeExtent, globalExtent], [oldNodeExtent, oldGlobalExtent]) => { watch([() => node.extent, nodeExtent], ([nodeExtent, globalExtent], [oldNodeExtent, oldGlobalExtent]) => {
// update position if extent has actually changed // update position if extent has actually changed
if (nodeExtent !== oldNodeExtent || globalExtent !== oldGlobalExtent) { if (nodeExtent !== oldNodeExtent || globalExtent !== oldGlobalExtent) {
clampPosition() clampPosition()
@@ -179,10 +224,10 @@ const NodeWrapper = defineComponent({
// clamp initial position to nodes' extent // clamp initial position to nodes' extent
// if extent is parent, we need dimensions to properly clamp the position // if extent is parent, we need dimensions to properly clamp the position
if ( if (
node.value.extent === 'parent' || node.extent === 'parent' ||
(typeof node.value.extent === 'object' && 'range' in node.value.extent && node.value.extent.range === 'parent') (typeof node.extent === 'object' && 'range' in node.extent && node.extent.range === 'parent')
) { ) {
until(() => node.value.initialized) until(() => node.initialized)
.toBe(true) .toBe(true)
.then(clampPosition) .then(clampPosition)
} }
@@ -192,7 +237,7 @@ const NodeWrapper = defineComponent({
} }
return () => { return () => {
if (node.value.hidden) { if (node.hidden) {
return null return null
} }
@@ -200,31 +245,31 @@ const NodeWrapper = defineComponent({
'div', 'div',
{ {
'ref': nodeElement, 'ref': nodeElement,
'data-id': node.value.id, 'data-id': node.id,
'class': [ 'class': [
'vue-flow__node', 'vue-flow__node',
`vue-flow__node-${props.type === false ? 'default' : props.name}`, `vue-flow__node-${nodeCmp.value === false ? 'default' : node.type || 'default'}`,
{ {
[noPanClassName.value]: props.draggable, [noPanClassName.value]: isDraggable.value,
dragging: dragging?.value, dragging: dragging?.value,
draggable: props.draggable, draggable: isDraggable.value,
selected: node.value.selected, selected: node.selected,
selectable: props.selectable, selectable: isSelectable.value,
parent: node.value.isParent, parent: node.isParent,
}, },
getClass.value, getClass.value,
], ],
'style': { 'style': {
visibility: node.value.initialized ? 'visible' : 'hidden', visibility: node.initialized ? 'visible' : 'hidden',
zIndex: node.value.computedPosition.z ?? zIndex.value, zIndex: node.computedPosition.z ?? zIndex.value,
transform: `translate(${node.value.computedPosition.x}px,${node.value.computedPosition.y}px)`, transform: `translate(${node.computedPosition.x}px,${node.computedPosition.y}px)`,
pointerEvents: props.selectable || props.draggable ? 'all' : 'none', pointerEvents: isSelectable.value || isDraggable.value ? 'all' : 'none',
...getStyle.value, ...getStyle.value,
}, },
'tabIndex': props.focusable ? 0 : undefined, 'tabIndex': isFocusable.value ? 0 : undefined,
'role': props.focusable ? 'button' : undefined, 'role': isFocusable.value ? 'button' : undefined,
'aria-describedby': disableKeyboardA11y.value ? undefined : `${ARIA_NODE_DESC_KEY}-${vueFlowId}`, 'aria-describedby': disableKeyboardA11y.value ? undefined : `${ARIA_NODE_DESC_KEY}-${vueFlowId}`,
'aria-label': node.value.ariaLabel, 'aria-label': node.ariaLabel,
'onMouseenter': onMouseEnter, 'onMouseenter': onMouseEnter,
'onMousemove': onMouseMove, 'onMousemove': onMouseMove,
'onMouseleave': onMouseLeave, 'onMouseleave': onMouseLeave,
@@ -234,26 +279,26 @@ const NodeWrapper = defineComponent({
'onKeydown': onKeyDown, 'onKeydown': onKeyDown,
}, },
[ [
h(props.type === false ? getNodeTypes.value.default : props.type, { h(nodeCmp.value === false ? getNodeTypes.value.default : (nodeCmp.value as any), {
id: node.value.id, id: node.id,
type: node.value.type, type: node.type,
data: node.value.data, data: node.data,
events: { ...node.value.events, ...on }, events: { ...node.events, ...on },
selected: node.value.selected, selected: node.selected,
resizing: node.value.resizing, resizing: node.resizing,
dragging: dragging.value, dragging: dragging.value,
connectable: props.connectable, connectable: isConnectable.value,
position: node.value.computedPosition, position: node.computedPosition,
dimensions: node.value.dimensions, dimensions: node.dimensions,
isValidTargetPos: node.value.isValidTargetPos, isValidTargetPos: node.isValidTargetPos,
isValidSourcePos: node.value.isValidSourcePos, isValidSourcePos: node.isValidSourcePos,
parent: node.value.parentNode, parent: node.parentNode,
parentNodeId: node.value.parentNode, parentNodeId: node.parentNode,
zIndex: node.value.computedPosition.z ?? zIndex.value, zIndex: node.computedPosition.z ?? zIndex.value,
targetPosition: node.value.targetPosition, targetPosition: node.targetPosition,
sourcePosition: node.value.sourcePosition, sourcePosition: node.sourcePosition,
label: node.value.label, label: node.label,
dragHandle: node.value.dragHandle, dragHandle: node.dragHandle,
onUpdateNodeInternals: updateInternals, onUpdateNodeInternals: updateInternals,
}), }),
], ],
@@ -261,28 +306,22 @@ const NodeWrapper = defineComponent({
} }
/** this re-calculates the current position, necessary for clamping by a node's extent */ /** this re-calculates the current position, necessary for clamping by a node's extent */
function clampPosition() { function clampPosition() {
const nextPos = node.value.computedPosition const nextPos = node.computedPosition
if (snapToGrid.value) { if (snapToGrid.value) {
nextPos.x = snapGrid.value[0] * Math.round(nextPos.x / snapGrid.value[0]) nextPos.x = snapGrid.value[0] * Math.round(nextPos.x / snapGrid.value[0])
nextPos.y = snapGrid.value[1] * Math.round(nextPos.y / snapGrid.value[1]) nextPos.y = snapGrid.value[1] * Math.round(nextPos.y / snapGrid.value[1])
} }
const { computedPosition, position } = calcNextPosition( const { computedPosition, position } = calcNextPosition(node, nextPos, emits.error, nodeExtent.value, parentNode.value)
node.value,
nextPos,
emits.error,
nodeExtent.value,
parentNode.value,
)
// only overwrite positions if there are changes when clamping // only overwrite positions if there are changes when clamping
if (node.value.computedPosition.x !== computedPosition.x || node.value.computedPosition.y !== computedPosition.y) { if (node.computedPosition.x !== computedPosition.x || node.computedPosition.y !== computedPosition.y) {
node.value.computedPosition = { ...node.value.computedPosition, ...computedPosition } node.computedPosition = { ...node.computedPosition, ...computedPosition }
} }
if (node.value.position.x !== position.x || node.value.position.y !== position.y) { if (node.position.x !== position.x || node.position.y !== position.y) {
node.value.position = position node.position = position
} }
} }
@@ -294,34 +333,34 @@ const NodeWrapper = defineComponent({
function onMouseEnter(event: MouseEvent) { function onMouseEnter(event: MouseEvent) {
if (!dragging?.value) { if (!dragging?.value) {
emit.mouseEnter({ event, node: node.value, connectedEdges: connectedEdges.value }) emit.mouseEnter({ event, node, connectedEdges: connectedEdges.value })
} }
} }
function onMouseMove(event: MouseEvent) { function onMouseMove(event: MouseEvent) {
if (!dragging?.value) { if (!dragging?.value) {
emit.mouseMove({ event, node: node.value, connectedEdges: connectedEdges.value }) emit.mouseMove({ event, node, connectedEdges: connectedEdges.value })
} }
} }
function onMouseLeave(event: MouseEvent) { function onMouseLeave(event: MouseEvent) {
if (!dragging?.value) { if (!dragging?.value) {
emit.mouseLeave({ event, node: node.value, connectedEdges: connectedEdges.value }) emit.mouseLeave({ event, node, connectedEdges: connectedEdges.value })
} }
} }
function onContextMenu(event: MouseEvent) { function onContextMenu(event: MouseEvent) {
return emit.contextMenu({ event, node: node.value, connectedEdges: connectedEdges.value }) return emit.contextMenu({ event, node, connectedEdges: connectedEdges.value })
} }
function onDoubleClick(event: MouseEvent) { function onDoubleClick(event: MouseEvent) {
return emit.doubleClick({ event, node: node.value, connectedEdges: connectedEdges.value }) return emit.doubleClick({ event, node, connectedEdges: connectedEdges.value })
} }
function onSelectNode(event: MouseEvent) { function onSelectNode(event: MouseEvent) {
if (props.selectable && (!selectNodesOnDrag.value || !props.draggable || nodeDragThreshold.value > 0)) { if (isSelectable.value && (!selectNodesOnDrag.value || !isDraggable.value || nodeDragThreshold.value > 0)) {
handleNodeClick( handleNodeClick(
node.value, node,
multiSelectionActive.value, multiSelectionActive.value,
addSelectedNodes, addSelectedNodes,
removeSelectedNodes, removeSelectedNodes,
@@ -331,7 +370,7 @@ const NodeWrapper = defineComponent({
) )
} }
emit.click({ event, node: node.value, connectedEdges: connectedEdges.value }) emit.click({ event, node, connectedEdges: connectedEdges.value })
} }
function onKeyDown(event: KeyboardEvent) { function onKeyDown(event: KeyboardEvent) {
@@ -339,11 +378,11 @@ const NodeWrapper = defineComponent({
return return
} }
if (elementSelectionKeys.includes(event.key) && props.selectable) { if (elementSelectionKeys.includes(event.key) && isSelectable.value) {
const unselect = event.key === 'Escape' const unselect = event.key === 'Escape'
handleNodeClick( handleNodeClick(
node.value, node,
multiSelectionActive.value, multiSelectionActive.value,
addSelectedNodes, addSelectedNodes,
removeSelectedNodes, removeSelectedNodes,
@@ -351,9 +390,9 @@ const NodeWrapper = defineComponent({
unselect, unselect,
nodeElement.value!, nodeElement.value!,
) )
} else if (props.draggable && node.value.selected && arrowKeyDiffs[event.key]) { } else if (isDraggable.value && node.selected && arrowKeyDiffs[event.key]) {
ariaLiveMessage.value = `Moved selected node ${event.key.replace('Arrow', '').toLowerCase()}. New position, x: ${~~node ariaLiveMessage.value = `Moved selected node ${event.key.replace('Arrow', '').toLowerCase()}. New position, x: ${~~node
.value.position.x}, y: ${~~node.value.position.y}` .position.x}, y: ${~~node.position.y}`
updateNodePositions( updateNodePositions(
{ {
+1 -1
View File
@@ -21,7 +21,7 @@ export function useEdge<Data = ElementData, CustomEvents extends Record<string,
const { findEdge, emits } = useVueFlow() const { findEdge, emits } = useVueFlow()
const edge = findEdge<Data, CustomEvents>(edgeId) const edge = findEdge<Data, CustomEvents>(edgeId)!
if (!edge) { if (!edge) {
emits.error(new VueFlowError(ErrorCode.EDGE_NOT_FOUND, edgeId)) emits.error(new VueFlowError(ErrorCode.EDGE_NOT_FOUND, edgeId))
@@ -1,66 +1,11 @@
<script lang="ts" setup> <script lang="ts" setup>
import { getCurrentInstance, inject, resolveComponent } from 'vue'
import EdgeWrapper from '../../components/Edges/EdgeWrapper' import EdgeWrapper from '../../components/Edges/EdgeWrapper'
import ConnectionLine from '../../components/ConnectionLine' import ConnectionLine from '../../components/ConnectionLine'
import type { EdgeComponent, EdgeUpdatable, GraphEdge } from '../../types'
import { Slots } from '../../context'
import { useVueFlow } from '../../composables' import { useVueFlow } from '../../composables'
import { ErrorCode, VueFlowError, getEdgeZIndex } from '../../utils' import { getEdgeZIndex } from '../../utils'
import MarkerDefinitions from './MarkerDefinitions.vue' import MarkerDefinitions from './MarkerDefinitions.vue'
const slots = inject(Slots) const { findNode, getEdges, elevateEdgesOnSelect, dimensions } = useVueFlow()
const {
edgesUpdatable,
edgesFocusable,
elementsSelectable,
findNode,
getEdges,
getEdgeTypes,
elevateEdgesOnSelect,
dimensions,
emits,
} = useVueFlow()
const instance = getCurrentInstance()
function selectable(edgeSelectable?: boolean) {
return typeof edgeSelectable === 'undefined' ? elementsSelectable.value : edgeSelectable
}
function updatable(edgeUpdatable?: EdgeUpdatable) {
return typeof edgeUpdatable === 'undefined' ? edgesUpdatable.value : edgeUpdatable
}
function focusable(edgeFocusable?: boolean) {
return typeof edgeFocusable === 'undefined' ? edgesFocusable.value : edgeFocusable
}
function getType(type?: string, template?: GraphEdge['template']) {
const name = type || 'default'
const slot = slots?.[`edge-${name}`]
if (slot) {
return slot
}
let edgeType = template ?? getEdgeTypes.value[name]
if (typeof edgeType === 'string') {
if (instance) {
const components = Object.keys(instance.appContext.components)
if (components && components.includes(name)) {
edgeType = resolveComponent(name, false) as EdgeComponent
}
}
}
if (edgeType && typeof edgeType !== 'string') {
return edgeType
}
emits.error(new VueFlowError(ErrorCode.EDGE_TYPE_MISSING, edgeType))
return false
}
</script> </script>
<script lang="ts"> <script lang="ts">
@@ -77,18 +22,11 @@ export default {
<svg <svg
v-for="edge of getEdges" v-for="edge of getEdges"
:key="edge.id" :key="edge.id"
v-memo="[edge.id]"
class="vue-flow__edges vue-flow__container" class="vue-flow__edges vue-flow__container"
:style="{ zIndex: getEdgeZIndex(edge, findNode, elevateEdgesOnSelect) }" :style="{ zIndex: getEdgeZIndex(edge, findNode, elevateEdgesOnSelect) }"
> >
<EdgeWrapper <EdgeWrapper :id="edge.id" />
:id="edge.id"
:edge="edge"
:type="getType(edge.type, edge.template)"
:name="edge.type || 'default'"
:selectable="selectable(edge.selectable)"
:updatable="updatable(edge.updatable)"
:focusable="focusable(edge.focusable)"
/>
</svg> </svg>
<ConnectionLine /> <ConnectionLine />
@@ -1,35 +1,19 @@
<script lang="ts" setup> <script lang="ts" setup>
import { getCurrentInstance, inject, nextTick, onBeforeUnmount, onMounted, ref, resolveComponent, watch } from 'vue' import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { NodeWrapper } from '../../components' import { NodeWrapper } from '../../components'
import type { GraphNode, HandleConnectable, NodeComponent } from '../../types'
import { Slots } from '../../context'
import { useVueFlow } from '../../composables' import { useVueFlow } from '../../composables'
import { ErrorCode, VueFlowError } from '../../utils'
import { useNodesInitialized } from '../../composables/useNodesInitialized' import { useNodesInitialized } from '../../composables/useNodesInitialized'
const { const { getNodes, updateNodeDimensions, emits } = useVueFlow()
getNodes,
nodesDraggable,
nodesFocusable,
elementsSelectable,
nodesConnectable,
getNodeTypes,
updateNodeDimensions,
emits,
} = useVueFlow()
const nodesInitialized = useNodesInitialized() const nodesInitialized = useNodesInitialized()
const slots = inject(Slots)
const resizeObserver = ref<ResizeObserver>() const resizeObserver = ref<ResizeObserver>()
const instance = getCurrentInstance()
watch( watch(
nodesInitialized, nodesInitialized,
(initialized) => { (isInit) => {
if (initialized) { if (isInit) {
nextTick(() => { nextTick(() => {
emits.nodesInitialized(getNodes.value) emits.nodesInitialized(getNodes.value)
}) })
@@ -55,47 +39,6 @@ onMounted(() => {
}) })
onBeforeUnmount(() => resizeObserver.value?.disconnect()) onBeforeUnmount(() => resizeObserver.value?.disconnect())
function draggable(nodeDraggable?: boolean) {
return typeof nodeDraggable === 'undefined' ? nodesDraggable.value : nodeDraggable
}
function selectable(nodeSelectable?: boolean) {
return typeof nodeSelectable === 'undefined' ? elementsSelectable.value : nodeSelectable
}
function connectable(nodeConnectable?: HandleConnectable) {
return typeof nodeConnectable === 'undefined' ? nodesConnectable.value : nodeConnectable
}
function focusable(nodeFocusable?: boolean) {
return typeof nodeFocusable === 'undefined' ? nodesFocusable.value : nodeFocusable
}
function getType(type?: string, template?: GraphNode['template']) {
const name = type || 'default'
const slot = slots?.[`node-${name}`]
if (slot) {
return slot
}
let nodeType = template ?? getNodeTypes.value[name]
if (typeof nodeType === 'string') {
if (instance) {
const components = Object.keys(instance.appContext.components)
if (components && components.includes(name)) {
nodeType = resolveComponent(name, false) as NodeComponent
}
}
}
if (nodeType && typeof nodeType !== 'string') {
return nodeType
}
emits.error(new VueFlowError(ErrorCode.NODE_TYPE_MISSING, nodeType))
return false
}
</script> </script>
<script lang="ts"> <script lang="ts">
@@ -108,19 +51,7 @@ export default {
<template> <template>
<div class="vue-flow__nodes vue-flow__container"> <div class="vue-flow__nodes vue-flow__container">
<template v-if="resizeObserver"> <template v-if="resizeObserver">
<NodeWrapper <NodeWrapper v-for="node of getNodes" :id="node.id" :key="node.id" v-memo="[node.id]" :resize-observer="resizeObserver" />
v-for="node of getNodes"
:id="node.id"
:key="node.id"
:resize-observer="resizeObserver"
:type="getType(node.type, node.template)"
:name="node.type || 'default'"
:draggable="draggable(node.draggable)"
:selectable="selectable(node.selectable)"
:connectable="connectable(node.connectable)"
:focusable="focusable(node.focusable)"
:node="node"
/>
</template> </template>
</div> </div>
</template> </template>