Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): snap a step dropped anywhere on the tile canvas to the nearest + (#129098)

Michael Reichenbach539c71a06f1b
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx
index 8a5712a342ec..82c74cf81330 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx
@@ -10,7 +10,7 @@ import { getEdgeId } from '../../edgeId'
import type { HogFlowEdge } from '../../types'
import { StepPalette } from './StepPalette'
import { tileCanvasLogic } from './tileCanvasLogic'
-import { Point } from './tileCanvasModel'
+import { Point, QUICK_ADD_ATTR } from './tileCanvasModel'
function buttonLook(isDropTarget: boolean, isActive: boolean, revealed: boolean): string {
if (isDropTarget) {
@@ -77,7 +77,7 @@ export function QuickAddButton({
ref={buttonRef}
aria-label={label}
title={label}
- data-attr="workflow-tile-quick-add"
+ data-attr={QUICK_ADD_ATTR}
onClick={() => (isPlacing ? placeAt(edge) : isOpen ? closeQuickAdd() : openQuickAdd(key))}
className={cn(
'flex size-5 cursor-pointer items-center justify-center rounded-full border bg-surface-primary text-secondary transition-all duration-200 ease-out hover:scale-125 hover:border-[var(--color-accent)] hover:text-[var(--color-accent)] motion-reduce:transition-none',
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx
index 41dcff63e838..86543effeebc 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx
@@ -6,8 +6,6 @@ import { cn } from 'lib/utils/css-classes'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { getEdgeId } from '../../edgeId'
-import type { HogFlowEdge } from '../../types'
import { CommandBar } from './CommandBar'
import { PathChip } from './PathChip'
import { PathFrame } from './PathFrame'
@@ -21,8 +19,10 @@ import { CANVAS_MIN_ZOOM, hasStepMenu } from './tileCanvasModel'
import {
buildCanvasEdges,
buildCanvasNodes,
+ handleStepDragOver,
+ handleStepDrop,
keepUnchangedNodes,
- nearestInsertEdge,
+ StepDropCanvas,
TileCanvasNode,
TileEdgeType,
} from './tileCanvasNodes'
@@ -34,8 +34,6 @@ import { useCanvasViewport } from './useCanvasViewport'
const NODE_TYPES = { tile: TileFlowNode, frame: PathFrame, chip: PathChip } as NodeTypes
const EDGE_TYPES = { tile: TileEdge } as EdgeTypes
const MAX_ZOOM = 1.5
-/** How far from a + a dragged step still drops on it, in screen pixels. */
-const DROP_REACH = 120
type TileKeyCommand = 'activate' | 'menu'
@@ -77,7 +75,7 @@ export function TileCanvasContent(): JSX.Element {
dropTargetEdgeKey,
} = useValues(tileCanvasLogic)
const { activateNode, openStepMenu, handlePaneClick, setDropTargetEdgeKey, dropAt } = useActions(tileCanvasLogic)
- const { screenToFlowPosition, getZoom } = useReactFlow()
+ const { screenToFlowPosition } = useReactFlow()
useCanvasViewport(wrapperRef)
const previousNodes = useRef<TileCanvasNode[]>([])
@@ -115,26 +113,14 @@ export function TileCanvasContent(): JSX.Element {
const hasMenu = (nodeId: string): boolean =>
drawnGraph.nodes.some((node) => node.id === nodeId && node.kind === 'step' && hasStepMenu(node.action))
- const dropEdgeAt = (event: DragEvent<HTMLDivElement>): HogFlowEdge | null =>
- nearestInsertEdge(
- edges,
- screenToFlowPosition({ x: event.clientX, y: event.clientY }),
- DROP_REACH / getZoom(),
- placeableEdgeKeys
- )
- const isDragging = !!nodeToBeAdded || isDraggingStep
-
- const onDragOver = (event: DragEvent<HTMLDivElement>): void => {
- if (!isDragging) {
- return
- }
- event.preventDefault()
- event.dataTransfer.dropEffect = 'move'
- const edge = dropEdgeAt(event)
- const key = edge ? getEdgeId(edge) : null
- if (key !== dropTargetEdgeKey) {
- setDropTargetEdgeKey(key)
- }
+ const stepDropCanvas: StepDropCanvas = {
+ edges,
+ placeableEdgeKeys,
+ isWaitingForStep: !!nodeToBeAdded || isDraggingStep,
+ toFlowPoint: screenToFlowPosition,
+ dropTargetEdgeKey,
+ setDropTargetEdgeKey,
+ dropAt,
}
const onDragLeave = (event: DragEvent<HTMLDivElement>): void => {
@@ -143,18 +129,6 @@ export function TileCanvasContent(): JSX.Element {
}
}
- const onDrop = (event: DragEvent<HTMLDivElement>): void => {
- if (!isDragging) {
- return
- }
- event.preventDefault()
- const edge = dropEdgeAt(event)
- setDropTargetEdgeKey(null)
- if (edge) {
- dropAt(edge)
- }
- }
-
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
const nodeId = focusedTileId(event)
const command = nodeId ? tileKeyCommand(event) : null
@@ -181,9 +155,9 @@ export function TileCanvasContent(): JSX.Element {
<div
ref={wrapperRef}
onKeyDown={onKeyDown}
- onDragOver={onDragOver}
+ onDragOver={(event) => handleStepDragOver(event, stepDropCanvas)}
onDragLeave={onDragLeave}
- onDrop={onDrop}
+ onDrop={(event) => handleStepDrop(event, stepDropCanvas)}
className="TileCanvas__flow @container/tile-canvas relative flex min-h-0 min-w-0 grow @max-[48rem]/workflow-editor:min-h-48"
>
<ReactFlow<TileCanvasNode, TileEdgeType>
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx
index 33c18c970361..5458b04f25ec 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx
@@ -7,7 +7,7 @@ import { StepImportNotesBadge } from '../../../import/StepImportNotesBadge'
import { canMoveStep } from '../../hogFlowEditorLogic'
import type { HogFlow, HogFlowAction } from '../../types'
import { tileCanvasLogic } from './tileCanvasLogic'
-import { hasStepMenu, STEP_DRAG_DATA_TYPE } from './tileCanvasModel'
+import { hasStepMenu, MOVING_STEP_ATTR, STEP_DRAG_DATA_TYPE } from './tileCanvasModel'
import { TileCaption } from './TileCaption'
import { TileFace } from './TileFace'
import { HOVER_CARD_CLOSE_MS, TileHoverCard } from './TileHoverCard'
@@ -18,6 +18,10 @@ import { useTileStep } from './useTileStep'
const HOVER_OPEN_DELAY_MS = 260
+function movingStepAttrs(isMoving: boolean): Record<string, string> {
+ return isMoving ? { [MOVING_STEP_ATTR]: '' } : {}
+}
+
export function TileStepNode({
action,
workflow,
@@ -71,6 +75,7 @@ export function TileStepNode({
onMouseMove={hover.onMouseMove}
onMouseLeave={hover.onMouseLeave}
data-attr={interactive ? 'workflow-tile-step' : undefined}
+ {...movingStepAttrs(movingNodeId === action.id)}
draggable={draggable}
onDragStart={
draggable
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts
index d65e34dc14e1..d9816dc74969 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.test.ts
@@ -225,6 +225,7 @@ describe('tileCanvasLogic', () => {
logic.actions.startPlacing(delayStep)
logic.actions.placeAt(logic.values.workflow.edges[0])
},
+ extra: {},
},
{
source: 'command bar',
@@ -233,26 +234,33 @@ describe('tileCanvasLogic', () => {
logic.actions.startPlacing(delayStep)
logic.actions.placeAt(logic.values.workflow.edges[0])
},
+ extra: {},
},
{
source: 'quick add',
add: (): void => logic.actions.addStepAt(delayStep, logic.values.workflow.edges[0]),
+ extra: {},
},
{
source: 'drag',
add: (): void => {
logic.actions.openCommandPalette('d')
logic.actions.startDraggingNewStep(delayStep)
- logic.actions.dropAt(logic.values.workflow.edges[0])
+ logic.actions.dropAt(logic.values.workflow.edges[0], true)
logic.actions.endDraggingNewStep()
},
+ extra: { snapped: true },
},
- ])('counts a step added from the $source', ({ source, add }) => {
+ ])('counts a step added from the $source', ({ source, add, extra }) => {
const capture = jest.spyOn(posthog, 'capture')
add()
- expect(capture).toHaveBeenCalledWith('workflows tile canvas step added', { source, step_type: 'delay' })
+ expect(capture).toHaveBeenCalledWith('workflows tile canvas step added', {
+ source,
+ step_type: 'delay',
+ ...extra,
+ })
})
it.each([
@@ -347,7 +355,7 @@ describe('tileCanvasLogic', () => {
const capture = jest.spyOn(posthog, 'capture')
logic.actions.startDraggingStep('b2')
- logic.actions.dropAt(edge('split', 'b1') as HogFlowEdge)
+ logic.actions.dropAt(edge('split', 'b1') as HogFlowEdge, false)
// The moved tile can re-render before its dragend, so the drop itself must send the event.
const atDrop = dragEndedCalls(capture)
logic.actions.endDraggingStep('move')
@@ -368,7 +376,9 @@ describe('tileCanvasLogic', () => {
source: 'drag',
step_type: 'delay',
})
- const moved = [['workflows tile canvas step drag ended', { outcome: 'moved', step_type: 'delay' }]]
+ const moved = [
+ ['workflows tile canvas step drag ended', { outcome: 'moved', step_type: 'delay', snapped: false }],
+ ]
expect(atDrop).toEqual(moved)
expect(dragEndedCalls(capture)).toEqual(moved)
})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts
index ea31b5e7cb09..6e7743cec8ea 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts
@@ -126,15 +126,23 @@ function frameOrigin(layout: CanvasLayout | null, group: PathGroup): Point {
return box ? { x: box.x + box.width / 2, y: box.y + 40 } : { x: 0, y: 0 }
}
-function captureStepAdded(source: StepAddSource, stepType: string): void {
- posthog.capture('workflows tile canvas step added', { source, step_type: stepType })
+const snappedProperty = (snapped: boolean | undefined): { snapped?: boolean } =>
+ snapped !== undefined ? { snapped } : {}
+
+function captureStepAdded(source: StepAddSource, stepType: string, snapped?: boolean): void {
+ posthog.capture('workflows tile canvas step added', { source, step_type: stepType, ...snappedProperty(snapped) })
}
-function captureStepDragEnded(outcome: StepDragOutcome, stepType: string, dropEffect?: string | null): void {
+function captureStepDragEnded(
+ outcome: StepDragOutcome,
+ stepType: string,
+ { dropEffect, snapped }: { dropEffect?: string | null; snapped?: boolean } = {}
+): void {
posthog.capture('workflows tile canvas step drag ended', {
outcome,
step_type: stepType,
...(dropEffect !== undefined ? { drop_effect: dropEffect } : {}),
+ ...snappedProperty(snapped),
})
}
@@ -307,8 +315,12 @@ export interface tileCanvasLogicActions {
collapsePath: (groupId: string) => {
groupId: string
}
- dropAt: (edge: HogFlowEdge) => {
+ dropAt: (
+ edge: HogFlowEdge,
+ snapped?: boolean
+ ) => {
edge: HogFlowEdge
+ snapped: boolean | undefined
}
endDraggingNewStep: () => {
value: true
@@ -552,7 +564,7 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([
addStepAt: (step: CreateActionType, edge: HogFlowEdge) => ({ step, edge }),
placeAt: (edge: HogFlowEdge) => ({ edge }),
setDropTargetEdgeKey: (edgeKey: string | null) => ({ edgeKey }),
- dropAt: (edge: HogFlowEdge) => ({ edge }),
+ dropAt: (edge: HogFlowEdge, snapped?: boolean) => ({ edge, snapped }),
startDraggingStep: (actionId: string) => ({ actionId }),
endDraggingStep: (dropEffect: string | null = null) => ({ dropEffect }),
startDraggingNewStep: (step: CreateActionType) => ({ step }),
@@ -824,18 +836,18 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([
actions.setOpenPathIds([...new Set([...values.openPathIds, ...containing.map((group) => group.id)])])
actions.focusPathAfterLayout(innermost.id)
}
- const recordStepDrop = (outcome: StepDragOutcome): void => {
+ const recordStepDrop = (outcome: StepDragOutcome, snapped?: boolean): void => {
const drag = cache.stepDrag as StepDrag | null | undefined
if (drag && !drag.dropped) {
drag.dropped = true
- captureStepDragEnded(outcome, drag.stepType)
+ captureStepDragEnded(outcome, drag.stepType, { snapped })
}
}
- const placeExistingStep = (edge: HogFlowEdge, source: StepMoveSource): void => {
+ const placeExistingStep = (edge: HogFlowEdge, source: StepMoveSource, snapped?: boolean): void => {
const dropzone = values.dropzoneNodes.find((zone) => zone.data.edge.id === getEdgeId(edge))
if (!dropzone) {
if (source === 'drag') {
- recordStepDrop('no_matching_spot')
+ recordStepDrop('no_matching_spot', snapped)
}
return
}
@@ -845,7 +857,7 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([
actions.moveNodeToHighlightedDropzone()
posthog.capture('workflows tile canvas step moved', { source, step_type: stepType })
if (source === 'drag') {
- recordStepDrop('moved')
+ recordStepDrop('moved', snapped)
}
} else {
actions.copyNodeToHighlightedDropzone()
@@ -939,7 +951,7 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([
const drag = cache.stepDrag as StepDrag | null | undefined
// The browser reports dropEffect "none" when no drop target accepted the drag.
if (drag && !drag.dropped) {
- captureStepDragEnded('let_go_elsewhere', drag.stepType, dropEffect)
+ captureStepDragEnded('let_go_elsewhere', drag.stepType, { dropEffect })
}
cache.stepDrag = null
},
@@ -957,13 +969,13 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([
actions.closeQuickAdd()
}
},
- dropAt: ({ edge }) => {
+ dropAt: ({ edge, snapped }) => {
const step = values.nodeToBeAdded
if (values.isMovingNode) {
- placeExistingStep(edge, 'drag')
+ placeExistingStep(edge, 'drag', snapped)
} else if (step) {
actions.onDrop(undefined, edge)
- captureStepAdded('drag', 'data' in step ? step.data.type : step.type)
+ captureStepAdded('drag', 'data' in step ? step.data.type : step.type, snapped)
// A drop on the + that opened the add window removes that window, so its dragend never fires.
if (values.isDraggingNewStep) {
actions.endDraggingNewStep()
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts
index 380b7c243a1b..14b601d28f09 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts
@@ -786,6 +786,10 @@ export interface PaletteCommand {
// so step drags carry a type that no text field accepts.
export const STEP_DRAG_DATA_TYPE = 'application/x-posthog-workflow-step'
+export const QUICK_ADD_ATTR = 'workflow-tile-quick-add'
+
+export const MOVING_STEP_ATTR = 'data-workflow-moving-step'
+
export type PaletteItem<Command extends PaletteCommand = PaletteCommand> =
| { kind: 'step'; key: string; section: string; label: string; description?: string; step: CreateActionType }
| { kind: 'command'; key: string; section: string; label: string; description?: string; command: Command }
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts
index a7720e13573f..b88a5b02a383 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.test.ts
@@ -1,13 +1,16 @@
import { getEdgeId } from '../../edgeId'
-import type { HogFlow, HogFlowAction } from '../../types'
+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../../types'
import { CanvasLayout } from './tileCanvasLayout'
-import { computeVisibleGraph } from './tileCanvasModel'
+import { computeVisibleGraph, MOVING_STEP_ATTR, Point, QUICK_ADD_ATTR, STEP_DRAG_DATA_TYPE } from './tileCanvasModel'
import {
buildCanvasEdges,
buildCanvasNodes,
CanvasNodeState,
+ handleStepDragOver,
+ handleStepDrop,
keepUnchangedNodes,
nearestInsertEdge,
+ StepDragEvent,
} from './tileCanvasNodes'
const step = (id: string): HogFlowAction => ({ id, type: 'delay', name: id, config: {} }) as unknown as HogFlowAction
@@ -95,10 +98,127 @@ describe('tileCanvasNodes', () => {
const bToC = getEdgeId({ from: 'b', to: 'c', type: 'continue' } as HogFlow['edges'][0])
it.each([
- ['the closest + when no set is given', null, 'b'],
- ['a + from the set, so a hidden + never takes the drop', new Set([bToC]), 'c'],
- ])('picks %s', (_, placeableEdgeKeys, expectedTo) => {
- expect(nearestInsertEdge(edges, { x: 0, y: 50 }, 1000, placeableEdgeKeys)?.to).toBe(expectedTo)
+ ['the closest + when no set is given', { x: 0, y: 50 }, null, 'b'],
+ ['a + from the set, so a hidden + never takes the drop', { x: 0, y: 50 }, new Set([bToC]), 'c'],
+ ['the closest + for a drop far from every +', { x: 4000, y: 3000 }, null, 'c'],
+ ])('picks %s', (_, point, placeableEdgeKeys, expectedTo) => {
+ expect(nearestInsertEdge(edges, point, placeableEdgeKeys)?.to).toBe(expectedTo)
+ })
+
+ it('finds no + when none can take the step', () => {
+ expect(nearestInsertEdge(edges, { x: 0, y: 50 }, new Set())).toBeNull()
+ })
+
+ describe('step drops on the canvas', () => {
+ const aToB = getEdgeId({ from: 'a', to: 'b', type: 'continue' } as HogFlow['edges'][0])
+
+ type DropTarget = 'pane' | 'plus' | 'moving step' | 'canvas panel'
+
+ const releasedOver = (over: DropTarget): Element => {
+ const holder = document.createElement('div')
+ if (over === 'plus') {
+ holder.setAttribute('data-attr', QUICK_ADD_ATTR)
+ } else if (over === 'moving step') {
+ holder.setAttribute(MOVING_STEP_ATTR, '')
+ } else if (over === 'canvas panel') {
+ holder.className = 'react-flow__panel'
+ }
+ return holder.appendChild(document.createElement('span'))
+ }
+
+ const dragAt = (point: Point, types: string[], over: DropTarget): StepDragEvent => {
+ return {
+ clientX: point.x,
+ clientY: point.y,
+ target: releasedOver(over),
+ dataTransfer: { types, dropEffect: 'none' },
+ preventDefault: jest.fn(),
+ }
+ }
+
+ it.each([
+ {
+ name: 'snaps a step dropped far from every + to the nearest +',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 4000, y: 3000 },
+ expected: { highlights: [bToC, null], drops: [{ to: 'c', snapped: true }] },
+ },
+ {
+ name: 'keeps a drop on the + itself direct',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 0, y: 50 },
+ over: 'plus' as const,
+ expected: { highlights: [aToB, null], drops: [{ to: 'b', snapped: false }] },
+ },
+ {
+ name: 'cancels a move let go on the moving step itself',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 0, y: 150 },
+ over: 'moving step' as const,
+ expected: { highlights: [null], drops: [] },
+ },
+ {
+ name: 'cancels a drag let go over the controls on the canvas',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 0, y: 150 },
+ over: 'canvas panel' as const,
+ expected: { highlights: [null], drops: [] },
+ },
+ {
+ name: 'refuses a step that no + can take',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 0, y: 50 },
+ placeableEdgeKeys: new Set<string>(),
+ expected: { highlights: [null], drops: [] },
+ },
+ {
+ name: 'ignores a text drag while a step waits to be placed',
+ types: ['text/plain'],
+ point: { x: 0, y: 50 },
+ expected: { highlights: [], drops: [] },
+ },
+ {
+ name: 'ignores a step drag when the canvas waits for no step',
+ types: [STEP_DRAG_DATA_TYPE],
+ point: { x: 0, y: 50 },
+ isWaitingForStep: false,
+ expected: { highlights: [], drops: [] },
+ },
+ ])(
+ '$name',
+ ({
+ types,
+ point,
+ over: target = 'pane' as DropTarget,
+ placeableEdgeKeys = null,
+ isWaitingForStep = true,
+ expected,
+ }) => {
+ const setDropTargetEdgeKey = jest.fn()
+ const dropAt = jest.fn<void, [HogFlowEdge, boolean]>()
+ const canvas = {
+ edges,
+ placeableEdgeKeys,
+ isWaitingForStep,
+ toFlowPoint: (screenPoint: Point) => screenPoint,
+ dropTargetEdgeKey: null,
+ setDropTargetEdgeKey,
+ dropAt,
+ }
+ const over = dragAt(point, types, target)
+
+ handleStepDragOver(over, canvas)
+ handleStepDrop(dragAt(point, types, target), canvas)
+
+ const accepted = expected.drops.length > 0
+ expect(over.preventDefault).toHaveBeenCalledTimes(accepted ? 1 : 0)
+ expect(over.dataTransfer.dropEffect).toBe(accepted ? 'move' : 'none')
+ expect(setDropTargetEdgeKey.mock.calls.map(([key]) => key)).toEqual(expected.highlights)
+ expect(dropAt.mock.calls.map(([edge, snapped]) => ({ to: edge.to, snapped }))).toEqual(
+ expected.drops
+ )
+ }
+ )
})
})
})
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts
index b46e99319d36..bd9fd8a05369 100644
--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts
+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts
@@ -20,6 +20,9 @@ import {
NodeMotion,
PathGroup,
Point,
+ MOVING_STEP_ATTR,
+ QUICK_ADD_ATTR,
+ STEP_DRAG_DATA_TYPE,
VisibleEdge,
VisibleGraph,
VisibleNode,
@@ -191,11 +194,10 @@ export function edgeLabelText(edge: VisibleEdge, routed: RoutedEdge): string | u
return edge.label && routed.label ? edge.label : undefined
}
-/** The arrow whose + is closest to the point, if one is within reach and, when a set is given, in it. */
+/** The arrow whose + is closest to the point and, when a set is given, in it. */
export function nearestInsertEdge(
edges: TileEdgeType[],
point: Point,
- reach: number,
placeableEdgeKeys: Set<string> | null = null
): HogFlowEdge | null {
let best: { edge: HogFlowEdge; distance: number } | null = null
@@ -209,13 +211,82 @@ export function nearestInsertEdge(
}
const at = quickAddPoint(data.routed, edgeLabelText(data.edge, data.routed))
const distance = Math.hypot(at.x - point.x, at.y - point.y)
- if (distance <= reach && (!best || distance < best.distance)) {
+ if (!best || distance < best.distance) {
best = { edge: data.edge.insertEdge, distance }
}
}
return best?.edge ?? null
}
+export interface StepDragEvent {
+ clientX: number
+ clientY: number
+ target: EventTarget | null
+ dataTransfer: { readonly types: readonly string[]; dropEffect: string }
+ preventDefault: () => void
+}
+
+export interface StepDropCanvas {
+ edges: TileEdgeType[]
+ placeableEdgeKeys: Set<string> | null
+ isWaitingForStep: boolean
+ toFlowPoint: (screenPoint: Point) => Point
+ dropTargetEdgeKey: string | null
+ setDropTargetEdgeKey: (key: string | null) => void
+ dropAt: (edge: HogFlowEdge, snapped: boolean) => void
+}
+
+function isAwaitedStepDrag(event: StepDragEvent, canvas: StepDropCanvas): boolean {
+ return canvas.isWaitingForStep && event.dataTransfer.types.includes(STEP_DRAG_DATA_TYPE)
+}
+
+function isReleasedWhereDragCancels(event: StepDragEvent): boolean {
+ return event.target instanceof Element && !!event.target.closest(`[${MOVING_STEP_ATTR}], .react-flow__panel`)
+}
+
+function placeableEdgeUnderDrag(event: StepDragEvent, canvas: StepDropCanvas): HogFlowEdge | null {
+ if (isReleasedWhereDragCancels(event)) {
+ return null
+ }
+ const point = canvas.toFlowPoint({ x: event.clientX, y: event.clientY })
+ return nearestInsertEdge(canvas.edges, point, canvas.placeableEdgeKeys)
+}
+
+function acceptStepDrag(event: StepDragEvent): void {
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'move'
+}
+
+function isReleasedOnPlus(event: StepDragEvent): boolean {
+ return event.target instanceof Element && !!event.target.closest(`[data-attr="${QUICK_ADD_ATTR}"]`)
+}
+
+export function handleStepDragOver(event: StepDragEvent, canvas: StepDropCanvas): void {
+ if (!isAwaitedStepDrag(event, canvas)) {
+ return
+ }
+ const edge = placeableEdgeUnderDrag(event, canvas)
+ const key = edge ? getEdgeId(edge) : null
+ if (key !== canvas.dropTargetEdgeKey) {
+ canvas.setDropTargetEdgeKey(key)
+ }
+ if (edge) {
+ acceptStepDrag(event)
+ }
+}
+
+export function handleStepDrop(event: StepDragEvent, canvas: StepDropCanvas): void {
+ if (!isAwaitedStepDrag(event, canvas)) {
+ return
+ }
+ const edge = placeableEdgeUnderDrag(event, canvas)
+ canvas.setDropTargetEdgeKey(null)
+ if (edge) {
+ event.preventDefault()
+ canvas.dropAt(edge, !isReleasedOnPlus(event))
+ }
+}
+
export function buildCanvasEdges(graph: VisibleGraph, layout: CanvasLayout | null): TileEdgeType[] {
return graph.edges.map((edge) => ({
id: edge.id,