Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@ export const WorkflowBlock = memo(function WorkflowBlock({
edge.source,
edge.target
),
isEdgeSelected: (edge.data as { isSelected?: boolean } | undefined)?.isSelected,
})
if (!isHighlighted) continue
if (edge.source === id) keys.push(edge.sourceHandle || 'source')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ const WorkflowEdgeComponent = (props: WorkflowEdgeProps) => {
source,
target
)
const isEdgeSelected = Boolean((data as { isSelected?: boolean } | undefined)?.isSelected)
const shouldHighlightEdge = isEdgeHighlighted({
isEndpointSelected: isConnectedToSelection,
isConnectedToEditor,
isEdgeSelected,
})

const previewExecutionStatus = (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @vitest-environment jsdom
*/

import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { describe, expect, it, vi } from 'vitest'
import { useShiftSelectionLock } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-shift-selection-lock'

function renderShiftSelectionLock() {
let api: ReturnType<typeof useShiftSelectionLock> | null = null
const host = document.createElement('div')
const root: Root = createRoot(host)

function Probe() {
api = useShiftSelectionLock({ isHandMode: false })
return null
}

act(() => root.render(<Probe />))
if (!api) throw new Error('hook did not render')

return { api, unmount: () => act(() => root.unmount()) }
}

describe('useShiftSelectionLock', () => {
it('does not swallow Shift clicks on selectable elements inside the pane', () => {
const { api, unmount } = renderShiftSelectionLock()
const pane = document.createElement('div')
pane.className = 'react-flow__pane'
const edge = document.createElement('path')
edge.classList.add('react-flow__edge-interaction')
pane.appendChild(edge)
const preventDefault = vi.fn()

api.handleCanvasMouseDown({
shiftKey: true,
target: edge,
preventDefault,
} as unknown as React.MouseEvent)

expect(preventDefault).not.toHaveBeenCalled()
unmount()
})

it('still prevents native selection when Shift-drag starts on the pane background', () => {
const { api, unmount } = renderShiftSelectionLock()
const pane = document.createElement('div')
pane.className = 'react-flow__pane'
const preventDefault = vi.fn()

api.handleCanvasMouseDown({
shiftKey: true,
target: pane,
preventDefault,
} as unknown as React.MouseEvent)

expect(preventDefault).toHaveBeenCalledOnce()
unmount()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function useShiftSelectionLock({
if (!event.shiftKey) return

const target = event.target as HTMLElement | null
const isPaneTarget = Boolean(target?.closest('.react-flow__pane, .react-flow__selectionpane'))
const isPaneTarget = Boolean(target?.matches('.react-flow__pane, .react-flow__selectionpane'))

if (isPaneTarget && isHandMode) {
setIsShiftSelecting(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,60 @@
*/
import { describe, expect, it } from 'vitest'
import {
applyEdgeSelectionChanges,
getArrowNavigationDirection,
getEdgeSelectionMapKey,
isPositionalTriggerBlock,
reconcileCanvasEdges,
reconcileCanvasNodes,
shouldHighlightContainerDropTarget,
} from '@/app/workspace/[workspaceId]/w/[workflowId]/utils/workflow-canvas-helpers'

describe('edge selection helpers', () => {
it('keeps modifier selections and removes deselected edges', () => {
const selected = new Map([['edge-1-loop-1', 'edge-1']])
const selectionKeys = new Map([
['edge-1', 'edge-1-loop-1'],
['edge-2', 'edge-2-loop-1'],
])

const withSecondEdge = applyEdgeSelectionChanges(
selected,
[{ id: 'edge-2', type: 'select', selected: true }],
(edgeId) => selectionKeys.get(edgeId) ?? null
)
expect([...withSecondEdge]).toEqual([
['edge-1-loop-1', 'edge-1'],
['edge-2-loop-1', 'edge-2'],
])

const withoutFirstEdge = applyEdgeSelectionChanges(
withSecondEdge,
[{ id: 'edge-1', type: 'select', selected: false }],
(edgeId) => selectionKeys.get(edgeId) ?? null
)
expect([...withoutFirstEdge]).toEqual([['edge-2-loop-1', 'edge-2']])
})

it('uses nested context keys and ignores temporary edges', () => {
const key = getEdgeSelectionMapKey(
{ id: 'edge-1', source: 'source', target: 'target' },
[{ id: 'source', parentId: 'loop-1' }, { id: 'target' }],
{}
)
expect(key).toBe('edge-1-loop-1')

const selected = new Map<string, string>()
expect(
applyEdgeSelectionChanges(
selected,
[{ id: 'connection-block-selector-edge', type: 'select', selected: true }],
() => null
)
).toBe(selected)
})
})

describe('getArrowNavigationDirection', () => {
it('moves once for a fresh horizontal arrow press', () => {
expect(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BLOCK_DIMENSIONS, CONTAINER_DIMENSIONS, getNoteBlockHeight } from '@sim/workflow-renderer'
import { isEqual } from 'es-toolkit'
import type { Edge, Node } from 'reactflow'
import type { Edge, EdgeChange, Node } from 'reactflow'
import { TriggerUtils } from '@/lib/workflows/triggers/triggers'
import { clampPositionToContainer } from '@/app/workspace/[workspaceId]/w/[workflowId]/utils/node-position-utils'
import type { BlockState } from '@/stores/workflows/workflow/types'
Expand Down Expand Up @@ -313,6 +313,44 @@ export function getEdgeSelectionContextId(
return null
}

/** Stable key for transient edge selection, including a nested subflow context when present. */
export function getEdgeSelectionMapKey(
edge: Pick<Edge, 'id' | 'source' | 'target'>,
nodes: Array<Pick<Node, 'id' | 'parentId'>>,
blocks: Record<string, { data?: { parentId?: string } }>
): string {
const contextId = getEdgeSelectionContextId(edge, nodes, blocks)
return contextId ? `${edge.id}-${contextId}` : edge.id
}

type EdgeSelectChange = Extract<EdgeChange, { type: 'select' }>

/** Applies React Flow selection changes to the canvas' transient edge-selection map. */
export function applyEdgeSelectionChanges(
current: Map<string, string>,
changes: EdgeSelectChange[],
getSelectionKey: (edgeId: string) => string | null
): Map<string, string> {
let next: Map<string, string> | null = null
const writable = () => (next ??= new Map(current))

for (const change of changes) {
if (change.selected) {
const selectionKey = getSelectionKey(change.id)
if (selectionKey && (next ?? current).get(selectionKey) !== change.id) {
writable().set(selectionKey, change.id)
}
continue
}

for (const [selectionKey, edgeId] of next ?? current) {
if (edgeId === change.id) writable().delete(selectionKey)
}
}

return next ?? current
}

export function resolveSelectionContextConflicts(
nodes: Node[],
blocks: Record<string, { data?: { parentId?: string } }>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const reactFlowStyles = [
'[&_.react-flow__selectionpane]:select-none',
String.raw`[&_.react-flow\_\_selection]:!border-[var(--text-secondary)]`,
String.raw`[&_.react-flow\_\_selection]:!bg-[color-mix(in_oklch,var(--text-secondary)_8%,transparent)]`,
String.raw`[&_.react-flow\_\_edge:focus-visible_.react-flow\_\_edge-path]:drop-shadow-[0_0_2px_var(--text-secondary)]`,
'[&_.react-flow__background]:hidden',
'[&_.react-flow__node-subflowNode.selected]:!shadow-none',
].join(' ')
Expand Down
85 changes: 45 additions & 40 deletions apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import ReactFlow, {
applyNodeChanges,
ConnectionLineType,
type Edge,
type EdgeChange,
type Node,
type NodeChange,
type OnConnectStart,
Expand Down Expand Up @@ -80,6 +81,7 @@ import {
useWorkflowExecution,
} from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks'
import {
applyEdgeSelectionChanges,
calculateContainerDimensions,
clampPositionToContainer,
clearDragHighlights,
Expand All @@ -89,7 +91,7 @@ import {
getArrowNavigationDirection,
getClampedPositionForNode,
getDescendantBlockIds,
getEdgeSelectionContextId,
getEdgeSelectionMapKey,
getNodeSelectionContextId,
getRunFromBlockDependencyState,
getWorkflowLockToggleIds,
Expand Down Expand Up @@ -3366,12 +3368,39 @@ const WorkflowContent = React.memo(
}
}, [blocks, batchUpdateBlocksWithParent, getNodeAbsolutePosition, isWorkflowReady])

/** Handles edge removal changes. */
/** Synchronizes transient edge selection and handles edge removal changes. */
const onEdgesChange = useCallback(
(changes: any) => {
(changes: EdgeChange[]) => {
const selectionChanges = changes.filter(
(change): change is Extract<EdgeChange, { type: 'select' }> => change.type === 'select'
)
if (selectionChanges.length > 0) {
const focusedEdgeTestId = document.activeElement?.getAttribute('data-testid')
const shouldRestoreEdgeFocus = selectionChanges.some(
(change) => change.selected && focusedEdgeTestId === `rf__edge-${change.id}`
)
const nodes = getNodes()
setSelectedEdges((current) =>
applyEdgeSelectionChanges(current, selectionChanges, (edgeId) => {
const edge = edgesForDisplay.find((candidate) => candidate.id === edgeId)
return edge ? getEdgeSelectionMapKey(edge, nodes, blocks) : null
})
)
if (shouldRestoreEdgeFocus) {
requestAnimationFrame(() => {
const focusedEdge = Array.from(
document.querySelectorAll<SVGGElement>('.react-flow__edge')
).find((edge) => edge.getAttribute('data-testid') === focusedEdgeTestId)
focusedEdge?.focus({ preventScroll: true })
})
}
}

const edgeIdsToRemove = changes
.filter((change: any) => change.type === 'remove')
.map((change: any) => change.id)
.filter(
(change): change is Extract<EdgeChange, { type: 'remove' }> => change.type === 'remove'
)
.map((change) => change.id)
.filter((edgeId: string) => {
// Prevent removing edges targeting protected blocks
const edge = edges.find((e) => e.id === edgeId)
Expand All @@ -3383,7 +3412,7 @@ const WorkflowContent = React.memo(
collaborativeBatchRemoveEdges(edgeIdsToRemove)
}
},
[collaborativeBatchRemoveEdges, edges, blocks]
[blocks, collaborativeBatchRemoveEdges, edges, edgesForDisplay, getNodes]
)

/**
Expand Down Expand Up @@ -4733,43 +4762,15 @@ const WorkflowContent = React.memo(
workflowIdParam,
])

/** Handles edge selection with container context tracking and Shift-click multi-selection. */
const onEdgeClick = useCallback(
(event: React.MouseEvent, edge: any) => {
event.stopPropagation() // Prevent bubbling
if (edge.id === `${CONNECTION_BLOCK_SELECTOR_NODE_ID}-edge`) return

const contextId = `${edge.id}${(() => {
const selectionContextId = getEdgeSelectionContextId(edge, getNodes(), blocks)
return selectionContextId ? `-${selectionContextId}` : ''
})()}`

if (event.shiftKey) {
// Shift-click: toggle edge in selection
setSelectedEdges((prev) => {
const next = new Map(prev)
if (next.has(contextId)) {
next.delete(contextId)
} else {
next.set(contextId, edge.id)
}
return next
})
} else {
// Normal click: replace selection with this edge
setSelectedEdges(new Map([[contextId, edge.id]]))
}
},
[blocks, getNodes]
)

const latestEdgesRef = useRef(edges)
latestEdgesRef.current = edges
const latestBlocksRef = useRef(blocks)
latestBlocksRef.current = blocks
/** Stable delete handler to avoid creating new function references per edge. */
const handleEdgeDelete = useCallback(
(edgeId: string) => {
if (!effectivePermissions.canEdit) return

// Prevent removing edges targeting protected blocks
const edge = latestEdgesRef.current.find((candidate) => candidate.id === edgeId)
if (edge && isEdgeProtected(edge, latestBlocksRef.current)) {
Expand All @@ -4788,7 +4789,7 @@ const WorkflowContent = React.memo(
return next
})
},
[removeEdge]
[effectivePermissions.canEdit, removeEdge]
)

/*
Expand Down Expand Up @@ -4856,7 +4857,7 @@ const WorkflowContent = React.memo(
const sourceNode = nodeMap.get(edge.source)
const targetNode = nodeMap.get(edge.target)
const parentLoopId = sourceNode?.parentId || targetNode?.parentId
const edgeContextId = `${edge.id}${parentLoopId ? `-${parentLoopId}` : ''}`
const edgeContextId = getEdgeSelectionMapKey(edge, displayNodes, blocks)

// Ordered within the edge band by its container's depth, so an edge is
// always above the container body it crosses (which is opaque, and takes
Expand Down Expand Up @@ -4897,6 +4898,7 @@ const WorkflowContent = React.memo(

return {
...edge,
selected: isSelected,
zIndex,
data: {
...edge.data,
Expand All @@ -4905,7 +4907,7 @@ const WorkflowContent = React.memo(
isInsideLoop: Boolean(parentLoopId),
parentLoopId,
sourceHandle: edge.sourceHandle,
onDelete: handleEdgeDelete,
...(effectivePermissions.canEdit ? { onDelete: handleEdgeDelete } : {}),
...(targetContainerZIndex !== undefined ? { labelZIndex: zIndex } : {}),
},
}
Expand All @@ -4925,6 +4927,7 @@ const WorkflowContent = React.memo(
displayNodes,
selectedNodeIds,
selectedEdges,
effectivePermissions.canEdit,
handleEdgeDelete,
editorOpenBlockId,
panelActiveTab,
Expand Down Expand Up @@ -4978,6 +4981,9 @@ const WorkflowContent = React.memo(

// Handle edge deletion first (edges take priority if selected)
if (selectedEdges.size > 0) {
event.preventDefault()
if (!effectivePermissions.canEdit) return

// Get all selected edge IDs and filter out edges targeting protected blocks
const edgeIds = Array.from(selectedEdges.values()).filter((edgeId) => {
const edge = edges.find((e) => e.id === edgeId)
Expand Down Expand Up @@ -5157,7 +5163,6 @@ const WorkflowContent = React.memo(
connectionLineContainerStyle={CONNECTION_LINE_CONTAINER_STYLE}
connectionLineType={ConnectionLineType.SmoothStep}
onPaneClick={onPaneClick}
onEdgeClick={embedded ? undefined : onEdgeClick}
onNodeClick={handleNodeClick}
onPaneContextMenu={handlePaneContextMenu}
onNodeContextMenu={handleNodeContextMenu}
Expand Down
Loading
Loading