: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
fix(workflows): give each arrow in the tile canvas its own line (#127486)
Michael Reichenbach7f9193c0262f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8524c314de68..38592780587f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8423,25 +8423,25 @@ snapshots:products-workflows-editor-graph--with-navigation--light:hash: v1.k794b7964.80893cf0e8c8e443606cad555c64cc7e33323c3d4da76599c8e63f7ca1c291bd.5ATLbGHLQWlJfeMpGAo-7Zld7eNzLRqjOkp2MwxmpV4products-workflows-editor-tile-canvas--long-emails--dark:- hash: v1.k794b7964.fd71da5c1231d1036556e7e58e34b68a931b14812134201ce9f7fb2008d195c9.Eyw-ZqzqCvOOfKSecjq358TQw_kZtHC2hXzISMuEP9Q+ hash: v1.k794b7964.1952a127037bb7742f34a262ba7383326e4f5e04c86ffd58caf988de908d8fe0.lASWXxfI4hHT-xShH9moFcK8Fsd5JbnWjflhV6hu1dIproducts-workflows-editor-tile-canvas--long-emails--light:- hash: v1.k794b7964.f7c8b7f120b9d77bbc35e34c228c4d94875408d06b86935452594036a21bd3e4.EEU2unhqDjBNtYEvkX9wh3AgvSoqLlkNF9EPIeTxjuw+ hash: v1.k794b7964.2f2b3c752c4f010a1a6f6e9f0064ef2f9ebcaf974a68617004d48169e2825207.JeVtmRCcAbwRA5XD3qf8UWnfW_CJpok5N0aUWYhkoe0products-workflows-editor-tile-canvas--paths-collapsed--dark:- hash: v1.k794b7964.fbc02489e48230560f38677e2c0564544ba43ba5fccb814d9c58d21141f7bd56.mSexBQ6C7P2Tfnhl5JcaUMWxhpEgUdYwGzc0bsnnEKE+ hash: v1.k794b7964.2db6eff86fd9e7ab3ad02322c32b76820b358288969fe3d1c2d0768fb3b5f3f2.U2-0fg3YEmHB5NfrBnLB1_dxozv03EeIMzJdYQjH9Dcproducts-workflows-editor-tile-canvas--paths-collapsed--light:- hash: v1.k794b7964.3d1637648ee51ef3722219862d7d1fb06bf5a6a557e717256576e7894d861fb6.jmfY3wnm_MZTY_6DZYAw1yw54aqt5k9lM6qyf2PCW-I+ hash: v1.k794b7964.fa53ed40abbff04e3b400d16e602425b64e1cb2dc243381f9a5ea5c69e2c6e63.2zpDbbpmxK6a8oDXnG-unhtxVASlt8xoNe0av_2dKbsproducts-workflows-editor-tile-canvas--paths-open--dark:- hash: v1.k794b7964.814198da2522e4b84347f93ed982501c269854725253835786e532db662a00b2.HrvlQqF-r9XB80Wk5t8Dh933q4t_scSHWTVmOfd7s6E+ hash: v1.k794b7964.d3d47bc1351aa7293b4e5d90dd46d2adeae5f8f85eb2e814bb870d7e68729cff.NjIakT0uJmtshrpzvna3XCjjvemJFbQgpgGAPVUuYMoproducts-workflows-editor-tile-canvas--paths-open--light:- hash: v1.k794b7964.cee0f349c18a1b78a05c1ab61307e904993b24d116b8c243a2ba0a0ad60f9e18.Igdbc6OD8bF9oJ_1c8lUUIVcieG4JvrXa49np3otQIU+ hash: v1.k794b7964.e9b74962cdcabd5fd75afc8638e036eb19a8bf15ed04f165e027976602d87fff.MgLraG0WhRe09Mr9IXm-q0riB7tn_vibXFxvEeoDaSwproducts-workflows-editor-tile-canvas--time-window-and-webhook--dark:- hash: v1.k794b7964.b1a47db1602c1e0703b2f3b521ac52dcbc5a3ebba76f4e7d2d309c3b4c7c4b7a._LObcIoA9-yXUI0LuwW34VQfGxEUdGcreQQvdLF1-Aw+ hash: v1.k794b7964.5619f27b26cc0897dbcf28dca61ceb1cc0a9f847fcade41d25c49f71f214c731.DGGpKPpM3NMJ5BG-KVbFglz5IRPUcE7HXvY_vxaJK3Uproducts-workflows-editor-tile-canvas--time-window-and-webhook--light:- hash: v1.k794b7964.96225fdd020c0c75c161f88680367e556a5c95ea9616dbfb4540e526038198c8.5Bl9S5lwxwuPa6gPDab0DYRVBhU9njZz8tg2puTozyk+ hash: v1.k794b7964.11b35d0c89a16ab3c5f9aecffcd99725cbd31d584ac7a67f27039cb453bbcf72.5LRNbjHVw5Fo9Khk1YPOe0ip2ex2MtkX1QR2FPb9VFkproducts-workflows-editor-tile-canvas--with-step-counts--dark:- hash: v1.k794b7964.de5dddfb98e5dcb9ad68c0fbeb72adc735052df9f6adaa2409863b4ff49febf3.CvpVLCAl5s20yCLvaCQj7Y0yOmvGr-X9bjdS9br6m4M+ hash: v1.k794b7964.7c7eac0a64e20be352335e9955c4abccf70d7ec2b180217d33e275e59061a7af.RfzdMvzPcl8UMVgMFh5cr00tXX09P7bfm2EC7tBQdVsproducts-workflows-editor-tile-canvas--with-step-counts--light:- hash: v1.k794b7964.d28c0e207d14d3f1ee827602f1600c4e3eb47ec9c790e4357757388aa1172f9a.yjhNs4J_VVtzYX_ksVtLrSzDD0vw8lAknbYlYncjD9A+ hash: v1.k794b7964.50beae04f0b949a710da41fdca70c671369ae0ac0499d284b69e1c57e931f1bc.o27SKj0cbEgIAZ6OSgXLX9_lFEaYUAWLmXef1W0TB3wproducts-workflows-editor-tree--add-on-promotion-emails--dark:hash: v1.k794b7964.17e5ae30b6cfa98729709e1bb572aa329eea7d267ee0fd757a8bcbb1d065f805.UCtBAJZoCAO4I9fElU_pbm8QniucCrnrfH8XHXnsEZAproducts-workflows-editor-tree--add-on-promotion-emails--light:diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.tsindex 575853f85480..cab4ed572e14 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.test.ts@@ -1,6 +1,8 @@+import { groupBy } from 'lib/utils/arrays'+import type { HogFlowAction, HogFlowEdge } from '../../types'-import { layoutTileCanvas, NodeSize, pathFrameSpecs } from './tileCanvasLayout'-import { computePathGroups, computeVisibleGraph, PathGroup } from './tileCanvasModel'+import { Box, CanvasLayout, layoutTileCanvas, NodeSize, pathFrameSpecs } from './tileCanvasLayout'+import { computePathGroups, computeVisibleGraph, FlowGraph, PathGroup, Point, VisibleEdge } from './tileCanvasModel'const step = (id: string, type: HogFlowAction['type'] = 'function'): HogFlowAction =>({ id, type, name: id, description: '', config: {} }) as HogFlowAction@@ -53,15 +55,26 @@ const groups = computePathGroups(workflow)const outerArms = groups.filter((group) => group.branchActionId === 'split')const innerArms = groups.filter((group) => group.branchActionId === 'c1')-async function layoutWith(openIds: string[]): Promise<(group: PathGroup) => { x: number; top: number }> {- const graph = computeVisibleGraph(workflow, groups, openIds)+const STEP: NodeSize = { width: 260, height: 64, anchor: { x: 32, y: 32, width: 64, height: 64 } }+const STACK: NodeSize = { width: 180, height: 90, anchor: { x: 40, y: 40, width: 80, height: 80 } }++async function layOut(+ flow: FlowGraph,+ flowGroups: PathGroup[],+ openIds: string[],+ stopIfStale?: () => void+): Promise<{ layout: CanvasLayout; sizes: Record<string, NodeSize>; edges: VisibleEdge[] }> {+ const graph = computeVisibleGraph(flow, flowGroups, openIds)const sizes: Record<string, NodeSize> = Object.fromEntries(- graph.nodes.map((node) => [- node.id,- node.kind === 'stack' ? { width: 180, height: 90 } : { width: 64, height: 64 },- ])+ graph.nodes.map((node) => [node.id, node.kind === 'stack' ? STACK : STEP]))- const layout = await layoutTileCanvas(sizes, graph.edges, pathFrameSpecs(groups, openIds, graph.nodes))+ const frames = pathFrameSpecs(flowGroups, openIds, graph.nodes)+ const layout = await layoutTileCanvas(sizes, graph.edges, frames, stopIfStale)+ return { layout, sizes, edges: graph.edges }+}++async function layoutWith(openIds: string[]): Promise<(group: PathGroup) => { x: number; top: number }> {+ const { layout, sizes } = await layOut(workflow, groups, openIds)return (group) => {const frame = layout.frames[`frame:${group.id}`]return frame@@ -76,6 +89,131 @@ async function leftToRight(arms: PathGroup[], openIds: string[]): Promise<stringreturn [...arms].sort((one, other) => placeOf(one).x - placeOf(other).x).map((group) => group.memberIds[0])}+const sharedTarget: FlowGraph = {+ actions: ['trigger', 'split', 'b1', 'b2', 'b3', 'shared', 'd1', 'd2', 'd3', 'after', 'join', 'exit'].map((id) =>+ step(id, id === 'trigger' ? 'trigger' : id === 'split' ? 'conditional_branch' : 'function')+ ),+ edges: [+ { from: 'trigger', to: 'split', type: 'continue' },+ ...['shared', 'shared', 'b1', 'shared', 'd1'].map((to, index) => pathEdge('split', to, index, 5)),+ ...[+ ['b1', 'b2'],+ ['b2', 'b3'],+ ['b3', 'join'],+ ['d1', 'd2'],+ ['d2', 'd3'],+ ['d3', 'join'],+ ['shared', 'after'],+ ['after', 'exit'],+ ['join', 'exit'],+ ].map(([from, to]): HogFlowEdge => ({ from, to, type: 'continue' })),+ ],+}+const sharedTargetGroups = computePathGroups(sharedTarget)++const splits = (from: [string, string[]][]): HogFlowEdge[] =>+ from.flatMap(([source, targets]) => targets.map((to, index) => pathEdge(source, to, index, targets.length)))++// Splits that lead into each other, so opening the first path moves the targets of the splits below it+const nestedSplits: FlowGraph = {+ actions: ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'].map((id) =>+ step(id, id === 'n0' ? 'trigger' : ['n6', 'n7'].includes(id) ? 'function' : 'conditional_branch')+ ),+ edges: [+ { from: 'n0', to: 'n1', type: 'continue' },+ ...splits([+ ['n1', ['n2', 'n2', 'n5']],+ ['n2', ['n3', 'n7']],+ ['n3', ['n4', 'n5']],+ ['n4', ['n5', 'n6', 'n6']],+ ['n5', ['n6', 'n6']],+ ]),+ { from: 'n6', to: 'n7', type: 'continue' },+ ],+}+const nestedSplitsGroups = computePathGroups(nestedSplits)++const longDrop: FlowGraph = {+ actions: ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6'].map((id) =>+ step(id, id === 'n0' ? 'trigger' : id === 'n6' ? 'function' : 'conditional_branch')+ ),+ edges: [+ { from: 'n0', to: 'n1', type: 'continue' },+ ...splits([+ ['n1', ['n2', 'n2', 'n5']],+ ['n2', ['n3', 'n3', 'n4', 'n3']],+ ['n3', ['n4', 'n5', 'n6']],+ ['n4', ['n5', 'n5']],+ ['n5', ['n6']],+ ]),+ ],+}++const TEN = Array.from({ length: 10 }, (_, index) => `p${index}`)+const busyJoin: FlowGraph = {+ actions: [+ step('trigger', 'trigger'),+ step('split', 'conditional_branch'),+ ...TEN.map((id) => step(id)),+ step('exit'),+ ],+ edges: [+ { from: 'trigger', to: 'split', type: 'continue' },+ ...splits([['split', TEN]]),+ ...TEN.map((id): HogFlowEdge => ({ from: id, to: 'exit', type: 'continue' })),+ ],+}++const laterCross: FlowGraph = {+ actions: ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'].map((id) =>+ step(id, id === 'n0' ? 'trigger' : id === 'n9' ? 'function' : 'conditional_branch')+ ),+ edges: [+ { from: 'n0', to: 'n1', type: 'continue' },+ ...splits([+ ['n1', ['n2', 'n7', 'n2']],+ ['n2', ['n3', 'n3', 'n4', 'n3']],+ ['n3', ['n4', 'n4', 'n9', 'n8']],+ ['n4', ['n5', 'n5', 'n7', 'n5']],+ ['n5', ['n6', 'n8', 'n7', 'n6']],+ ['n6', ['n7', 'n7', 'n8', 'n7']],+ ['n7', ['n8', 'n8', 'n9', 'n8']],+ ['n8', ['n9', 'n9', 'n9', 'n9']],+ ]),+ ],+}++type Segment = [Point, Point]+const segmentsOf = (points: Point[]): Segment[] => points.slice(1).map((end, index) => [points[index], end])+const span = (a: number, b: number): [number, number] => [Math.min(a, b), Math.max(a, b)]++function overlap([a0, a1]: Segment, [b0, b1]: Segment): number {+ const axis =+ a0.y === a1.y && b0.y === b1.y && a0.y === b0.y+ ? 'x'+ : a0.x === a1.x && b0.x === b1.x && a0.x === b0.x+ ? 'y'+ : null+ if (!axis) {+ return 0+ }+ const [aLow, aHigh] = span(a0[axis], a1[axis])+ const [bLow, bHigh] = span(b0[axis], b1[axis])+ return Math.min(aHigh, bHigh) - Math.max(aLow, bLow)+}++function crosses(one: Segment, other: Segment): boolean {+ const [across, down] = one[0].y === one[1].y ? [one, other] : [other, one]+ const [left, right] = span(across[0].x, across[1].x)+ const [top, bottom] = span(down[0].y, down[1].y)+ const { x } = down[0]+ const { y } = across[0]+ return down[1].x === x && across[1].y === y && x > left && x < right && y > top && y < bottom+}++const pairsOf = <T>(items: T[]): [T, T][] =>+ items.flatMap((one, index) => items.slice(index + 1).map((other): [T, T] => [one, other]))+const OUTER_ORDER = OUTER.slice(0, -1).map((arm) => `${arm}1`)const INNER_ORDER = INNER.map((arm) => `${arm}1`)@@ -105,6 +243,105 @@ describe('layoutTileCanvas', () => {expect(tops).toEqual(tops.map(() => placeOf(outerArms[opened]).top))})+ it.each([+ ['a split into a shared step, closed', sharedTarget, sharedTargetGroups, [] as string[]],+ ['a split into a shared step, open', sharedTarget, sharedTargetGroups, sharedTargetGroups.map((g) => g.id)],+ [+ 'splits that lead into each other, with the first path open',+ nestedSplits,+ nestedSplitsGroups,+ ['path:n2:branch:0'],+ ],+ ['an arrow that turns only near its target', longDrop, computePathGroups(longDrop), [] as string[]],+ ['arrows that cross below the nearest target', laterCross, computePathGroups(laterCross), [] as string[]],+ ])(+ 'gives each arrow of a split its own line, with its label on it, for %s',+ async (_, flow, flowGroups, openIds) => {+ const { layout, sizes, edges } = await layOut(flow, flowGroups, openIds)+ const routes = Object.values(layout.edges)+ const routed = (from: VisibleEdge[]): [string, CanvasLayout['edges'][string]][] =>+ from.filter(({ id }) => layout.edges[id]).map(({ id }) => [id, layout.edges[id]])+ const fromSplits = Object.values(groupBy(edges, (edge) => edge.source)).filter((group) => group.length > 1)++ const sharedRuns = pairsOf(routes).filter(([one, other]) =>+ segmentsOf(one.points).some((a) => segmentsOf(other.points).some((b) => overlap(a, b) > 1))+ )+ const splitCrossings = fromSplits.flatMap((group) =>+ pairsOf(routed(group))+ .filter(([[, one], [, other]]) =>+ segmentsOf(one.points).some((a) => segmentsOf(other.points).some((b) => crosses(a, b)))+ )+ .map(([[one], [other]]) => [one, other])+ )+ const onLine = (label: Point, [a, b]: Segment): boolean =>+ a.x === b.x &&+ Math.abs(a.x - label.x) < 1 &&+ label.y >= span(a.y, b.y)[0] &&+ label.y <= span(a.y, b.y)[1]+ const labelsOffTheirLine = routed(fromSplits.flat())+ .filter(+ ([, { label, points }]) => !label || !segmentsOf(points).some((segment) => onLine(label, segment))+ )+ .map(([id]) => id)++ const meetsTile = (point: Point | undefined, node: string): boolean => {+ const { x, width } = sizes[node].anchor as Box+ return !!point && Math.abs(point.x - layout.positions[node].x - x) < width / 2+ }+ const arrowsOffTheirTiles = edges+ .filter(({ id, source, target }) => {+ const points = layout.edges[id]?.points+ return !meetsTile(points?.[0], source) || !meetsTile(points?.at(-1), target)+ })+ .map(({ id }) => id)++ expect({+ unrouted: edges.filter(({ id }) => !layout.edges[id]).map(({ id }) => id),+ sharedRuns,+ splitCrossings,+ labelsOffTheirLine,+ arrowsOffTheirTiles,+ }).toEqual({+ unrouted: [],+ sharedRuns: [],+ splitCrossings: [],+ labelsOffTheirLine: [],+ arrowsOffTheirTiles: [],+ })+ }+ )++ it('keeps the arrowheads into a step with many arrows apart, and the arrows out of a wide split on its tile', async () => {+ const { layout, sizes, edges } = await layOut(busyJoin, computePathGroups(busyJoin), [])+ const xs = (from: VisibleEdge[], end: 0 | -1): number[] =>+ from.map(({ id }) => layout.edges[id].points.at(end)?.x ?? 0).sort((a, b) => a - b)+ const ends = xs(+ edges.filter((edge) => edge.target === 'exit'),+ -1+ )+ const gaps = ends.slice(1).map((x, index) => x - ends[index])+ const tile = sizes.split.anchor as Box+ const tileLeft = layout.positions.split.x + tile.x - tile.width / 2+ const starts = xs(+ edges.filter((edge) => edge.source === 'split'),+ 0+ )++ expect(ends).toHaveLength(10)+ expect(Math.min(...gaps)).toBeGreaterThanOrEqual(8)+ expect(starts.filter((x) => x < tileLeft || x > tileLeft + tile.width)).toEqual([])+ })++ it('stops a layout that a newer one replaced before its next pass', async () => {+ const replaced = new Error('replaced')+ const stopIfStale = jest.fn(() => {+ throw replaced+ })++ await expect(layOut(workflow, groups, [], stopIfStale)).rejects.toBe(replaced)+ expect(stopIfStale).toHaveBeenCalledTimes(1)+ })+it('gives a path no more room for a name longer than its label shows', () => {const named = (label: string): number =>pathFrameSpecs([{ ...outerArms[0], label }], [outerArms[0].id], [])[0].minWidthdiff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.tsindex 1aea9aa080a9..5def9e4cf226 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLayout.ts@@ -1,6 +1,7 @@-import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk.bundled.js'+import type { ElkExtendedEdge, ElkLabel, ElkNode, ElkPort } from 'elkjs/lib/elk.bundled.js'import { getElk } from 'lib/elk'+import { groupBy } from 'lib/utils/arrays'import { getEdgeId } from '../../edgeId'import { isInPathGroup, openPathFrames, PathGroup, Point, VisibleEdge, VisibleNode } from './tileCanvasModel'@@ -9,6 +10,12 @@ export const TILE_SIZE = 64export const EDGE_LABEL_HEIGHT = 22const BADGE_ROOM = 10const PORT_SPREAD = 14+const PORT_MARGIN = 4+const ARROW_HALF_WIDTH = 4+// Arrowheads closer than their width draw as one shape, so many arrows into one step spread past its tile.+const MIN_ARROWHEAD_GAP = 2 * ARROW_HALF_WIDTH + 2+// ELK can move a split's targets after the ports are pinned, which changes the order the ports need.+const MAX_LAYOUT_PASSES = 4const FRAME_PADDING = { top: 30, side: 16, bottom: 16 }export interface Box {@@ -75,15 +82,18 @@ export function tileEntry(position: Point, size: NodeSize): Point {return { x: position.x + (size.anchor ? size.anchor.x : size.width / 2), y: position.y }}-function tilePorts(size: NodeSize, count: number): { in: Point; out: Point[] } {- const centerX = tileEntry({ x: 0, y: 0 }, size).x- return {- in: { x: centerX, y: 0 },- out: Array.from({ length: count }, (_, index) => ({- x: centerX + (index - (count - 1) / 2) * PORT_SPREAD,- y: size.height,- })),- }+interface PortOrder {+ out: Map<string, number>+ in: Map<string, number>+}++function portSpread(size: NodeSize, count: number, minGap: number): number {+ const room = (size.anchor?.width ?? size.width) - 2 * PORT_MARGIN+ return count > 1 ? Math.min(PORT_SPREAD, Math.max(minGap, room / (count - 1))) : PORT_SPREAD+}++function portX(size: NodeSize, slot: number, count: number, minGap: number): number {+ return tileEntry({ x: 0, y: 0 }, size).x + (slot - (count - 1) / 2) * portSpread(size, count, minGap)}const LAYOUT_OPTIONS: Record<string, string> = {@@ -112,26 +122,53 @@ const FLAT_ONLY_OPTIONS: Record<string, string> = {/** An open frame is taller than the stacks in its row, and they line up with its top, not its middle. */const ROW_ALIGNMENT = { 'elk.alignment': 'TOP' }-function leafNode(id: string, size: NodeSize, portCount: number): ElkNode {- const ports = tilePorts(size, portCount)+const IN = ':in'+const OUT = ':out'++/** Each arrow has a port of its own at both ends, so ELK never merges two arrows into one run. */+function leafNode(id: string, size: NodeSize, edgesIn: VisibleEdge[], edgesOut: VisibleEdge[]): ElkNode {+ const port = (portId: string, side: 'NORTH' | 'SOUTH'): ElkPort => ({+ id: portId,+ width: 1,+ height: 1,+ layoutOptions: { 'elk.port.side': side },+ })return {id,width: size.width,height: size.height,- layoutOptions: { 'elk.portConstraints': 'FIXED_POS', ...ROW_ALIGNMENT },+ layoutOptions: { 'elk.portConstraints': 'FIXED_SIDE', ...ROW_ALIGNMENT },ports: [- { id: `${id}:in`, ...ports.in, width: 1, height: 1, layoutOptions: { 'elk.port.side': 'NORTH' } },- ...ports.out.map((point, index) => ({- id: `${id}:out:${index}`,- ...point,- width: 1,- height: 1,- layoutOptions: { 'elk.port.side': 'SOUTH' },- })),+ ...edgesIn.map((edge) => port(edge.id + IN, 'NORTH')),+ ...edgesOut.map((edge) => port(edge.id + OUT, 'SOUTH')),],}}+/** Pins each port under the tile, in its slot, because ELK centers free ports on the whole node and its caption. */+function pinPorts(node: ElkNode, sizes: Record<string, NodeSize>, order: PortOrder): ElkNode {+ const children = node.children?.map((child) => pinPorts(child, sizes, order))+ const size = sizes[node.id]+ if (!size || !node.ports) {+ return { ...node, children }+ }+ const into = node.ports.filter((port) => port.id.endsWith(IN)).length+ const ports = node.ports.map((port) => {+ const isIn = port.id.endsWith(IN)+ const edgeId = port.id.slice(0, -(isIn ? IN : OUT).length)+ const slot = (isIn ? order.in : order.out).get(edgeId) ?? 0+ const count = isIn ? into : node.ports!.length - into+ const x = portX(size, slot, count, isIn ? MIN_ARROWHEAD_GAP : 0)+ return { ...port, x, y: isIn ? 0 : size.height }+ })+ return {+ ...node,+ children,+ ports,+ layoutOptions: { ...node.layoutOptions, 'elk.portConstraints': 'FIXED_POS' },+ }+}+const FRAME_PADDING_OPTION = `[left=${FRAME_PADDING.side}, top=${FRAME_PADDING.top}, right=${FRAME_PADDING.side}, bottom=${FRAME_PADDING.bottom}]`function elkRootOptions(nested: boolean): Record<string, string> {@@ -153,19 +190,25 @@ function elkRootOptions(nested: boolean): Record<string, string> {* arrow, so it gets a blank one, and every path of a split starts in the same row. ELK skips a label with no text.*/function elkLabels(edge: VisibleEdge): ElkExtendedEdge['labels'] {+ // An inline label sits on its arrow. Otherwise ELK puts it beside the arrow, closer to the next arrow than to its own.+ const label = (text: string, width: number): ElkLabel => ({+ id: `${edge.id}:label`,+ text,+ width,+ height: EDGE_LABEL_HEIGHT,+ layoutOptions: { 'elk.edgeLabels.inline': 'true' },+ })if (edge.label) {- return [- { id: `${edge.id}:label`, text: edge.label, width: edgeLabelWidth(edge.label), height: EDGE_LABEL_HEIGHT },- ]+ return [label(edge.label, edgeLabelWidth(edge.label))]}- return edge.portCount > 1 ? [{ id: `${edge.id}:label`, text: ' ', width: 1, height: EDGE_LABEL_HEIGHT }] : []+ return edge.portCount > 1 ? [label(' ', 1)] : []}function elkEdge(edge: VisibleEdge): ElkExtendedEdge {return {id: edge.id,- sources: [`${edge.source}:out:${edge.portIndex}`],- targets: [`${edge.target}:in`],+ sources: [edge.id + OUT],+ targets: [edge.id + IN],labels: elkLabels(edge),}}@@ -219,10 +262,12 @@ function assignFrameChildren(}containerOf(frame.parentId).children?.push(containers.get(frame.id) as ElkNode)}- const portCounts = new Map(edges.map((edge) => [edge.source, edge.portCount]))+ const byPortIndex = [...edges].sort((a, b) => a.portIndex - b.portIndex)Object.entries(sizes).forEach(([id, size]) => {framesStartingAt.get(id)?.forEach(placeFrame)- containerOf(deepestFrameOf.get(id)).children?.push(leafNode(id, size, portCounts.get(id) ?? 1))+ const edgesIn = byPortIndex.filter((edge) => edge.target === id)+ const edgesOut = byPortIndex.filter((edge) => edge.source === id)+ containerOf(deepestFrameOf.get(id)).children?.push(leafNode(id, size, edgesIn, edgesOut))})frames.forEach(placeFrame)}@@ -232,12 +277,68 @@ function buildElkGraph(sizes: Record<string, NodeSize>, edges: VisibleEdge[], frid: 'root',layoutOptions: elkRootOptions(frames.length > 0),children: [],- edges: edges.filter((edge) => sizes[edge.source] && sizes[edge.target]).map(elkEdge),+ edges: edges.map(elkEdge),}assignFrameChildren(root, sizes, edges, frames)return root}+/** Slots edges left to right. Arrows from one split into one step tie, and keep `rank` order, so both ends agree. */+function slotsBy(+ edges: VisibleEdge[],+ compare: (a: VisibleEdge, b: VisibleEdge) => number,+ rank: (edge: VisibleEdge) => number+): Map<string, number> {+ const ordered = [...edges].sort((a, b) => compare(a, b) || rank(a) - rank(b))+ return new Map(ordered.map((edge, slot) => [edge.id, slot]))+}++function xAt(points: Point[], y: number): number {+ const down = points.findIndex((start, index) => {+ const end = points[index + 1]+ return !!end && end.x === start.x && y >= Math.min(start.y, end.y) && y <= Math.max(start.y, end.y)+ })+ return down >= 0 ? points[down].x : (points.at(-1)?.x ?? 0)+}++/**+ * Two arrows that do not cross keep their left-to-right order at every height they share. So two arrows out of one step+ * take the order they have just above the nearer of their ends, and two arrows into one step the order just below the+ * nearer of their starts.+ */+function portOrderOf(layout: CanvasLayout, edges: VisibleEdge[]): PortOrder {+ const out = new Map<string, number>()+ const into = new Map<string, number>()+ const pointsOf = (edge: VisibleEdge): Point[] => layout.edges[edge.id]?.points ?? []+ const endY = (edge: VisibleEdge): number => pointsOf(edge).at(-1)?.y ?? 0+ const startY = (edge: VisibleEdge): number => pointsOf(edge)[0]?.y ?? 0+ const xAbove = (a: VisibleEdge, b: VisibleEdge): number => {+ if (a.target === b.target) {+ return 0+ }+ const y = Math.min(endY(a), endY(b)) - 1+ return xAt(pointsOf(a), y) - xAt(pointsOf(b), y)+ }+ const xBelow = (a: VisibleEdge, b: VisibleEdge): number => {+ if (a.source === b.source) {+ return 0+ }+ const y = Math.max(startY(a), startY(b)) + 1+ return xAt(pointsOf(a), y) - xAt(pointsOf(b), y)+ }+ Object.values(groupBy(edges, (edge) => edge.source)).forEach((fromOneStep) =>+ slotsBy(fromOneStep, xAbove, (edge) => edge.portIndex).forEach((slot, id) => out.set(id, slot))+ )+ Object.values(groupBy(edges, (edge) => edge.target)).forEach((intoOneStep) =>+ slotsBy(intoOneStep, xBelow, (edge) => out.get(edge.id) ?? 0).forEach((slot, id) => into.set(id, slot))+ )+ return { out, in: into }+}++const sameOrder = (one: PortOrder, other: PortOrder): boolean =>+ [...one.out].every(([id, slot]) => other.out.get(id) === slot) &&+ [...one.in].every(([id, slot]) => other.in.get(id) === slot)+function readLayout(result: ElkNode, frameIds: Set<string>): CanvasLayout {const positions: CanvasLayout['positions'] = {}const frames: CanvasLayout['frames'] = {}@@ -298,14 +399,30 @@ function attachToTiles(layout: CanvasLayout, edges: VisibleEdge[], sizes: Recordreturn { ...layout, edges: attached }}+/** `stopIfStale` throws when a newer layout replaces this one, so a stale layout sends no more passes to the shared ELK worker. */export async function layoutTileCanvas(sizes: Record<string, NodeSize>,edges: VisibleEdge[],- frames: PathFrameSpec[]+ frames: PathFrameSpec[],+ stopIfStale: () => void = () => {}): Promise<CanvasLayout> {const elk = await getElk()- const result = await elk.layout(buildElkGraph(sizes, edges, frames))- return attachToTiles(readLayout(result, new Set(frames.map((frame) => frame.id))), edges, sizes)+ const frameIds = new Set(frames.map((frame) => frame.id))+ const shown = edges.filter((edge) => sizes[edge.source] && sizes[edge.target])+ const graph = (): ElkNode => buildElkGraph(sizes, shown, frames)+ // The first pass only finds where each arrow goes. Later passes pin the ports in that order until it holds.+ let layout = readLayout(await elk.layout(graph()), frameIds)+ let order: PortOrder | null = null+ for (let pass = 1; pass < MAX_LAYOUT_PASSES; pass++) {+ stopIfStale()+ const next = portOrderOf(layout, shown)+ if (order && sameOrder(order, next)) {+ break+ }+ order = next+ layout = readLayout(await elk.layout(pinPorts(graph(), sizes, order)), frameIds)+ }+ return attachToTiles(layout, edges, sizes)}export function roundedPath(points: Point[]): string {@@ -339,7 +456,8 @@ export function arrowHead(points: Point[]): string {const length = Math.hypot(end.x - before.x, end.y - before.y) || 1const [dx, dy] = [(end.x - before.x) / length, (end.y - before.y) / length]const back = { x: end.x - dx * 7, y: end.y - dy * 7 }- return `M ${back.x - dy * 4} ${back.y + dx * 4} L ${end.x} ${end.y} L ${back.x + dy * 4} ${back.y - dx * 4}`+ const [wx, wy] = [dy * ARROW_HALF_WIDTH, dx * ARROW_HALF_WIDTH]+ return `M ${back.x - wx} ${back.y + wy} L ${end.x} ${end.y} L ${back.x + wx} ${back.y - wy}`}export function insertPoint(points: Point[]): Point {diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.tsindex a20da54d5293..db3a23039f8f 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasLogic.ts@@ -872,7 +872,7 @@ export const tileCanvasLogic = kea<tileCanvasLogicType>([return}try {- const layout = await layoutTileCanvas(sizes, input.edges, input.frames)+ const layout = await layoutTileCanvas(sizes, input.edges, input.frames, () => breakpoint())breakpoint()cache.layoutInput = inputactions.setLayout(layout, graph)diff --git a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.tsindex d92c946a81b8..6b47f517a934 100644--- a/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts+++ b/products/workflows/frontend/Workflows/hogflows/editor/tile-canvas/tileCanvasModel.ts@@ -420,7 +420,7 @@ function mergeVisibleEdges(workflow: FlowGraph, collapsed: Collapsed): VisibleEdreturn [...edgesById.values()]}-/** Each arrow leaves its step from its own port, in path order, so the arrows of a split never cross. */+/** Numbers the arrows of a step in path order. The layout places them by where they go, and uses this order for ties. */function assignSourcePorts(workflow: FlowGraph, edges: VisibleEdge[]): VisibleEdge[] {const bySource = new Map<string, VisibleEdge[]>()edges.forEach((edge) => bySource.set(edge.source, [...(bySource.get(edge.source) ?? []), edge]))