chore(core): cleanup and replace const with function

Signed-off-by: braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
braks
2023-02-07 12:27:41 +01:00
committed by Braks
parent 5abe4ca2e5
commit bb2c4f449a
16 changed files with 183 additions and 164 deletions
@@ -18,7 +18,13 @@ let box = $ref<RectType>({ x: 0, y: 0, width: 0, height: 0 })
const el = $ref<SVGTextElement | null>(null) const el = $ref<SVGTextElement | null>(null)
const getBox = () => { const transform = computed(() => `translate(${x - box.width / 2} ${y - box.height / 2})`)
onMounted(getBox)
watch([() => x, () => y, $$(el), () => label], getBox)
function getBox() {
if (!el) return if (!el) return
const nextBox = el.getBBox() const nextBox = el.getBBox()
@@ -27,12 +33,6 @@ const getBox = () => {
box = nextBox box = nextBox
} }
} }
onMounted(getBox)
watch([() => x, () => y, $$(el), () => label], getBox)
const transform = computed(() => `translate(${x - box.width / 2} ${y - box.height / 2})`)
</script> </script>
<script lang="ts"> <script lang="ts">
@@ -23,6 +23,7 @@ const EdgeWrapper = defineComponent({
edgeUpdaterRadius, edgeUpdaterRadius,
emits, emits,
nodesSelectionActive, nodesSelectionActive,
noPanClassName,
getEdges, getEdges,
getEdgeTypes, getEdgeTypes,
removeSelectedEdges, removeSelectedEdges,
@@ -57,20 +58,6 @@ const EdgeWrapper = defineComponent({
const targetNode = $computed(() => findNode(edge.target)) const targetNode = $computed(() => findNode(edge.target))
const onEdgeUpdaterMouseEnter = () => (mouseOver = true)
const onEdgeUpdaterMouseOut = () => (mouseOver = false)
const onEdgeUpdate = (connection: Connection) => {
if (!connectionExists(connection, getEdges.value)) hooks.emit.update({ edge, connection })
}
const onEdgeUpdateEnd = () => {
if (!mouseEvent.value) return
hooks.emit.updateEnd({ event: mouseEvent.value, edge })
updating = false
}
const { handlePointerDown } = useHandle({ const { handlePointerDown } = useHandle({
nodeId, nodeId,
handleId, handleId,
@@ -81,61 +68,6 @@ const EdgeWrapper = defineComponent({
onEdgeUpdateEnd, onEdgeUpdateEnd,
}) })
const handleEdgeUpdater = (event: MouseEvent, isSourceHandle: boolean) => {
nodeId.value = isSourceHandle ? edge.target : edge.source
handleId.value = (isSourceHandle ? edge.targetHandle : edge.sourceHandle) ?? ''
type.value = isSourceHandle ? 'target' : 'source'
edgeUpdaterType.value = type.value
mouseEvent.value = event
hooks.emit.updateStart({ event, edge })
handlePointerDown(event)
}
const onEdgeClick = (event: MouseEvent) => {
const data = { event, edge }
if (props.selectable) {
nodesSelectionActive.value = false
addSelectedEdges([edge])
}
hooks.emit.click(data)
}
const onEdgeContextMenu = (event: MouseEvent) => hooks.emit.contextMenu({ event, edge })
const onDoubleClick = (event: MouseEvent) => hooks.emit.doubleClick({ event, edge })
const onEdgeMouseEnter = (event: MouseEvent) => hooks.emit.mouseEnter({ event, edge })
const onEdgeMouseMove = (event: MouseEvent) => hooks.emit.mouseMove({ event, edge })
const onEdgeMouseLeave = (event: MouseEvent) => hooks.emit.mouseLeave({ event, edge })
const onEdgeUpdaterSourceMouseDown = (event: MouseEvent) => {
updating = true
handleEdgeUpdater(event, true)
}
const onEdgeUpdaterTargetMouseDown = (event: MouseEvent) => {
updating = true
handleEdgeUpdater(event, false)
}
const onKeyDown = (event: KeyboardEvent) => {
if (elementSelectionKeys.includes(event.key) && props.selectable) {
const unselect = event.key === 'Escape'
if (unselect) {
edgeEl.value?.blur()
removeSelectedEdges([findEdge(props.id)!])
} else {
addSelectedEdges([findEdge(props.id)!])
}
}
}
return () => { return () => {
if (!sourceNode || !targetNode) return null if (!sourceNode || !targetNode) return null
@@ -181,6 +113,7 @@ const EdgeWrapper = defineComponent({
'class': [ 'class': [
'vue-flow__edge', 'vue-flow__edge',
`vue-flow__edge-${props.type === false ? 'default' : props.name}`, `vue-flow__edge-${props.type === false ? 'default' : props.name}`,
noPanClassName.value,
edgeClass, edgeClass,
{ {
updating: mouseOver, updating: mouseOver,
@@ -279,6 +212,89 @@ const EdgeWrapper = defineComponent({
], ],
) )
} }
function onEdgeUpdaterMouseEnter() {
mouseOver = true
}
function onEdgeUpdaterMouseOut() {
mouseOver = false
}
function onEdgeUpdate(connection: Connection) {
if (!connectionExists(connection, getEdges.value)) hooks.emit.update({ edge, connection })
}
function onEdgeUpdateEnd() {
if (!mouseEvent.value) return
hooks.emit.updateEnd({ event: mouseEvent.value, edge })
updating = false
}
function handleEdgeUpdater(event: MouseEvent, isSourceHandle: boolean) {
nodeId.value = isSourceHandle ? edge.target : edge.source
handleId.value = (isSourceHandle ? edge.targetHandle : edge.sourceHandle) ?? ''
type.value = isSourceHandle ? 'target' : 'source'
edgeUpdaterType.value = type.value
mouseEvent.value = event
hooks.emit.updateStart({ event, edge })
handlePointerDown(event)
}
function onEdgeClick(event: MouseEvent) {
const data = { event, edge }
if (props.selectable) {
nodesSelectionActive.value = false
addSelectedEdges([edge])
}
hooks.emit.click(data)
}
function onEdgeContextMenu(event: MouseEvent) {
hooks.emit.contextMenu({ event, edge })
}
function onDoubleClick(event: MouseEvent) {
hooks.emit.doubleClick({ event, edge })
}
function onEdgeMouseEnter(event: MouseEvent) {
hooks.emit.mouseEnter({ event, edge })
}
function onEdgeMouseMove(event: MouseEvent) {
hooks.emit.mouseMove({ event, edge })
}
function onEdgeMouseLeave(event: MouseEvent) {
hooks.emit.mouseLeave({ event, edge })
}
function onEdgeUpdaterSourceMouseDown(event: MouseEvent) {
updating = true
handleEdgeUpdater(event, true)
}
function onEdgeUpdaterTargetMouseDown(event: MouseEvent) {
updating = true
handleEdgeUpdater(event, false)
}
function onKeyDown(event: KeyboardEvent) {
if (elementSelectionKeys.includes(event.key) && props.selectable) {
const unselect = event.key === 'Escape'
if (unselect) {
edgeEl.value?.blur()
removeSelectedEdges([findEdge(props.id)!])
} else {
addSelectedEdges([findEdge(props.id)!])
}
}
}
}, },
}) })
@@ -4,6 +4,7 @@ import type { PanelProps } from '../../types'
const props = defineProps<PanelProps>() const props = defineProps<PanelProps>()
const { userSelectionActive } = useVueFlow() const { userSelectionActive } = useVueFlow()
const positionClasses = computed(() => `${props.position}`.split('-')) const positionClasses = computed(() => `${props.position}`.split('-'))
</script> </script>
@@ -19,14 +19,9 @@ const {
getEdges, getEdges,
getNodesInitialized, getNodesInitialized,
getEdgeTypes, getEdgeTypes,
noPanClassName,
elevateEdgesOnSelect, elevateEdgesOnSelect,
} = $(useVueFlow()) } = $(useVueFlow())
const selectable = (s?: boolean) => (typeof s === 'undefined' ? elementsSelectable : s)
const updatable = (u?: EdgeUpdatable) => (typeof u === 'undefined' ? edgesUpdatable : u)
const focusable = (f?: boolean) => (typeof f === 'undefined' ? edgesFocusable : f)
const sourceNode = $( const sourceNode = $(
controlledComputed( controlledComputed(
() => connectionStartHandle?.nodeId, () => connectionStartHandle?.nodeId,
@@ -73,7 +68,11 @@ onBeforeUnmount(() => {
stop?.() stop?.()
}) })
const getType = (type?: string, template?: GraphEdge['template']) => { const selectable = (edgeSelectable?: boolean) => (typeof edgeSelectable === 'undefined' ? elementsSelectable : edgeSelectable)
const updatable = (edgeUpdatable?: EdgeUpdatable) => (typeof edgeUpdatable === 'undefined' ? edgesUpdatable : edgeUpdatable)
const focusable = (edgeFocusable?: boolean) => (typeof edgeFocusable === 'undefined' ? edgesFocusable : edgeFocusable)
function getType(type?: string, template?: GraphEdge['template']) {
const name = type || 'default' const name = type || 'default'
let edgeType = template ?? getEdgeTypes[name] let edgeType = template ?? getEdgeTypes[name]
const instance = getCurrentInstance() const instance = getCurrentInstance()
@@ -96,11 +95,6 @@ const getType = (type?: string, template?: GraphEdge['template']) => {
return slot return slot
} }
const getClass = (edge: GraphEdge) => {
const extraClass = edge.class instanceof Function ? edge.class(edge) : edge.class
return [noPanClassName, extraClass]
}
</script> </script>
<script lang="ts"> <script lang="ts">
@@ -124,7 +118,6 @@ export default {
:selectable="selectable(edge.selectable)" :selectable="selectable(edge.selectable)"
:updatable="updatable(edge.updatable)" :updatable="updatable(edge.updatable)"
:focusable="focusable(edge.focusable)" :focusable="focusable(edge.focusable)"
:class="getClass(edge)"
/> />
</g> </g>
</svg> </svg>
@@ -17,11 +17,6 @@ const {
emits, emits,
} = $(useVueFlow()) } = $(useVueFlow())
const draggable = (d?: boolean) => (typeof d === 'undefined' ? nodesDraggable : d)
const selectable = (s?: boolean) => (typeof s === 'undefined' ? elementsSelectable : s)
const connectable = (c?: HandleConnectable) => (typeof c === 'undefined' ? nodesConnectable : c)
const focusable = (f?: boolean) => (typeof f === 'undefined' ? nodesFocusable : f)
let resizeObserver = $ref<ResizeObserver>() let resizeObserver = $ref<ResizeObserver>()
until(() => nodes.length > 0 && getNodesInitialized.length === nodes.length) until(() => nodes.length > 0 && getNodesInitialized.length === nodes.length)
@@ -49,7 +44,13 @@ onMounted(() => {
onBeforeUnmount(() => resizeObserver?.disconnect()) onBeforeUnmount(() => resizeObserver?.disconnect())
const getType = (type?: string, template?: GraphNode['template']) => { const draggable = (nodeDraggable?: boolean) => (typeof nodeDraggable === 'undefined' ? nodesDraggable : nodeDraggable)
const selectable = (nodeSelectable?: boolean) => (typeof nodeSelectable === 'undefined' ? elementsSelectable : nodeSelectable)
const connectable = (nodeConnectable?: HandleConnectable) =>
typeof nodeConnectable === 'undefined' ? nodesConnectable : nodeConnectable
const focusable = (nodeFocusable?: boolean) => (typeof nodeFocusable === 'undefined' ? nodesFocusable : nodeFocusable)
function getType(type?: string, template?: GraphNode['template']) {
const name = type || 'default' const name = type || 'default'
let nodeType = template ?? getNodeTypes[name] let nodeType = template ?? getNodeTypes[name]
const instance = getCurrentInstance() const instance = getCurrentInstance()
@@ -44,9 +44,6 @@ let zoomedWithRightMouseButton = $ref(false)
let mouseButton = $ref(0) let mouseButton = $ref(0)
const isRightClickPan = (pan: FlowOptions['panOnDrag'], usedButton: number) =>
usedButton === 2 && Array.isArray(pan) && pan.includes(2)
const panKeyPressed = useKeyPress(panActivationKeyCode) const panKeyPressed = useKeyPress(panActivationKeyCode)
const isConnecting = $computed(() => !!connectionStartHandle) const isConnecting = $computed(() => !!connectionStartHandle)
@@ -57,30 +54,6 @@ const isSelecting = computed(
() => (selectionKeyCode !== true && selectionKeyPressed) || (selectionKeyCode === true && shouldPanOnDrag.value !== true), () => (selectionKeyCode !== true && selectionKeyPressed) || (selectionKeyCode === true && shouldPanOnDrag.value !== true),
) )
const viewChanged = (prevViewport: ViewportTransform, eventTransform: ZoomTransform): boolean =>
(prevViewport.x !== eventTransform.x && !isNaN(eventTransform.x)) ||
(prevViewport.y !== eventTransform.y && !isNaN(eventTransform.y)) ||
(prevViewport.zoom !== eventTransform.k && !isNaN(eventTransform.k))
const eventToFlowTransform = (eventTransform: ZoomTransform): ViewportTransform => ({
x: eventTransform.x,
y: eventTransform.y,
zoom: eventTransform.k,
})
const setDimensions = () => {
if (!viewportEl.value) return
const { width, height } = getDimensions(viewportEl.value)
if (width === 0 || height === 0) warn('The Vue Flow parent container needs a width and a height to render the graph.')
dimensions.width = width || 500
dimensions.height = height || 500
}
const isWrappedWithClass = (event: Event, className: string | undefined) => (event.target as Element).closest(`.${className}`)
let prevTransform = $ref<ViewportTransform>({ let prevTransform = $ref<ViewportTransform>({
x: 0, x: 0,
y: 0, y: 0,
@@ -286,6 +259,41 @@ onMounted(() => {
return (!event.ctrlKey || event.type === 'wheel') && buttonAllowed return (!event.ctrlKey || event.type === 'wheel') && buttonAllowed
}) })
}) })
function isRightClickPan(pan: FlowOptions['panOnDrag'], usedButton: number) {
return usedButton === 2 && Array.isArray(pan) && pan.includes(2)
}
function viewChanged(prevViewport: ViewportTransform, eventTransform: ZoomTransform) {
return (
(prevViewport.x !== eventTransform.x && !isNaN(eventTransform.x)) ||
(prevViewport.y !== eventTransform.y && !isNaN(eventTransform.y)) ||
(prevViewport.zoom !== eventTransform.k && !isNaN(eventTransform.k))
)
}
function eventToFlowTransform(eventTransform: ZoomTransform): ViewportTransform {
return {
x: eventTransform.x,
y: eventTransform.y,
zoom: eventTransform.k,
}
}
function setDimensions() {
if (!viewportEl.value) return
const { width, height } = getDimensions(viewportEl.value)
if (width === 0 || height === 0) warn('The Vue Flow parent container needs a width and a height to render the graph.')
dimensions.width = width || 500
dimensions.height = height || 500
}
function isWrappedWithClass(event: Event, className: string | undefined) {
return (event.target as Element).closest(`.${className}`)
}
</script> </script>
<script lang="ts"> <script lang="ts">
+2 -2
View File
@@ -2,7 +2,7 @@ import type { Dimensions, XYPosition } from '~/types'
// returns a number between 0 and 1 that represents the velocity of the movement // returns a number between 0 and 1 that represents the velocity of the movement
// when the mouse is close to the edge of the canvas // when the mouse is close to the edge of the canvas
const calcAutoPanVelocity = (value: number, min: number, max: number) => { function calcAutoPanVelocity(value: number, min: number, max: number) {
if (value < min) { if (value < min) {
return clamp(Math.abs(value - min), 1, 50) / 50 return clamp(Math.abs(value - min), 1, 50) / 50
} else if (value > max) { } else if (value > max) {
@@ -12,7 +12,7 @@ const calcAutoPanVelocity = (value: number, min: number, max: number) => {
return 0 return 0
} }
export const calcAutoPan = (pos: XYPosition, bounds: Dimensions) => { export function calcAutoPan(pos: XYPosition, bounds: Dimensions) {
const xMovement = calcAutoPanVelocity(pos.x, 35, bounds.width - 35) * 20 const xMovement = calcAutoPanVelocity(pos.x, 35, bounds.width - 35) * 20
const yMovement = calcAutoPanVelocity(pos.y, 35, bounds.height - 35) * 20 const yMovement = calcAutoPanVelocity(pos.y, 35, bounds.height - 35) * 20
+3 -6
View File
@@ -99,13 +99,10 @@ function handleParentExpand(updateItem: GraphNode, parent: GraphNode) {
} }
} }
export const applyChanges = < export function applyChanges<
T extends FlowElement = FlowElement, T extends FlowElement = FlowElement,
C extends ElementChange = T extends GraphNode ? NodeChange : EdgeChange, C extends ElementChange = T extends GraphNode ? NodeChange : EdgeChange,
>( >(changes: C[], elements: T[]): T[] {
changes: C[],
elements: T[],
): T[] => {
const addRemoveChanges = changes.filter((c) => c.type === 'add' || c.type === 'remove') as ( const addRemoveChanges = changes.filter((c) => c.type === 'add' || c.type === 'remove') as (
| NodeAddChange | NodeAddChange
| EdgeAddChange | EdgeAddChange
@@ -213,7 +210,7 @@ export const createRemoveChange = (id: string): NodeRemoveChange | EdgeRemoveCha
type: 'remove', type: 'remove',
}) })
export const getSelectionChanges = (elements: FlowElements, selectedIds: string[]) => { export function getSelectionChanges(elements: FlowElements, selectedIds: string[]) {
return elements.reduce( return elements.reduce(
(res, item) => { (res, item) => {
let willBeSelected = selectedIds.includes(item.id) let willBeSelected = selectedIds.includes(item.id)
+2 -2
View File
@@ -124,12 +124,12 @@ export function getExtent<T extends NodeDragItem | GraphNode>(item: T, extent?:
return currentExtent as CoordinateExtent return currentExtent as CoordinateExtent
} }
export const calcNextPosition = ( export function calcNextPosition(
node: GraphNode | NodeDragItem, node: GraphNode | NodeDragItem,
nextPosition: XYPosition, nextPosition: XYPosition,
nodeExtent?: CoordinateExtent, nodeExtent?: CoordinateExtent,
parentNode?: GraphNode, parentNode?: GraphNode,
) => { ) {
const extent = getExtent(node, nodeExtent, parentNode) const extent = getExtent(node, nodeExtent, parentNode)
const clampedPos = clampPosition(nextPosition, extent) const clampedPos = clampPosition(nextPosition, extent)
+5 -5
View File
@@ -2,7 +2,7 @@ import { isNumber } from '@vueuse/core'
import type { Actions, EdgePositions, GraphEdge, GraphNode, HandleElement, Rect, ViewportTransform, XYPosition } from '~/types' import type { Actions, EdgePositions, GraphEdge, GraphNode, HandleElement, Rect, ViewportTransform, XYPosition } from '~/types'
import { Position } from '~/types' import { Position } from '~/types'
export const getHandlePosition = (position: Position, rect: Rect, handle?: HandleElement): XYPosition => { export function getHandlePosition(position: Position, rect: Rect, handle?: HandleElement): XYPosition {
const x = (handle?.x ?? 0) + rect.x const x = (handle?.x ?? 0) + rect.x
const y = (handle?.y ?? 0) + rect.y const y = (handle?.y ?? 0) + rect.y
const width = handle?.width ?? rect.width const width = handle?.width ?? rect.width
@@ -32,7 +32,7 @@ export const getHandlePosition = (position: Position, rect: Rect, handle?: Handl
} }
} }
export const getHandle = (bounds: HandleElement[] = [], handleId?: string | null): HandleElement | undefined => { export function getHandle(bounds: HandleElement[] = [], handleId?: string | null): HandleElement | undefined {
if (!bounds.length) return undefined if (!bounds.length) return undefined
let handle let handle
@@ -42,14 +42,14 @@ export const getHandle = (bounds: HandleElement[] = [], handleId?: string | null
return handle || bounds[0] return handle || bounds[0]
} }
export const getEdgePositions = ( export function getEdgePositions(
sourceNode: GraphNode, sourceNode: GraphNode,
sourceHandle: HandleElement | undefined, sourceHandle: HandleElement | undefined,
sourcePosition: Position, sourcePosition: Position,
targetNode: GraphNode, targetNode: GraphNode,
targetHandle: HandleElement | undefined, targetHandle: HandleElement | undefined,
targetPosition: Position, targetPosition: Position,
): EdgePositions => { ): EdgePositions {
const sourceHandlePos = getHandlePosition( const sourceHandlePos = getHandlePosition(
sourcePosition, sourcePosition,
{ {
@@ -127,7 +127,7 @@ export function isEdgeVisible({
return overlappingArea > 0 return overlappingArea > 0
} }
export const groupEdgesByZLevel = (edges: GraphEdge[], findNode: Actions['findNode'], elevateEdgesOnSelect = false) => { export function groupEdgesByZLevel(edges: GraphEdge[], findNode: Actions['findNode'], elevateEdgesOnSelect = false) {
let maxLevel = -1 let maxLevel = -1
const levelLookup = edges.reduce<Record<string, GraphEdge[]>>((tree, edge) => { const levelLookup = edges.reduce<Record<string, GraphEdge[]>>((tree, edge) => {
+1 -1
View File
@@ -1,6 +1,6 @@
export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event
export const getEventPosition = (event: MouseEvent | TouchEvent, bounds?: DOMRect) => { export function getEventPosition(event: MouseEvent | TouchEvent, bounds?: DOMRect) {
const isMouseTriggered = isMouseEvent(event) const isMouseTriggered = isMouseEvent(event)
const evtX = isMouseTriggered ? event.clientX : event.touches?.[0].clientX const evtX = isMouseTriggered ? event.clientX : event.touches?.[0].clientX
const evtY = isMouseTriggered ? event.clientY : event.touches?.[0].clientY const evtY = isMouseTriggered ? event.clientY : event.touches?.[0].clientY
+21 -18
View File
@@ -26,7 +26,7 @@ export const nodeToRect = (node: GraphNode): Rect => ({
height: node.dimensions.height || 0, height: node.dimensions.height || 0,
}) })
export const getOverlappingArea = (rectA: Rect, rectB: Rect) => { export function getOverlappingArea(rectA: Rect, rectB: Rect) {
const xOverlap = Math.max(0, Math.min(rectA.x + rectA.width, rectB.x + rectB.width) - Math.max(rectA.x, rectB.x)) const xOverlap = Math.max(0, Math.min(rectA.x + rectA.width, rectB.x + rectB.width) - Math.max(rectA.x, rectB.x))
const yOverlap = Math.max(0, Math.min(rectA.y + rectA.height, rectB.y + rectB.height) - Math.max(rectA.y, rectB.y)) const yOverlap = Math.max(0, Math.min(rectA.y + rectA.height, rectB.y + rectB.height) - Math.max(rectA.y, rectB.y))
@@ -45,7 +45,7 @@ export const clampPosition = (position: XYPosition, extent: CoordinateExtent): X
y: clamp(position.y, extent[0][1], extent[1][1]), y: clamp(position.y, extent[0][1], extent[1][1]),
}) })
export const getHostForElement = (element: HTMLElement): Document => { export function getHostForElement(element: HTMLElement): Document {
const doc = element.getRootNode() as Document const doc = element.getRootNode() as Document
const window = useWindow() const window = useWindow()
@@ -67,7 +67,7 @@ export const isGraphNode = <Data = ElementData>(element: MaybeElement): element
export const isRect = (obj: any): obj is Rect => !!obj.width && !!obj.height && !!obj.x && !!obj.y export const isRect = (obj: any): obj is Rect => !!obj.width && !!obj.height && !!obj.x && !!obj.y
export const parseNode = (node: Node, defaults?: Partial<GraphNode>): GraphNode => { export function parseNode(node: Node, defaults?: Partial<GraphNode>): GraphNode {
let defaultValues = defaults let defaultValues = defaults
if (!isGraphNode(node)) { if (!isGraphNode(node)) {
defaultValues = { defaultValues = {
@@ -105,7 +105,7 @@ export const parseNode = (node: Node, defaults?: Partial<GraphNode>): GraphNode
} }
} }
export const parseEdge = (edge: Edge, defaults?: Partial<GraphEdge>): GraphEdge => { export function parseEdge(edge: Edge, defaults?: Partial<GraphEdge>): GraphEdge {
const events = isDef(edge.events) ? edge.events : defaults?.events && isDef(defaults?.events) ? defaults?.events : {} const events = isDef(edge.events) ? edge.events : defaults?.events && isDef(defaults?.events) ? defaults?.events : {}
const data = isDef(edge.data) ? edge.data : defaults?.data && isDef(defaults?.data) ? defaults?.data : {} const data = isDef(edge.data) ? edge.data : defaults?.data && isDef(defaults?.data) ? defaults?.data : {}
@@ -159,7 +159,7 @@ export const connectionExists = (edge: Edge | Connection, elements: Elements) =>
* Intended for options API * Intended for options API
* In composition API you can access utilities from `useVueFlow` * In composition API you can access utilities from `useVueFlow`
*/ */
export const addEdge = (edgeParams: Edge | Connection, elements: Elements, defaults?: DefaultEdgeOptions) => { export function addEdge(edgeParams: Edge | Connection, elements: Elements, defaults?: DefaultEdgeOptions) {
if (!edgeParams.source || !edgeParams.target) { if (!edgeParams.source || !edgeParams.target) {
warn("Can't create edge. An edge needs a source and a target.") warn("Can't create edge. An edge needs a source and a target.")
return elements return elements
@@ -186,7 +186,7 @@ export const addEdge = (edgeParams: Edge | Connection, elements: Elements, defau
* Intended for options API * Intended for options API
* In composition API you can access utilities from `useVueFlow` * In composition API you can access utilities from `useVueFlow`
*/ */
export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: Elements) => { export function updateEdge(oldEdge: Edge, newConnection: Connection, elements: Elements) {
if (!newConnection.source || !newConnection.target) { if (!newConnection.source || !newConnection.target) {
warn("Can't create new edge. An edge needs a source and a target.") warn("Can't create new edge. An edge needs a source and a target.")
return elements return elements
@@ -213,18 +213,18 @@ export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: E
return elements.filter((e) => e.id !== oldEdge.id) return elements.filter((e) => e.id !== oldEdge.id)
} }
export const rendererPointToPoint = ({ x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: ViewportTransform): XYPosition => { export function rendererPointToPoint({ x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: ViewportTransform): XYPosition {
return { return {
x: x * tScale + tx, x: x * tScale + tx,
y: y * tScale + ty, y: y * tScale + ty,
} }
} }
export const pointToRendererPoint = ( export function pointToRendererPoint(
{ x, y }: XYPosition, { x, y }: XYPosition,
{ x: tx, y: ty, zoom: tScale }: ViewportTransform, { x: tx, y: ty, zoom: tScale }: ViewportTransform,
snapToGrid: boolean, snapToGrid: boolean,
[snapX, snapY]: [number, number], [snapX, snapY]: [number, number],
) => { ): XYPosition {
const position: XYPosition = { const position: XYPosition = {
x: (x - tx) / tScale, x: (x - tx) / tScale,
y: (y - ty) / tScale, y: (y - ty) / tScale,
@@ -263,7 +263,7 @@ export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
export const getBoundsofRects = (rect1: Rect, rect2: Rect) => boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2))) export const getBoundsofRects = (rect1: Rect, rect2: Rect) => boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)))
export const getRectOfNodes = (nodes: GraphNode[]) => { export function getRectOfNodes(nodes: GraphNode[]) {
const box = nodes.reduce( const box = nodes.reduce(
(currBox, { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = {} as any) => (currBox, { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = {} as any) =>
getBoundsOfBoxes( getBoundsOfBoxes(
@@ -284,14 +284,14 @@ export const graphPosToZoomedPos = ({ x, y }: XYPosition, { x: tx, y: ty, zoom:
y: y * tScale + ty, y: y * tScale + ty,
}) })
export const getNodesInside = ( export function getNodesInside(
nodes: GraphNode[], nodes: GraphNode[],
rect: Rect, rect: Rect,
{ x: tx, y: ty, zoom: tScale }: ViewportTransform = { x: 0, y: 0, zoom: 1 }, { x: tx, y: ty, zoom: tScale }: ViewportTransform = { x: 0, y: 0, zoom: 1 },
partially = false, partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute // set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false, excludeNonSelectableNodes = false,
) => { ) {
const paneRect = { const paneRect = {
x: (rect.x - tx) / tScale, x: (rect.x - tx) / tScale,
y: (rect.y - ty) / tScale, y: (rect.y - ty) / tScale,
@@ -320,13 +320,13 @@ export const getNodesInside = (
}) })
} }
export const getConnectedEdges = (nodes: (Node | GraphNode)[], edges: GraphEdge[]) => { export function getConnectedEdges(nodes: (Node | GraphNode)[], edges: GraphEdge[]) {
const nodeIds = nodes.map((node) => node.id) const nodeIds = nodes.map((node) => node.id)
return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target)) return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target))
} }
export const getTransformForBounds = ( export function getTransformForBounds(
bounds: Rect, bounds: Rect,
width: number, width: number,
height: number, height: number,
@@ -337,7 +337,7 @@ export const getTransformForBounds = (
x?: number x?: number
y?: number y?: number
} = { x: 0, y: 0 }, } = { x: 0, y: 0 },
): ViewportTransform => { ): ViewportTransform {
const xZoom = width / (bounds.width * (1 + padding)) const xZoom = width / (bounds.width * (1 + padding))
const yZoom = height / (bounds.height * (1 + padding)) const yZoom = height / (bounds.height * (1 + padding))
const zoom = Math.min(xZoom, yZoom) const zoom = Math.min(xZoom, yZoom)
@@ -350,7 +350,7 @@ export const getTransformForBounds = (
return { x, y, zoom: clampedZoom } return { x, y, zoom: clampedZoom }
} }
export const getXYZPos = (parentPos: XYZPosition, computedPosition: XYZPosition): XYZPosition => { export function getXYZPos(parentPos: XYZPosition, computedPosition: XYZPosition): XYZPosition {
return { return {
x: computedPosition.x + parentPos.x, x: computedPosition.x + parentPos.x,
y: computedPosition.y + parentPos.y, y: computedPosition.y + parentPos.y,
@@ -358,15 +358,18 @@ export const getXYZPos = (parentPos: XYZPosition, computedPosition: XYZPosition)
} }
} }
export const isParentSelected = (node: GraphNode, findNode: Actions['findNode']): boolean => { export function isParentSelected(node: GraphNode, findNode: Actions['findNode']): boolean {
if (!node.parentNode) return false if (!node.parentNode) return false
const parent = findNode(node.parentNode) const parent = findNode(node.parentNode)
if (!parent) return false if (!parent) return false
if (parent.selected) return true if (parent.selected) return true
return isParentSelected(parent, findNode) return isParentSelected(parent, findNode)
} }
export const getMarkerId = (marker: EdgeMarkerType | undefined, vueFlowId?: string): string => { export function getMarkerId(marker: EdgeMarkerType | undefined, vueFlowId?: string) {
if (typeof marker === 'undefined') return '' if (typeof marker === 'undefined') return ''
if (typeof marker === 'string') return marker if (typeof marker === 'string') return marker
+1 -1
View File
@@ -6,7 +6,7 @@ export class VueFlowError extends Error {
} }
} }
export const warn = (message: string, ...args: any[]) => { export function warn(message: string, ...args: any[]) {
if (!productionEnvs.includes(__ENV__ || '')) { if (!productionEnvs.includes(__ENV__ || '')) {
console.warn(`[Vue Flow]: ${message}`, ...args) console.warn(`[Vue Flow]: ${message}`, ...args)
} }
+3 -3
View File
@@ -1,7 +1,7 @@
import type { Ref } from 'vue' import type { Ref } from 'vue'
import type { Actions, GraphNode, HandleElement, Position } from '~/types' import type { Actions, GraphNode, HandleElement, Position } from '~/types'
export const getHandleBounds = (selector: string, nodeElement: HTMLDivElement, zoom: number): HandleElement[] | undefined => { export function getHandleBounds(selector: string, nodeElement: HTMLDivElement, zoom: number): HandleElement[] | undefined {
const handles = nodeElement.querySelectorAll(`.vue-flow__handle${selector}`) const handles = nodeElement.querySelectorAll(`.vue-flow__handle${selector}`)
if (!handles || !handles.length) { if (!handles || !handles.length) {
@@ -24,14 +24,14 @@ export const getHandleBounds = (selector: string, nodeElement: HTMLDivElement, z
}) })
} }
export const handleNodeClick = ( export function handleNodeClick(
node: GraphNode, node: GraphNode,
multiSelectionActive: boolean, multiSelectionActive: boolean,
addSelectedNodes: Actions['addSelectedNodes'], addSelectedNodes: Actions['addSelectedNodes'],
removeSelectedNodes: Actions['removeSelectedNodes'], removeSelectedNodes: Actions['removeSelectedNodes'],
nodesSelectionActive: Ref<boolean>, nodesSelectionActive: Ref<boolean>,
unselect = false, unselect = false,
) => { ) {
nodesSelectionActive.value = false nodesSelectionActive.value = false
if (!node.selected) { if (!node.selected) {
+3 -3
View File
@@ -2,7 +2,7 @@ import type { Actions, Connection, Edge, GraphEdge, GraphNode, Node } from '~/ty
export const isDef = <T>(val: T): val is NonNullable<T> => typeof unref(val) !== 'undefined' export const isDef = <T>(val: T): val is NonNullable<T> => typeof unref(val) !== 'undefined'
export const addEdgeToStore = (edgeParams: Edge | Connection, edges: Edge[]) => { export function addEdgeToStore(edgeParams: Edge | Connection, edges: Edge[]) {
if (!edgeParams.source || !edgeParams.target) { if (!edgeParams.source || !edgeParams.target) {
warn("Can't create edge. An edge needs a source and a target.") warn("Can't create edge. An edge needs a source and a target.")
return false return false
@@ -22,7 +22,7 @@ export const addEdgeToStore = (edgeParams: Edge | Connection, edges: Edge[]) =>
return edge return edge
} }
export const updateEdgeAction = (edge: GraphEdge, newConnection: Connection, edges: GraphEdge[]) => { export function updateEdgeAction(edge: GraphEdge, newConnection: Connection, edges: GraphEdge[]) {
if (!newConnection.source || !newConnection.target) { if (!newConnection.source || !newConnection.target) {
warn("Can't create new edge. An edge needs a source and a target.") warn("Can't create new edge. An edge needs a source and a target.")
return false return false
@@ -49,7 +49,7 @@ export const updateEdgeAction = (edge: GraphEdge, newConnection: Connection, edg
return newEdge return newEdge
} }
export const createGraphNodes = (nodes: Node[], findNode: Actions['findNode'], currGraphNodes: GraphNode[]) => { export function createGraphNodes(nodes: Node[], findNode: Actions['findNode'], currGraphNodes: GraphNode[]) {
const parentNodes: Record<string, true> = {} const parentNodes: Record<string, true> = {}
const graphNodes = nodes.map((node) => { const graphNodes = nodes.map((node) => {
+2 -2
View File
@@ -3,11 +3,11 @@ import type { WatchPausableReturn } from '@vueuse/core'
import { isFunction } from '@vueuse/core' import { isFunction } from '@vueuse/core'
import type { Connection, FlowProps, VueFlowStore } from '~/types' import type { Connection, FlowProps, VueFlowStore } from '~/types'
export const useWatch = ( export function useWatch(
models: ToRefs<Pick<FlowProps, 'nodes' | 'edges' | 'modelValue'>>, models: ToRefs<Pick<FlowProps, 'nodes' | 'edges' | 'modelValue'>>,
props: FlowProps, props: FlowProps,
store: VueFlowStore, store: VueFlowStore,
) => { ) {
const scope = effectScope() const scope = effectScope()
scope.run(() => { scope.run(() => {