: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): drag a step to move it on the tile canvas (#127479)
Michael Reichenbach38a5e2d989d6
diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsxindex 7ddaef4f3ab2..02daa23cdbfa 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/PlacementHint.tsx@@ -6,9 +6,10 @@ import { LemonButton } from '@posthog/lemon-ui'import { tileCanvasLogic } from './tileCanvasLogic'export function PlacementHint(): JSX.Element | null {- const { nodeToBeAdded, isMovingNode, isCopyingNode } = useValues(tileCanvasLogic)+ const { nodeToBeAdded, isMovingNode, isCopyingNode, isDraggingStep } = useValues(tileCanvasLogic)const { cancel } = useActions(tileCanvasLogic)const action = isMovingNode ? 'move the step there' : isCopyingNode ? 'copy the step there' : null+ const verb = isDraggingStep ? 'Drop on' : 'Click'if (!action && !nodeToBeAdded) {return null}@@ -16,7 +17,9 @@ export function PlacementHint(): JSX.Element | null {<div className="flex items-center gap-2 rounded-full border bg-surface-primary py-1 pl-3 pr-1 text-sm shadow"><span>{action ? (- <>Click a highlighted + to {action}</>+ <>+ {verb} a highlighted + to {action}+ </>) : (<>Click a highlighted + to add{' '}diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsxindex 643cee69f4db..abb6c22a5d96 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/QuickAddButton.tsx@@ -24,13 +24,17 @@ export function QuickAddButton({revealed?: boolean/** A dragged step is nearest to this button, so a drop lands here. */isDropTarget?: boolean-}): JSX.Element {+}): JSX.Element | null {const buttonRef = useRef<HTMLButtonElement>(null)- const { quickAddEdgeKey, isPlacing, paletteSections, nodeToBeAdded } = useValues(tileCanvasLogic)+ const { quickAddEdgeKey, isPlacing, paletteSections, placementLabel, placeableEdgeKeys } =+ useValues(tileCanvasLogic)const { openQuickAdd, closeQuickAdd, addStepAt, placeAt } = useActions(tileCanvasLogic)const key = getEdgeId(edge)const isOpen = quickAddEdgeKey === key- const stepName = nodeToBeAdded && 'data' in nodeToBeAdded ? nodeToBeAdded.data.name : nodeToBeAdded?.name++ if (placeableEdgeKeys && !placeableEdgeKeys.has(key)) {+ return null+ }return (<div@@ -72,7 +76,7 @@ export function QuickAddButton({<IconPlus className="text-xs" /></button></Popover>- {isPlacing && stepName && (+ {isPlacing && placementLabel && (<divaria-hidden="true"className={cn(@@ -82,7 +86,7 @@ export function QuickAddButton({: '-translate-x-1 -translate-y-1/2 scale-90 opacity-0')}>- Add {stepName} here+ {placementLabel}</div>)}</div>diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsxindex 96d638646649..92ad29a557f3 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileCanvasContent.tsx@@ -71,6 +71,8 @@ export function TileCanvasContent(): JSX.Element {countOf,templateNameOf,nodeToBeAdded,+ isDraggingStep,+ placeableEdgeKeys,dropTargetEdgeKey,} = useValues(tileCanvasLogic)const { activateNode, openStepMenu, handlePaneClick, setDropTargetEdgeKey, dropAt } = useActions(tileCanvasLogic)@@ -113,10 +115,16 @@ export function TileCanvasContent(): JSX.Element {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())+ nearestInsertEdge(+ edges,+ screenToFlowPosition({ x: event.clientX, y: event.clientY }),+ DROP_REACH / getZoom(),+ placeableEdgeKeys+ )+ const isDragging = !!nodeToBeAdded || isDraggingStepconst onDragOver = (event: DragEvent<HTMLDivElement>): void => {- if (!nodeToBeAdded) {+ if (!isDragging) {return}event.preventDefault()@@ -135,7 +143,7 @@ export function TileCanvasContent(): JSX.Element {}const onDrop = (event: DragEvent<HTMLDivElement>): void => {- if (!nodeToBeAdded) {+ if (!isDragging) {return}event.preventDefault()diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsxindex 30d70ed91f62..ba00fb389384 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/TileStepNode.tsx@@ -1,9 +1,10 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { useRef } from 'react'import { cn } from 'lib/utils/css-classes'import { StepImportNotesBadge } from '../../../import/StepImportNotesBadge'+import { canMoveStep } from '../../hogFlowEditorLogic'import type { HogFlow, HogFlowAction } from '../../types'import { tileCanvasLogic } from './tileCanvasLogic'import { hasStepMenu } from './tileCanvasModel'@@ -34,8 +35,14 @@ export function TileStepNode({}): JSX.Element {const ref = useRef<HTMLDivElement>(null)const tile = useTileStep(action, workflow)- const hover = useHoverIntent(interactive && !selected && !menuOpen, HOVER_OPEN_DELAY_MS, HOVER_CARD_CLOSE_MS)- const { openStepMenu } = useActions(tileCanvasLogic)+ const { movingNodeId } = useValues(tileCanvasLogic)+ const hover = useHoverIntent(+ interactive && !selected && !menuOpen && !movingNodeId,+ HOVER_OPEN_DELAY_MS,+ HOVER_CARD_CLOSE_MS+ )+ const { openStepMenu, startDraggingStep, endDraggingStep } = useActions(tileCanvasLogic)+ const draggable = interactive && canMoveStep(workflow, action.id)useRaisedNode(ref, hover.mounted)const face = (<div@@ -55,11 +62,27 @@ export function TileStepNode({return (<divref={ref}- className="flex cursor-pointer items-start gap-3 text-primary"+ className={cn(+ 'flex cursor-pointer items-start gap-3 text-primary transition-opacity',+ draggable && 'nopan',+ movingNodeId === action.id && 'opacity-40'+ )}title={hover.mounted ? undefined : action.name}onMouseMove={hover.onMouseMove}onMouseLeave={hover.onMouseLeave}data-attr={interactive ? 'workflow-tile-step' : undefined}+ draggable={draggable}+ onDragStart={+ draggable+ ? (event) => {+ event.dataTransfer.effectAllowed = 'move'+ // Firefox starts a drag only when it carries data.+ event.dataTransfer.setData('text/plain', action.id)+ startDraggingStep(action.id)+ }+ : undefined+ }+ onDragEnd={draggable ? endDraggingStep : undefined}onContextMenu={interactive && hasStepMenu(action)? (event) => {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.tsindex ee9520329003..0ebb100f7ebc 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@@ -7,8 +7,9 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { workflowLogic } from '../../../workflowLogic'+import { getEdgeId } from '../../edgeId'import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'-import type { HogFlowActionNode } from '../../types'+import type { HogFlowActionNode, HogFlowEdge } from '../../types'import * as tileCanvasLayout from './tileCanvasLayout'import { tileCanvasLogic } from './tileCanvasLogic'import { stepCount } from './tileCanvasModel'@@ -275,6 +276,104 @@ describe('tileCanvasLogic', () => {})})+ describe('dragging a step', () => {+ const edge = (from: string, to: string): object | undefined =>+ logic.values.workflow.edges.find((candidate) => candidate.from === from && candidate.to === to)+ const edgePairs = (): string[] =>+ logic.values.workflow.edges.map((candidate) => `${candidate.from}->${candidate.to}`).sort()++ beforeEach(async () => {+ jest.mocked(loadAppMetricsTotals).mockResolvedValue({})+ logic = await mountSavedCanvas()+ // The editor lays out its graph nodes after the load, and a move reads them.+ await expectLogic(hogFlowEditorLogic({ id: WORKFLOW_ID }))+ .toFinishAllListeners()+ .toMatchValues({ nodes: expect.arrayContaining([expect.objectContaining({ id: 'b2' })]) })+ })++ it('moves the dragged step to the + it lands on, and its old neighbors join up', async () => {+ const capture = jest.spyOn(posthog, 'capture')++ logic.actions.startDraggingStep('b2')+ logic.actions.dropAt(edge('split', 'b1') as HogFlowEdge)+ logic.actions.endDraggingStep()++ expect(edgePairs()).toEqual(+ [+ 'trigger_node->split',+ 'split->pause',+ 'pause->a2',+ 'a2->exit_node',+ 'split->b2',+ 'b2->b1',+ 'b1->exit_node',+ ].sort()+ )+ expect(logic.values.isMovingNode).toBe(false)+ expect(capture).toHaveBeenCalledWith('workflows tile canvas step moved', {+ source: 'drag',+ step_type: 'delay',+ })+ })++ it.each(['trigger_node', 'split', 'exit_node'])('does not let %s be dragged', async (actionId) => {+ await expectLogic(logic, () => logic.actions.startDraggingStep(actionId)).toMatchValues({+ isMovingNode: false,+ isDraggingStep: false,+ })+ })++ it('offers no + next to the dragged step, and ignores a drop there', async () => {+ const before = edgePairs()++ logic.actions.startDraggingStep('b1')++ expect(logic.values.placeableEdgeKeys).not.toContain(getEdgeId(edge('split', 'b1') as HogFlowEdge))+ expect(logic.values.placeableEdgeKeys).not.toContain(getEdgeId(edge('b1', 'b2') as HogFlowEdge))+ expect(logic.values.placeableEdgeKeys).toContain(getEdgeId(edge('pause', 'a2') as HogFlowEdge))++ logic.actions.dropAt(edge('b1', 'b2') as HogFlowEdge)+ logic.actions.endDraggingStep()++ expect(edgePairs()).toEqual(before)+ expect(logic.values.isMovingNode).toBe(false)+ })++ it('offers no + after a step that two paths join into, and records no move for a drop there', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': {+ ...savedWorkflow,+ actions: [...savedWorkflow.actions.slice(0, -1), step('join'), savedWorkflow.actions.at(-1)],+ edges: [+ ...savedWorkflow.edges.filter((candidate) => candidate.to !== 'exit_node'),+ { from: 'a2', to: 'join', type: 'continue' },+ { from: 'b2', to: 'join', type: 'continue' },+ { from: 'join', to: 'exit_node', type: 'continue' },+ ],+ },+ },+ })+ logic = await mountSavedCanvas()+ await expectLogic(hogFlowEditorLogic({ id: WORKFLOW_ID }))+ .toFinishAllListeners()+ .toMatchValues({ nodes: expect.arrayContaining([expect.objectContaining({ id: 'join' })]) })+ const before = edgePairs()+ const capture = jest.spyOn(posthog, 'capture')++ logic.actions.startDraggingStep('join')++ expect(logic.values.placeableEdgeKeys).not.toContain(getEdgeId(edge('join', 'exit_node') as HogFlowEdge))+ expect(logic.values.placeableEdgeKeys).toContain(getEdgeId(edge('a2', 'join') as HogFlowEdge))++ logic.actions.dropAt(edge('join', 'exit_node') as HogFlowEdge)+ logic.actions.endDraggingStep()++ expect(edgePairs()).toEqual(before)+ expect(capture).not.toHaveBeenCalledWith('workflows tile canvas step moved', expect.anything())+ })+ })+describe('paths', () => {let layoutSpy: jest.SpyInstancediff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.tsindex db3a23039f8f..377889960c70 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts@@ -29,6 +29,7 @@ import { WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'import { getEdgeId } from '../../edgeId'import {actionMetricsFromTotals,+ canMoveStep,CreateActionType,HogFlowEditorActionMetrics,HogFlowEditorMode,@@ -66,6 +67,7 @@ import { withLeavingStacks } from './tileCanvasNodes'export type TileCanvasPanelMode = HogFlowEditorMode | 'history'export type StepAddSource = 'palette' | 'command bar' | 'quick add' | 'drag'+export type StepMoveSource = 'menu' | 'drag'export type StepCountOf = (actionId: string) => number | undefinedexport type TemplateNameOf = (templateId: string) => string | undefined@@ -158,7 +160,9 @@ export interface tileCanvasLogicValues {isCopyingNode: boolean // hogFlowEditorLogicisMovingNode: boolean // hogFlowEditorLogicmode: HogFlowEditorMode // hogFlowEditorLogic+ movingNodeId: string | null // hogFlowEditorLogicnodeToBeAdded: CreateActionType | HogFlowActionNode | null // hogFlowEditorLogic+ nodesById: Record<string, HogFlowActionNode> // hogFlowEditorLogicselectedNode: HogFlowActionNode | null // hogFlowEditorLogicselectedNodeCanBeCopiedOrMoved: boolean // hogFlowEditorLogicselectedNodeCanBeDeleted: boolean // hogFlowEditorLogic@@ -173,11 +177,13 @@ export interface tileCanvasLogicValues {allPathsCollapsed: booleancommandPaletteQuery: string | nullcountOf: StepCountOf+ draggedStepId: string | nulldrawnGraph: VisibleGraphdropTargetEdgeKey: string | nullfitRequest: numberfitsNextLayout: booleanframeSpecs: PathFrameSpec[]+ isDraggingStep: booleanisHistoryOpen: booleanisPanelOpen: booleanisPlacing: boolean@@ -192,6 +198,8 @@ export interface tileCanvasLogicValues {panelMode: TileCanvasPanelMode | nullpathGroups: PathGroup[]pendingPathFocus: PendingPathFocus | null+ placeableEdgeKeys: Set<string> | null+ placementLabel: string | nullplacingSource: StepAddSourcequickAddEdgeKey: string | nullselectedStepId: string | null@@ -286,6 +294,9 @@ export interface tileCanvasLogicActions {dropAt: (edge: HogFlowEdge) => {edge: HogFlowEdge}+ endDraggingStep: () => {+ value: true+ }fitNextLayout: () => {value: true}@@ -380,6 +391,9 @@ export interface tileCanvasLogicActions {setPendingPathFocus: (pendingPathFocus: PendingPathFocus | null) => {pendingPathFocus: PendingPathFocus | null}+ startDraggingStep: (actionId: string) => {+ actionId: string+ }startPlacing: (step: CreateActionType) => {step: CreateActionType}@@ -418,6 +432,18 @@ export interface tileCanvasLogicMeta {isMovingNode: boolean,isCopyingNode: boolean) => boolean+ isDraggingStep: (draggedStepId: string | null, isMovingNode: boolean, movingNodeId: string | null) => boolean+ placeableEdgeKeys: (+ isMovingNode: boolean,+ isCopyingNode: boolean,+ dropzoneNodes: DropzoneNode[]+ ) => Set<string> | null+ placementLabel: (+ isMovingNode: boolean,+ movingNodeId: string | null,+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null,+ workflow: HogFlow+ ) => string | nullpaletteSections: (featureFlags: FeatureFlagsSet,currentTeam: TeamPublicType | TeamType | null,@@ -446,8 +472,10 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([['nodeToBeAdded','isMovingNode',+ 'movingNodeId','isCopyingNode','dropzoneNodes',+ 'nodesById','selectedNodeId','selectedNode','selectedNodeCanBeDeleted',@@ -503,6 +531,8 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([placeAt: (edge: HogFlowEdge) => ({ edge }),setDropTargetEdgeKey: (edgeKey: string | null) => ({ edgeKey }),dropAt: (edge: HogFlowEdge) => ({ edge }),+ startDraggingStep: (actionId: string) => ({ actionId }),+ endDraggingStep: true,selectStep: (actionId: string) => ({ actionId }),revealStep: (actionId: string, openPanel: boolean = true) => ({ actionId, openPanel }),openPanel: (mode: TileCanvasPanelMode) => ({ mode }),@@ -553,6 +583,14 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([cancel: () => null,},],+ draggedStepId: [+ null as string | null,+ {+ startDraggingStep: (_, { actionId }) => actionId,+ endDraggingStep: () => null,+ cancel: () => null,+ },+ ],quickAddEdgeKey: [null as string | null,{@@ -678,6 +716,33 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([isCopyingNode: boolean): boolean => !!nodeToBeAdded || isMovingNode || isCopyingNode,],+ isDraggingStep: [+ (s) => [s.draggedStepId, s.isMovingNode, s.movingNodeId],+ (draggedStepId: string | null, isMovingNode: boolean, movingNodeId: string | null): boolean =>+ isMovingNode && !!draggedStepId && draggedStepId === movingNodeId,+ ],+ /** While a step is moved or copied, only the arrows it can land on take it. */+ placeableEdgeKeys: [+ (s) => [s.isMovingNode, s.isCopyingNode, s.dropzoneNodes],+ (isMovingNode: boolean, isCopyingNode: boolean, dropzoneNodes: DropzoneNode[]): Set<string> | null =>+ isMovingNode || isCopyingNode ? new Set(dropzoneNodes.map((zone) => zone.data.edge.id)) : null,+ ],+ placementLabel: [+ (s) => [s.isMovingNode, s.movingNodeId, s.nodeToBeAdded, s.workflow],+ (+ isMovingNode: boolean,+ movingNodeId: string | null,+ nodeToBeAdded: CreateActionType | HogFlowActionNode | null,+ workflow: HogFlow+ ): string | null => {+ if (isMovingNode) {+ const name = workflow.actions.find((action) => action.id === movingNodeId)?.name+ return name ? `Move ${name} here` : null+ }+ const name = nodeToBeAdded && 'data' in nodeToBeAdded ? nodeToBeAdded.data.name : nodeToBeAdded?.name+ return name ? `Add ${name} here` : null+ },+ ],paletteSections: [(s) => [s.featureFlags, s.currentTeam, s.isRowScopedTrigger, s.hogFunctionTemplatesById],(@@ -727,14 +792,16 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([actions.setOpenPathIds([...new Set([...values.openPathIds, ...containing.map((group) => group.id)])])actions.focusPathAfterLayout(innermost.id)}- const placeExistingStep = (edge: HogFlowEdge): void => {+ const placeExistingStep = (edge: HogFlowEdge, source: StepMoveSource): void => {const dropzone = values.dropzoneNodes.find((zone) => zone.data.edge.id === getEdgeId(edge))if (!dropzone) {return}actions.setHighlightedDropzoneNodeId(dropzone.id)if (values.isMovingNode) {+ const stepType = values.nodesById[values.movingNodeId ?? '']?.data.typeactions.moveNodeToHighlightedDropzone()+ posthog.capture('workflows tile canvas step moved', { source, step_type: stepType })} else {actions.copyNodeToHighlightedDropzone()}@@ -807,16 +874,35 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([actions.onDrop(undefined, edge)captureStepAdded('quick add', step.type)},+ startDraggingStep: ({ actionId }) => {+ const node = values.nodesById[actionId]+ if (!node || !canMoveStep(values.workflow, actionId)) {+ return+ }+ actions.closeStepMenu()+ actions.setNodeToBeAdded(null)+ dropPendingMoveOrCopy()+ actions.startMovingNode(node)+ posthog.capture('workflows tile canvas step drag started', { step_type: node.data.type })+ },+ endDraggingStep: () => {+ // A drop that moved the step already ended the move, so only a drag let go elsewhere is still moving.+ if (values.isMovingNode) {+ actions.stopMovingNode()+ }+ },dropAt: ({ edge }) => {const step = values.nodeToBeAdded- if (step) {+ if (values.isMovingNode) {+ placeExistingStep(edge, 'drag')+ } else if (step) {actions.onDrop(undefined, edge)captureStepAdded('drag', 'data' in step ? step.data.type : step.type)}},placeAt: ({ edge }) => {if (values.isMovingNode || values.isCopyingNode) {- placeExistingStep(edge)+ placeExistingStep(edge, 'menu')} else if (values.nodeToBeAdded) {placeNewStep(edge, values.nodeToBeAdded)}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.tsindex fd740983d575..a7720e13573f 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,7 +1,14 @@+import { getEdgeId } from '../../edgeId'import type { HogFlow, HogFlowAction } from '../../types'import { CanvasLayout } from './tileCanvasLayout'import { computeVisibleGraph } from './tileCanvasModel'-import { buildCanvasNodes, CanvasNodeState, keepUnchangedNodes } from './tileCanvasNodes'+import {+ buildCanvasEdges,+ buildCanvasNodes,+ CanvasNodeState,+ keepUnchangedNodes,+ nearestInsertEdge,+} from './tileCanvasNodes'const step = (id: string): HogFlowAction => ({ id, type: 'delay', name: id, config: {} }) as unknown as HogFlowAction@@ -31,28 +38,67 @@ const state: CanvasNodeState = {templateNameOf: () => undefined,}-describe('keepUnchangedNodes', () => {- it('keeps the node objects that did not change, so React Flow redraws only the rest', () => {- const before = buildCanvasNodes(layoutWith(120), [], graph, state)+describe('tileCanvasNodes', () => {+ describe('keepUnchangedNodes', () => {+ it('keeps the node objects that did not change, so React Flow redraws only the rest', () => {+ const before = buildCanvasNodes(layoutWith(120), [], graph, state)- const after = keepUnchangedNodes(- before,- buildCanvasNodes(layoutWith(200), [], graph, { ...state, selectedStepId: 'a' })- )- const moved = keepUnchangedNodes(before, buildCanvasNodes(layoutWith(200), [], graph, state))+ const after = keepUnchangedNodes(+ before,+ buildCanvasNodes(layoutWith(200), [], graph, { ...state, selectedStepId: 'a' })+ )+ const moved = keepUnchangedNodes(before, buildCanvasNodes(layoutWith(200), [], graph, state))- expect(after.map((node, index) => node === before[index])).toEqual([false, false])- expect(moved.map((node, index) => node === before[index])).toEqual([true, false])- })+ expect(after.map((node, index) => node === before[index])).toEqual([false, false])+ expect(moved.map((node, index) => node === before[index])).toEqual([true, false])+ })++ it('tells React Flow the size of each tile, so a replaced tile stays visible', () => {+ const sizes = { a: { width: 306, height: 84 }, b: { width: 306, height: 120 } }- it('tells React Flow the size of each tile, so a replaced tile stays visible', () => {- const sizes = { a: { width: 306, height: 84 }, b: { width: 306, height: 120 } }+ const nodes = buildCanvasNodes(layoutWith(120), [], graph, { ...state, sizes })++ expect(nodes.map((node) => node.measured)).toEqual([+ { width: 306, height: 84 },+ { width: 306, height: 120 },+ ])+ })+ })- const nodes = buildCanvasNodes(layoutWith(120), [], graph, { ...state, sizes })+ describe('nearestInsertEdge', () => {+ // a -> b -> c, with the + of a -> b near y 50 and the + of b -> c near y 250+ const chain = {+ actions: [step('a'), step('b'), step('c')],+ edges: [+ { from: 'a', to: 'b', type: 'continue' },+ { from: 'b', to: 'c', type: 'continue' },+ ],+ } as unknown as HogFlow+ const chainGraph = computeVisibleGraph(chain, [], [])+ const edges = buildCanvasEdges(chainGraph, {+ positions: {},+ edges: Object.fromEntries(+ chainGraph.edges.map((edge, index) => [+ edge.id,+ {+ points: [+ { x: 0, y: index * 200 },+ { x: 0, y: index * 200 + 100 },+ ],+ },+ ])+ ),+ frames: {},+ width: 300,+ height: 600,+ })+ const bToC = getEdgeId({ from: 'b', to: 'c', type: 'continue' } as HogFlow['edges'][0])- expect(nodes.map((node) => node.measured)).toEqual([- { width: 306, height: 84 },- { width: 306, height: 120 },- ])+ 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)+ })})})diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.tsindex 4f67e4dba1d7..b46e99319d36 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasNodes.ts@@ -1,5 +1,6 @@import type { Edge, Node } from '@xyflow/react'+import { getEdgeId } from '../../edgeId'import type { HogFlow, HogFlowEdge } from '../../types'import {Box,@@ -190,11 +191,20 @@ export function edgeLabelText(edge: VisibleEdge, routed: RoutedEdge): string | ureturn edge.label && routed.label ? edge.label : undefined}-/** The arrow whose + is closest to the point, if one is within reach. */-export function nearestInsertEdge(edges: TileEdgeType[], point: Point, reach: number): HogFlowEdge | null {+/** The arrow whose + is closest to the point, if one is within reach 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 = nullfor (const { data } of edges) {- if (!data?.routed || !data.edge.insertEdge) {+ if (+ !data?.routed ||+ !data.edge.insertEdge ||+ (placeableEdgeKeys && !placeableEdgeKeys.has(getEdgeId(data.edge.insertEdge)))+ ) {continue}const at = quickAddPoint(data.routed, edgeLabelText(data.edge, data.routed))diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 4f109ec0ce64..87e98e7850c5 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -193,6 +193,21 @@ export function computeMoveEdges(return newEdges}+const BRANCHING_STEP_TYPES: HogFlowAction['type'][] = [+ 'conditional_branch',+ 'random_cohort_branch',+ 'wait_until_condition',+]++/** A step moves on its own when it has one next step and no paths of its own to carry along. */+export function canMoveStep(workflow: HogFlow, actionId: string): boolean {+ const action = workflow.actions.find((candidate) => candidate.id === actionId)+ if (!action || action.type === 'trigger' || action.type === 'exit' || BRANCHING_STEP_TYPES.includes(action.type)) {+ return false+ }+ return new Set(workflow.edges.filter((edge) => edge.from === actionId).map((edge) => edge.to)).size === 1+}+export const HOG_FLOW_EDITOR_MODES = ['build', 'variables', 'test', 'metrics', 'logs'] as constexport type HogFlowEditorMode = (typeof HOG_FLOW_EDITOR_MODES)[number]export const HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH = 592@@ -2567,8 +2582,7 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([return false}- const branchingTypes = ['conditional_branch', 'random_cohort_branch', 'wait_until_condition']- return !branchingTypes.includes(selectedNode?.data.type ?? '')+ return !!selectedNode && !BRANCHING_STEP_TYPES.includes(selectedNode.data.type)},],}),@@ -2773,11 +2787,13 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([if (isMovingNode && movingNodeId) {const incomingEdges = edges.filter((e) => e.target === movingNodeId)const outgoingEdges = edges.filter((e) => e.source === movingNodeId)- // Only skip in the simple linear case (1 incoming, 1 outgoing)- // where placing on adjacent edges would result in the same position+ // A move drops the step's outgoing edge before it splits the target, so that edge can never take the step.+ if (outgoingEdges.length === 1) {+ skipEdgeIds.add(outgoingEdges[0].id)+ }+ // With one incoming edge, placing the step there leaves it where it is.if (incomingEdges.length === 1 && outgoingEdges.length === 1) {skipEdgeIds.add(incomingEdges[0].id)- skipEdgeIds.add(outgoingEdges[0].id)}}