refactor(core): rename core pkg dir to core

This commit is contained in:
braks
2022-10-10 21:33:44 +02:00
committed by Braks
parent f7dd7f1803
commit 082050b164
87 changed files with 640 additions and 0 deletions
+176
View File
@@ -0,0 +1,176 @@
import { isGraphEdge, isGraphNode } from './graph'
import type {
Edge,
EdgeAddChange,
EdgeChange,
EdgeRemoveChange,
EdgeSelectionChange,
ElementChange,
FlowElement,
FlowElements,
GraphEdge,
GraphNode,
Node,
NodeAddChange,
NodeChange,
NodeRemoveChange,
NodeSelectionChange,
} from '~/types'
function handleParentExpand(updateItem: GraphNode, parent: GraphNode) {
if (parent) {
const extendWidth = updateItem.position.x + updateItem.dimensions.width - parent.dimensions.width
const extendHeight = updateItem.position.y + updateItem.dimensions.height - parent.dimensions.height
if (extendWidth > 0 || extendHeight > 0 || updateItem.position.x < 0 || updateItem.position.y < 0) {
parent.style = { ...parent.style } || {}
parent.style.width = parent.style.width ?? parent.dimensions.width
parent.style.height = parent.style.height ?? parent.dimensions.height
if (extendWidth > 0) {
if (typeof parent.style.width === 'string') {
const currWidth = parseInt(parent.style.width, 10)
parent.style.width = `${currWidth + extendWidth}px`
} else {
parent.style.width += extendWidth
}
}
if (extendHeight > 0) {
if (typeof parent.style.height === 'string') {
const currWidth = parseInt(parent.style.height, 10)
parent.style.height = `${currWidth + extendHeight}px`
} else {
parent.style.height += extendHeight
}
}
if (updateItem.position.x < 0) {
const xDiff = Math.abs(updateItem.position.x)
parent.position.x = parent.position.x - xDiff
if (typeof parent.style.width === 'string') {
const currWidth = parseInt(parent.style.width, 10)
parent.style.width = `${currWidth + xDiff}px`
} else {
;(parent.style as any).width += xDiff
}
updateItem.position.x = 0
}
if (updateItem.position.y < 0) {
const yDiff = Math.abs(updateItem.position.y)
parent.position.y = parent.position.y - yDiff
if (typeof parent.style.height === 'string') {
const currWidth = parseInt(parent.style.height, 10)
parent.style.height = `${currWidth + yDiff}px`
} else {
;(parent.style as any).height += yDiff
}
updateItem.position.y = 0
}
}
}
}
export const applyChanges = <
T extends Node | Edge | FlowElement = Node,
C extends ElementChange = T extends GraphNode ? NodeChange : EdgeChange,
>(
changes: C[],
elements: T[],
): T[] => {
let elementIds = elements.map((el) => el.id)
changes.forEach((change) => {
if (change.type === 'add') {
const item = <T>change.item
return elements.push(item)
}
const i = elementIds.indexOf((<any>change).id)
const el = elements[i]
switch (change.type) {
case 'select':
if (isGraphNode(el) || isGraphEdge(el)) el.selected = change.selected
break
case 'position':
if (isGraphNode(el)) {
if (typeof change.position !== 'undefined') el.position = change.position
if (typeof change.computedPosition !== 'undefined') {
el.computedPosition = { ...el.computedPosition, ...change.computedPosition }
}
if (el.expandParent && el.parentNode) {
const parent = elements[elementIds.indexOf(el.parentNode)]
if (parent && isGraphNode(parent)) {
handleParentExpand(el, parent)
}
}
}
break
case 'dimensions':
if (isGraphNode(el)) {
if (typeof change.dimensions !== 'undefined') el.dimensions = change.dimensions
if (el.expandParent && el.parentNode) {
const parent = elements[elementIds.indexOf(el.parentNode)]
if (parent && isGraphNode(parent)) {
handleParentExpand(el, parent)
}
}
}
break
case 'remove':
if (elementIds.includes(change.id)) {
elements.splice(i, 1)
elementIds = elements.map((el) => el.id)
}
break
}
})
return elements
}
export const applyEdgeChanges = (changes: EdgeChange[], edges: GraphEdge[]) => applyChanges(changes, edges)
export const applyNodeChanges = (changes: NodeChange[], nodes: GraphNode[]) => applyChanges(changes, nodes)
export const createSelectionChange = (id: string, selected: boolean): NodeSelectionChange | EdgeSelectionChange => ({
id,
type: 'select',
selected,
})
export const createAdditionChange = <
T extends GraphNode | GraphEdge = GraphNode,
C extends NodeAddChange | EdgeAddChange = T extends GraphNode ? NodeAddChange : EdgeAddChange,
>(
item: T,
): C =>
<C>{
item,
type: 'add',
}
export const createRemoveChange = (id: string): NodeRemoveChange | EdgeRemoveChange => ({
id,
type: 'remove',
})
export const getSelectionChanges = (items: FlowElements, selectedIds: string[]) => {
return items.reduce((res, item) => {
const willBeSelected = selectedIds.includes(item.id)
if (!item.selected && willBeSelected) {
item.selected = true
res.push(createSelectionChange(item.id, true))
} else if (item.selected && !willBeSelected) {
item.selected = false
res.push(createSelectionChange(item.id, false))
}
return res
}, [] as (NodeSelectionChange | EdgeSelectionChange)[])
}
+112
View File
@@ -0,0 +1,112 @@
import type { Ref } from 'vue'
import { clampPosition, isParentSelected } from './graph'
import type { ComputedGetters, CoordinateExtent, Getters, GraphNode, NodeDragItem, SnapGrid, XYPosition } from '~/types'
export function hasSelector(target: Element, selector: string, node: Ref<Element>): boolean {
let current = target
do {
if (current && current.matches(selector)) return true
else if (current === node.value) return false
current = current.parentElement as Element
} while (current)
return false
}
export function getDragItems(
nodes: GraphNode[],
mousePos: XYPosition,
getNode: Getters['getNode'],
nodeId?: string,
): NodeDragItem[] {
return nodes
.filter((n) => (n.selected || n.id === nodeId) && (!n.parentNode || !isParentSelected(n, getNode)))
.map((n) =>
markRaw({
id: n.id,
position: n.computedPosition || { x: 0, y: 0, z: 0 },
distance: {
x: mousePos.x - n.computedPosition?.x || 0,
y: mousePos.y - n.computedPosition?.y || 0,
},
from: n.computedPosition,
extent: n.extent,
parentNode: n.parentNode,
dimensions: n.dimensions,
}),
)
}
export function getEventHandlerParams({
id,
dragItems,
getNode,
}: {
id?: string
dragItems: NodeDragItem[]
getNode: ComputedGetters['getNode']
}): [GraphNode, GraphNode[]] {
const extendedDragItems: GraphNode[] = dragItems.map((n) => {
const node = getNode.value(n.id)!
return {
...node,
}
})
return [id ? extendedDragItems.find((n) => n.id === id)! : extendedDragItems[0], extendedDragItems]
}
export function updatePosition(
dragItem: NodeDragItem,
mousePos: XYPosition,
snapToGrid?: boolean,
snapGrid?: SnapGrid,
parent?: GraphNode,
nodeExtent?: CoordinateExtent,
): NodeDragItem {
const nextPosition = { x: mousePos.x - dragItem.distance.x, y: mousePos.y - dragItem.distance.y }
if (snapToGrid && snapGrid) {
const [snapX, snapY] = snapGrid
nextPosition.x = snapX * Math.round(nextPosition.x / snapX)
nextPosition.y = snapY * Math.round(nextPosition.y / snapY)
}
const currentExtent = applyExtent(dragItem, nodeExtent, parent)
dragItem.position = currentExtent ? clampPosition(nextPosition, currentExtent as CoordinateExtent) : nextPosition
return dragItem
}
export function applyExtent<T extends NodeDragItem | GraphNode>(item: T, extent?: CoordinateExtent, parent?: GraphNode) {
let currentExtent = item.extent || extent
if (item.extent === 'parent' && parent) {
if (item.parentNode && item.dimensions.width && item.dimensions.height) {
currentExtent =
parent.computedPosition && parent.dimensions.width && parent.dimensions.height
? [
[parent.computedPosition.x, parent.computedPosition.y],
[
parent.computedPosition.x + parent.dimensions.width - item.dimensions.width,
parent.computedPosition.y + parent.dimensions.height - item.dimensions.height,
],
]
: currentExtent
}
} else if (item.extent && item.parentNode) {
const itemExtent = item.extent as CoordinateExtent
const parentX = parent?.computedPosition?.x ?? 0
const parentY = parent?.computedPosition?.y ?? 0
currentExtent = [
[itemExtent[0][0] + parentX, itemExtent[0][1] + parentY],
[itemExtent[1][0] + parentX, itemExtent[1][1] + parentY],
]
}
return currentExtent
}
+160
View File
@@ -0,0 +1,160 @@
import { rectToBox } from './graph'
import type { EdgePositions, Getters, GraphEdge, GraphNode, HandleElement, Rect, Viewport, XYPosition } from '~/types'
import { Position } from '~/types'
export const getHandlePosition = (position: Position, rect: Rect, handle?: HandleElement): XYPosition => {
const x = (handle?.x ?? 0) + rect.x
const y = (handle?.y ?? 0) + rect.y
const width = handle?.width ?? rect.width
const height = handle?.height ?? rect.height
switch (position) {
case Position.Top:
return {
x: x + width / 2,
y,
}
case Position.Right:
return {
x: x + width,
y: y + height / 2,
}
case Position.Bottom:
return {
x: x + width / 2,
y: y + height,
}
case Position.Left:
return {
x,
y: y + height / 2,
}
}
}
export const getHandle = (bounds: HandleElement[] = [], handleId?: string | null): HandleElement | undefined => {
if (!bounds.length) return undefined
let handle
if (!handleId && bounds.length === 1) handle = bounds[0]
else if (handleId) handle = bounds.find((d) => d.id === handleId)
return handle || bounds[0]
}
export const getEdgePositions = (
sourceNode: GraphNode,
sourceHandle: HandleElement | undefined,
sourcePosition: Position,
targetNode: GraphNode,
targetHandle: HandleElement | undefined,
targetPosition: Position,
): EdgePositions => {
const sourceHandlePos = getHandlePosition(
sourcePosition,
{
...sourceNode.dimensions,
...sourceNode.computedPosition,
},
sourceHandle,
)
const targetHandlePos = getHandlePosition(
targetPosition,
{
...targetNode.dimensions,
...targetNode.computedPosition,
},
targetHandle,
)
return {
sourceX: sourceHandlePos.x,
sourceY: sourceHandlePos.y,
targetX: targetHandlePos.x,
targetY: targetHandlePos.y,
}
}
interface IsEdgeVisibleParams {
sourcePos: XYPosition
targetPos: XYPosition
sourceWidth: number
sourceHeight: number
targetWidth: number
targetHeight: number
width: number
height: number
viewport: Viewport
}
export function isEdgeVisible({
sourcePos,
targetPos,
sourceWidth,
sourceHeight,
targetWidth,
targetHeight,
width,
height,
viewport,
}: IsEdgeVisibleParams): boolean {
const edgeBox = {
x: Math.min(sourcePos.x, targetPos.x),
y: Math.min(sourcePos.y, targetPos.y),
x2: Math.max(sourcePos.x + sourceWidth, targetPos.x + targetWidth),
y2: Math.max(sourcePos.y + sourceHeight, targetPos.y + targetHeight),
}
if (edgeBox.x === edgeBox.x2) {
edgeBox.x2 += 1
}
if (edgeBox.y === edgeBox.y2) {
edgeBox.y2 += 1
}
const viewBox = rectToBox({
x: (0 - viewport.x) / viewport.zoom,
y: (0 - viewport.y) / viewport.zoom,
width: width / viewport.zoom,
height: height / viewport.zoom,
})
const xOverlap = Math.max(0, Math.min(viewBox.x2, edgeBox.x2) - Math.max(viewBox.x, edgeBox.x))
const yOverlap = Math.max(0, Math.min(viewBox.y2, edgeBox.y2) - Math.max(viewBox.y, edgeBox.y))
const overlappingArea = Math.ceil(xOverlap * yOverlap)
return overlappingArea > 0
}
export const groupEdgesByZLevel = (edges: GraphEdge[], getNode: Getters['getNode']) => {
let maxLevel = -1
const levelLookup = edges.reduce<Record<string, GraphEdge[]>>((tree, edge) => {
const source = getNode(edge.source)
const target = getNode(edge.target)
if (!source || !target) return tree
const z = edge.z ? edge.z : Math.max(source.computedPosition.z || 0, target.computedPosition.z || 0)
if (tree[z]) {
tree[z].push(edge)
} else {
tree[z] = [edge]
}
maxLevel = z > maxLevel ? z : maxLevel
return tree
}, {})
return Object.entries(Object.keys(levelLookup).length ? levelLookup : { 0: [] }).map(([key, edges]) => {
const level = +key
return {
edges,
level,
isMaxLevel: level === maxLevel,
}
})
}
+334
View File
@@ -0,0 +1,334 @@
import type {
Box,
Connection,
CoordinateExtent,
DefaultEdgeOptions,
Dimensions,
Edge,
EdgeMarkerType,
Elements,
FlowElement,
Getters,
GraphEdge,
GraphNode,
Node,
Rect,
Viewport,
XYPosition,
XYZPosition,
} from '~/types'
import { useWindow } from '~/composables'
export const getDimensions = (node: HTMLElement): Dimensions => ({
width: node.offsetWidth,
height: node.offsetHeight,
})
export const clamp = (val: number, min = 0, max = 1) => Math.min(Math.max(val, min), max)
export const clampPosition = (position: XYPosition, extent: CoordinateExtent): XYPosition => ({
x: clamp(position.x, extent[0][0], extent[1][0]),
y: clamp(position.y, extent[0][1], extent[1][1]),
})
export const getHostForElement = (element: HTMLElement): Document => {
const doc = element.getRootNode() as Document
const window = useWindow()
if ('elementFromPoint' in doc) return doc
else return window.document
}
type MaybeElement = Node | Edge | Connection | FlowElement
export const isEdge = (element: MaybeElement): element is Edge =>
element && 'id' in element && 'source' in element && 'target' in element
export const isGraphEdge = (element: MaybeElement): element is GraphEdge =>
isEdge(element) && 'sourceNode' in element && 'targetNode' in element
export const isNode = (element: MaybeElement): element is Node => element && 'id' in element && !isEdge(element)
export const isGraphNode = (element: MaybeElement): element is GraphNode => isNode(element) && 'computedPosition' in element
export const parseNode = (node: Node, nodeExtent: CoordinateExtent, defaults?: Partial<GraphNode>): GraphNode => {
let defaultValues = defaults
if (!isGraphNode(node)) {
defaultValues = {
type: node.type ?? 'default',
dimensions: markRaw({
width: 0,
height: 0,
}),
handleBounds: shallowReactive({
source: [],
target: [],
}),
computedPosition: markRaw({
z: 0,
...node.position,
}),
draggable: undefined,
selectable: undefined,
connectable: undefined,
...defaults,
}
}
return {
...defaultValues,
...(node as GraphNode),
id: node.id.toString(),
}
}
export const parseEdge = (edge: Edge, defaults?: Partial<GraphEdge>): GraphEdge => {
defaults = !isGraphEdge(edge)
? ({
sourceHandle: edge.sourceHandle ? edge.sourceHandle.toString() : undefined,
targetHandle: edge.targetHandle ? edge.targetHandle.toString() : undefined,
type: edge.type,
source: edge.source.toString(),
target: edge.target.toString(),
z: 0,
sourceX: 0,
sourceY: 0,
targetX: 0,
targetY: 0,
updatable: edge.updatable,
selectable: edge.selectable,
data: edge.data,
...defaults,
} as GraphEdge)
: defaults
return Object.assign({ id: edge.id.toString() }, edge, defaults) as GraphEdge
}
const getConnectedElements = (node: GraphNode, elements: Elements, dir: 'source' | 'target') => {
if (!isNode(node)) return []
const origin = dir === 'source' ? 'target' : 'source'
const ids = elements.filter((e) => isEdge(e) && e[origin] === node.id).map((e) => isEdge(e) && e[dir])
return elements.filter((e) => ids.includes(e.id))
}
export const getOutgoers = (node: GraphNode, elements: Elements) => getConnectedElements(node, elements, 'target')
export const getIncomers = (node: GraphNode, elements: Elements) => getConnectedElements(node, elements, 'source')
export const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection) =>
`vueflow__edge-${source}${sourceHandle ?? ''}-${target}${targetHandle ?? ''}`
export const connectionExists = (edge: Edge | Connection, elements: Elements) =>
elements.some(
(el) =>
isEdge(el) &&
el.source === edge.source &&
el.target === edge.target &&
(el.sourceHandle === edge.sourceHandle || (!el.sourceHandle && !edge.sourceHandle)) &&
(el.targetHandle === edge.targetHandle || (!el.targetHandle && !edge.targetHandle)),
)
/**
* Intended for options API
* In composition API you can access utilities from `useVueFlow`
*/
export const addEdge = (edgeParams: Edge | Connection, elements: Elements, defaults?: DefaultEdgeOptions) => {
if (!edgeParams.source || !edgeParams.target) {
console.warn("[vueflow]: Can't create edge. An edge needs a source and a target.")
return elements
}
let edge
if (isEdge(edgeParams)) {
edge = { ...edgeParams }
} else {
edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge
}
edge = parseEdge(edge, defaults)
if (connectionExists(edge, elements)) return elements
elements.push(edge)
return elements
}
/**
* Intended for options API
* In composition API you can access utilities from `useVueFlow`
*/
export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: Elements) => {
if (!newConnection.source || !newConnection.target) {
console.warn("[vueflow]: Can't create new edge. An edge needs a source and a target.")
return elements
}
const foundEdge = elements.find((e) => isEdge(e) && e.id === oldEdge.id)
if (!foundEdge) {
console.warn(`[vueflow]: The old edge with id=${oldEdge.id} does not exist.`)
return elements
}
// Remove old edge and create the new edge with parameters of old edge.
const edge: Edge = {
...oldEdge,
id: getEdgeId(newConnection),
source: newConnection.source,
target: newConnection.target,
sourceHandle: newConnection.sourceHandle,
targetHandle: newConnection.targetHandle,
}
elements.splice(elements.indexOf(foundEdge), 1, edge)
return elements.filter((e) => e.id !== oldEdge.id)
}
export const pointToRendererPoint = (
{ x, y }: XYPosition,
{ x: tx, y: ty, zoom: tScale }: Viewport,
snapToGrid: boolean,
[snapX, snapY]: [number, number],
) => {
const position: XYPosition = {
x: (x - tx) / tScale,
y: (y - ty) / tScale,
}
if (snapToGrid) {
return {
x: snapX * Math.round(position.x / snapX),
y: snapY * Math.round(position.y / snapY),
}
}
return position
}
const getBoundsOfBoxes = (box1: Box, box2: Box): Box => ({
x: Math.min(box1.x, box2.x),
y: Math.min(box1.y, box2.y),
x2: Math.max(box1.x2, box2.x2),
y2: Math.max(box1.y2, box2.y2),
})
export const rectToBox = ({ x, y, width, height }: Rect): Box => ({
x,
y,
x2: x + width,
y2: y + height,
})
export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
x,
y,
width: x2 - x,
height: y2 - y,
})
export const getBoundsofRects = (rect1: Rect, rect2: Rect) => boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)))
export const getRectOfNodes = (nodes: GraphNode[]) => {
const box = nodes.reduce(
(currBox, { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = {} as any) =>
getBoundsOfBoxes(
currBox,
rectToBox({
...computedPosition,
...dimensions,
} as Rect),
),
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity },
)
return boxToRect(box)
}
export const graphPosToZoomedPos = ({ x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: Viewport): XYPosition => ({
x: x * tScale + tx,
y: y * tScale + ty,
})
export const getNodesInside = (
nodes: GraphNode[],
rect: Rect,
{ x: tx, y: ty, zoom: tScale }: Viewport = { x: 0, y: 0, zoom: 1 },
partially = false,
) => {
const rBox = rectToBox({
x: (rect.x - tx) / tScale,
y: (rect.y - ty) / tScale,
width: rect.width / tScale,
height: rect.height / tScale,
})
return nodes.filter((node) => {
if (!node || node.selectable === false) return false
const { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = node
const nBox = rectToBox({ ...computedPosition, ...dimensions })
const xOverlap = Math.max(0, Math.min(rBox.x2, nBox.x2) - Math.max(rBox.x, nBox.x))
const yOverlap = Math.max(0, Math.min(rBox.y2, nBox.y2) - Math.max(rBox.y, nBox.y))
const overlappingArea = Math.ceil(xOverlap * yOverlap)
const notInitialized =
typeof dimensions.width === 'undefined' ||
typeof dimensions.height === 'undefined' ||
dimensions.width === 0 ||
dimensions.height === 0
const partiallyVisible = partially && overlappingArea > 0
const area = dimensions.width * dimensions.height
return notInitialized || partiallyVisible || overlappingArea >= area
})
}
export const getConnectedEdges = (nodes: GraphNode[], edges: GraphEdge[]) => {
const nodeIds = nodes.map((node) => node.id)
return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target))
}
export const getTransformForBounds = (
bounds: Rect,
width: number,
height: number,
minZoom: number,
maxZoom: number,
padding = 0.1,
offset: {
x?: number
y?: number
} = { x: 0, y: 0 },
): Viewport => {
const xZoom = width / (bounds.width * (1 + padding))
const yZoom = height / (bounds.height * (1 + padding))
const zoom = Math.min(xZoom, yZoom)
const clampedZoom = clamp(zoom, minZoom, maxZoom)
const boundsCenterX = bounds.x + bounds.width / 2
const boundsCenterY = bounds.y + bounds.height / 2
const x = width / 2 - boundsCenterX * clampedZoom + (offset.x ?? 0)
const y = height / 2 - boundsCenterY * clampedZoom + (offset.y ?? 0)
return { x, y, zoom: clampedZoom }
}
export const getXYZPos = (parentPos: XYZPosition, computedPosition: XYZPosition): XYZPosition => {
return {
x: computedPosition.x + parentPos.x,
y: computedPosition.y + parentPos.y,
z: parentPos.z > computedPosition.z ? parentPos.z : computedPosition.z,
}
}
export const isParentSelected = (node: GraphNode, getNode: Getters['getNode']): boolean => {
if (!node.parentNode) return false
const parent = getNode(node.parentNode)
if (!parent) return false
if (parent.selected) return true
return isParentSelected(parent, getNode)
}
export const getMarkerId = (marker: EdgeMarkerType | undefined): string => {
if (typeof marker === 'undefined') return ''
if (typeof marker === 'string') return marker
return Object.keys(marker)
.sort()
.map((key) => `${key}=${marker[<keyof EdgeMarkerType>key]}`)
.join('&')
}
+5
View File
@@ -0,0 +1,5 @@
export * from './edge'
export * from './graph'
export * from './node'
export * from './changes'
export * from './store'
+42
View File
@@ -0,0 +1,42 @@
import type { Ref } from 'vue'
import { getDimensions } from './graph'
import type { Actions, GraphNode, HandleElement, Position } from '~/types'
export const getHandleBounds = (selector: string, nodeElement: HTMLDivElement, zoom: number): HandleElement[] | undefined => {
const handles = nodeElement.querySelectorAll(selector)
if (!handles || !handles.length) {
return undefined
}
const handlesArray = Array.from(handles) as HTMLDivElement[]
const nodeBounds = nodeElement.getBoundingClientRect()
return handlesArray.map((handle): HandleElement => {
const handleBounds = handle.getBoundingClientRect()
return {
id: handle.getAttribute('data-handleid'),
position: handle.getAttribute('data-handlepos') as unknown as Position,
x: (handleBounds.left - nodeBounds.left) / zoom,
y: (handleBounds.top - nodeBounds.top) / zoom,
...getDimensions(handle),
}
})
}
export const handleNodeClick = (
node: GraphNode,
multiSelectionActive: boolean,
addSelectedNodes: Actions['addSelectedNodes'],
removeSelectedElements: Actions['removeSelectedElements'],
nodesSelectionActive: Ref<boolean>,
) => {
nodesSelectionActive.value = false
if (!node.selected) {
addSelectedNodes([node])
} else if (node.selected && multiSelectionActive) {
removeSelectedElements({ nodes: [node] })
}
}
+91
View File
@@ -0,0 +1,91 @@
import type { Connection, CoordinateExtent, Edge, Getters, GraphEdge, GraphNode, Node } from '~/types'
import { connectionExists, getEdgeId, isEdge, isGraphEdge, parseEdge, parseNode } from '~/utils/graph'
export const isDef = <T>(val: T): val is NonNullable<T> => typeof val !== 'undefined'
export const addEdgeToStore = (edgeParams: Edge | Connection, edges: Edge[]) => {
if (!edgeParams.source || !edgeParams.target) {
console.warn("[vueflow]: Can't create edge. An edge needs a source and a target.")
return false
}
let edge
if (isEdge(edgeParams)) {
edge = { ...edgeParams }
} else {
edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge
}
edge = parseEdge(edge)
if (connectionExists(edge, edges)) return false
return edge
}
export const updateEdgeAction = (edge: GraphEdge, newConnection: Connection, edges: GraphEdge[]) => {
if (!newConnection.source || !newConnection.target) {
console.warn("[vueflow]: Can't create new edge. An edge needs a source and a target.")
return false
}
const foundEdge = edges.find((e) => isGraphEdge(e) && e.id === edge.id)
if (!foundEdge) {
console.warn(`[vueflow]: The old edge with id=${edge.id} does not exist.`)
return false
}
const newEdge = {
...edge,
id: getEdgeId(newConnection),
source: newConnection.source,
target: newConnection.target,
sourceHandle: newConnection.sourceHandle,
targetHandle: newConnection.targetHandle,
}
edges.splice(edges.indexOf(foundEdge), 1, newEdge)
return newEdge
}
export const createGraphNodes = (
nodes: Node[],
getNode: Getters['getNode'],
currGraphNodes: GraphNode[],
extent: CoordinateExtent,
) => {
const parentNodes: Record<string, true> = {}
const graphNodes = nodes.map((node) => {
const parsed = shallowReactive(
parseNode(node, extent, {
...getNode(node.id),
parentNode: node.parentNode,
}),
)
if (node.parentNode) {
parentNodes[node.parentNode] = true
}
return parsed
})
graphNodes.forEach((node) => {
const nextNodes = [...graphNodes, ...currGraphNodes]
if (node.parentNode && !nextNodes.find((n) => n.id === node.parentNode)) {
console.warn(`[vueflow]: Parent node ${node.parentNode} not found`)
}
if (node.parentNode || parentNodes[node.id]) {
if (parentNodes[node.id]) {
node.isParent = true
}
const parent = node.parentNode ? getNode(node.parentNode) : undefined
if (parent) parent.isParent = true
}
})
return graphNodes
}