GraphPage: Added Reorganize button

This commit is contained in:
Bruno Fargnoli 2026-07-16 22:02:40 +02:00
parent 8148a1d105
commit fd2a362d59
3 changed files with 360 additions and 0 deletions

View file

@ -169,6 +169,39 @@
border: 1px solid rgba(71, 72, 74, 0.16);
}
.graph-page__reorganize {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.85rem;
border: 1px solid rgba(71, 72, 74, 0.18);
border-radius: var(--radius-md);
background: rgba(18, 19, 21, 0.96);
color: var(--on-surface);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.02em;
cursor: pointer;
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
transition: all var(--transition-base);
}
.graph-page__reorganize:hover:not(:disabled) {
border-color: rgba(143, 245, 255, 0.28);
background: rgba(143, 245, 255, 0.12);
color: var(--primary);
}
.graph-page__reorganize:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.graph-page__reorganize .material-symbols-outlined {
font-size: 1.05rem;
}
.graph-page__controls {
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.28);
}

View file

@ -8,6 +8,7 @@ import {
EdgeLabelRenderer,
Handle,
MiniMap,
Panel,
Position,
ReactFlow,
useEdgesState,
@ -58,6 +59,7 @@ import {
canFetchTencentMeshResult,
canFetchTripoMeshResult,
canNodeTypeAcceptIncomingConnection,
computeReorganizedLayout,
createComfyExecutionId,
createWorkflowDraftBindings,
createWorkflowDraftInputs,
@ -2835,6 +2837,36 @@ export default function GraphPage({ project }) {
}
}, [project.id, updateProjectNodePosition])
// Tidy up the canvas: lay the nodes out in clean left-to-right columns that
// follow the connections, persist the new positions, then re-fit the view.
const handleReorganize = useCallback(async () => {
const layout = computeReorganizedLayout(nodes, edges)
const movedNodes = nodes.filter(node => {
const position = layout[node.id]
return position && (position.x !== node.position.x || position.y !== node.position.y)
})
if (movedNodes.length === 0) {
return
}
setNodes(currentNodes => currentNodes.map(node => (
layout[node.id] ? { ...node, position: layout[node.id] } : node
)))
window.requestAnimationFrame(() => {
reactFlowInstance?.fitView?.({ padding: 0.2, duration: 400 })
})
try {
await Promise.all(movedNodes.map(node => (
updateProjectNodePosition(project.id, Number(node.id), layout[node.id])
)))
} catch (err) {
console.error('Failed to persist reorganized node positions:', err)
}
}, [nodes, edges, setNodes, reactFlowInstance, project.id, updateProjectNodePosition])
const handleEdgesDelete = useCallback(async (deletedEdges) => {
await Promise.all(
deletedEdges.map(edge => handleDeleteConnection(edge))
@ -3201,6 +3233,18 @@ export default function GraphPage({ project }) {
deleteKeyCode={null}
proOptions={{ hideAttribution: true }}
>
<Panel position="top-left">
<button
type="button"
className="graph-page__reorganize"
onClick={handleReorganize}
disabled={nodes.length === 0}
title="Reorganize nodes by following their connections"
>
<span className="material-symbols-outlined">account_tree</span>
<span>Reorganize</span>
</button>
</Panel>
<Background gap={24} size={1} color="rgba(143, 245, 255, 0.14)" />
<MiniMap pannable zoomable className="graph-page__minimap" nodeColor={minimapNodeColor} />
<Controls className="graph-page__controls" showInteractive={false} />

View file

@ -403,6 +403,289 @@ export function buildEdgeId(connection) {
return `edge:${connection.sourceNodeId}:${connection.outputId}:${connection.targetNodeId}:${connection.inputId}`
}
// Produce a clean, left-to-right layered layout that follows the connections.
//
// Nodes are layered into columns by longest path (roots with no incoming edge
// in column 0, every node one column right of its furthest-upstream source), so
// columns line up across the whole canvas. The nodes are then split into
// connected groups, and each group is laid out as its own tidy tree in a
// dedicated horizontal band stacked below the previous one — so distinct chains
// never interleave and it stays obvious which node feeds which. Within a group,
// each node's vertical center is relaxed toward the average of its connected
// neighbours (a few Sugiyama-style sweeps), which centers parents against their
// children. Returns a map of nodeId -> { x, y } for every id passed in.
export function computeReorganizedLayout(nodes, edges, options = {}) {
const horizontalGap = options.horizontalGap ?? 140
const verticalGap = options.verticalGap ?? 48
const groupGap = options.groupGap ?? 140
const defaultWidth = options.defaultWidth ?? 360
const defaultHeight = options.defaultHeight ?? 280
const sweeps = options.sweeps ?? 8
if (!Array.isArray(nodes) || nodes.length === 0) {
return {}
}
const nodeById = new Map(nodes.map(node => [node.id, node]))
const predecessors = new Map(nodes.map(node => [node.id, []]))
const successors = new Map(nodes.map(node => [node.id, []]))
const neighbours = new Map(nodes.map(node => [node.id, new Set()]))
for (const edge of edges || []) {
const source = String(edge.source)
const target = String(edge.target)
if (source === target || !nodeById.has(source) || !nodeById.has(target)) {
continue
}
successors.get(source).push(target)
predecessors.get(target).push(source)
neighbours.get(source).add(target)
neighbours.get(target).add(source)
}
// --- Layering (two passes) -----------------------------------------------
// Pass 1 (ASAP): longest path from the sources, via Kahn (cycle-safe). This
// gives the total number of columns.
const asapDepth = new Map(nodes.map(node => [node.id, 0]))
const remainingIndegree = new Map(nodes.map(node => [node.id, predecessors.get(node.id).length]))
const forwardQueue = nodes.filter(node => remainingIndegree.get(node.id) === 0).map(node => node.id)
const forwardProcessed = new Set()
while (forwardQueue.length > 0) {
const id = forwardQueue.shift()
if (forwardProcessed.has(id)) {
continue
}
forwardProcessed.add(id)
for (const next of successors.get(id)) {
if (asapDepth.get(next) < asapDepth.get(id) + 1) {
asapDepth.set(next, asapDepth.get(id) + 1)
}
remainingIndegree.set(next, remainingIndegree.get(next) - 1)
if (remainingIndegree.get(next) === 0) {
forwardQueue.push(next)
}
}
}
for (const node of nodes) {
if (!forwardProcessed.has(node.id)) {
const maxSourceDepth = predecessors.get(node.id)
.reduce((max, source) => Math.max(max, asapDepth.get(source) ?? 0), -1)
asapDepth.set(node.id, maxSourceDepth + 1)
}
}
const maxDepth = Math.max(...nodes.map(node => asapDepth.get(node.id)))
// Pass 2 (ALAP): longest path from each node to a sink, via reverse Kahn. The
// final column is `maxDepth - reverseDepth`, which pushes every node as far
// right as its earliest consumer allows. Input nodes therefore sit in the
// column immediately left of the node they feed, instead of being stranded in
// column 0 with an edge stretched across the whole graph.
const reverseDepth = new Map(nodes.map(node => [node.id, 0]))
const remainingOutdegree = new Map(nodes.map(node => [node.id, successors.get(node.id).length]))
const backwardQueue = nodes.filter(node => remainingOutdegree.get(node.id) === 0).map(node => node.id)
const backwardProcessed = new Set()
while (backwardQueue.length > 0) {
const id = backwardQueue.shift()
if (backwardProcessed.has(id)) {
continue
}
backwardProcessed.add(id)
for (const previous of predecessors.get(id)) {
if (reverseDepth.get(previous) < reverseDepth.get(id) + 1) {
reverseDepth.set(previous, reverseDepth.get(id) + 1)
}
remainingOutdegree.set(previous, remainingOutdegree.get(previous) - 1)
if (remainingOutdegree.get(previous) === 0) {
backwardQueue.push(previous)
}
}
}
for (const node of nodes) {
if (!backwardProcessed.has(node.id)) {
const maxSuccessorReverse = successors.get(node.id)
.reduce((max, successor) => Math.max(max, reverseDepth.get(successor) ?? 0), -1)
reverseDepth.set(node.id, maxSuccessorReverse + 1)
}
}
const depth = new Map(nodes.map(node => [node.id, maxDepth - reverseDepth.get(node.id)]))
const getDimensions = (id) => {
const node = nodeById.get(id)
return {
width: node.measured?.width || node.width || defaultWidth,
height: node.measured?.height || node.height || defaultHeight
}
}
// Column x positions use the widest node in each column, shared across every
// group so the columns stay aligned down the whole canvas.
const columnWidth = new Map()
for (const node of nodes) {
const columnKey = depth.get(node.id)
columnWidth.set(columnKey, Math.max(columnWidth.get(columnKey) ?? 0, getDimensions(node.id).width))
}
const columnX = new Map()
let cursorX = 0
for (const columnKey of [...columnWidth.keys()].sort((a, b) => a - b)) {
columnX.set(columnKey, cursorX)
cursorX += columnWidth.get(columnKey) + horizontalGap
}
// Split into connected groups (undirected) via flood fill.
const groupByNode = new Map()
const groups = []
for (const node of nodes) {
if (groupByNode.has(node.id)) {
continue
}
const members = []
const stack = [node.id]
groupByNode.set(node.id, groups.length)
while (stack.length > 0) {
const id = stack.pop()
members.push(id)
for (const neighbour of neighbours.get(id)) {
if (!groupByNode.has(neighbour)) {
groupByNode.set(neighbour, groups.length)
stack.push(neighbour)
}
}
}
groups.push(members)
}
// Keep groups in a stable order: by their leftmost column, then by their
// current average vertical position.
const averageOf = (values) => values.reduce((sum, value) => sum + value, 0) / values.length
groups.sort((a, b) => {
const columnA = Math.min(...a.map(id => depth.get(id)))
const columnB = Math.min(...b.map(id => depth.get(id)))
if (columnA !== columnB) {
return columnA - columnB
}
return averageOf(a.map(id => nodeById.get(id).position?.y ?? 0))
- averageOf(b.map(id => nodeById.get(id).position?.y ?? 0))
})
const positions = {}
let bandTop = 0
for (const members of groups) {
// Bucket this group's nodes into their columns.
const groupColumns = new Map()
for (const id of members) {
const columnKey = depth.get(id)
if (!groupColumns.has(columnKey)) {
groupColumns.set(columnKey, [])
}
groupColumns.get(columnKey).push(id)
}
const columnKeys = [...groupColumns.keys()].sort((a, b) => a - b)
// Seed each column's vertical order by current position, then refine with a
// barycenter pass so connected nodes end up adjacent (fewer crossings).
const orderIndex = new Map()
const reindex = (columnKey) => groupColumns.get(columnKey).forEach((id, index) => orderIndex.set(id, index))
for (const columnKey of columnKeys) {
groupColumns.get(columnKey).sort((a, b) => (nodeById.get(a).position?.y ?? 0) - (nodeById.get(b).position?.y ?? 0))
reindex(columnKey)
}
for (const columnKey of columnKeys) {
if (columnKey === columnKeys[0]) {
continue
}
const column = groupColumns.get(columnKey)
const barycenter = new Map()
for (const id of column) {
const sources = predecessors.get(id)
barycenter.set(id, sources.length > 0
? averageOf(sources.map(source => orderIndex.get(source) ?? 0))
: (orderIndex.get(id) ?? 0))
}
column.sort((a, b) => barycenter.get(a) - barycenter.get(b))
reindex(columnKey)
}
// Initial vertical centers: stack each column top-to-bottom.
const centerY = new Map()
for (const columnKey of columnKeys) {
let cursorY = 0
for (const id of groupColumns.get(columnKey)) {
const { height } = getDimensions(id)
centerY.set(id, cursorY + height / 2)
cursorY += height + verticalGap
}
}
// Pack a column: honor each node's desired center where possible while
// keeping the column order and a minimum gap (a forward pass that only ever
// pushes nodes downward, so overlaps are impossible), then apply a single
// uniform shift so the column stays centered on the neighbours' barycenter
// instead of drifting downward over repeated passes.
const packColumn = (column, desiredCenters) => {
centerY.set(column[0], desiredCenters.get(column[0]))
for (let index = 1; index < column.length; index += 1) {
const previous = column[index - 1]
const current = column[index]
const minCenter = centerY.get(previous)
+ getDimensions(previous).height / 2
+ verticalGap
+ getDimensions(current).height / 2
centerY.set(current, Math.max(desiredCenters.get(current), minCenter))
}
const drift = averageOf(column.map(id => desiredCenters.get(id)))
- averageOf(column.map(id => centerY.get(id)))
for (const id of column) {
centerY.set(id, centerY.get(id) + drift)
}
}
// Relaxation sweeps: alternate directions, pulling each node toward the
// average center of its neighbours in the adjacent columns.
for (let sweep = 0; sweep < sweeps; sweep += 1) {
const order = sweep % 2 === 0 ? columnKeys : [...columnKeys].reverse()
for (const columnKey of order) {
const column = groupColumns.get(columnKey)
const desiredCenters = new Map()
for (const id of column) {
const connected = [...predecessors.get(id), ...successors.get(id)]
.filter(neighbour => groupByNode.get(neighbour) === groupByNode.get(id))
desiredCenters.set(id, connected.length > 0
? averageOf(connected.map(neighbour => centerY.get(neighbour)))
: centerY.get(id))
}
packColumn(column, desiredCenters)
}
}
// Drop this group into its own band, normalising so the group's topmost
// edge starts at bandTop.
let groupTop = Infinity
let groupBottom = -Infinity
for (const id of members) {
const { height } = getDimensions(id)
groupTop = Math.min(groupTop, centerY.get(id) - height / 2)
groupBottom = Math.max(groupBottom, centerY.get(id) + height / 2)
}
for (const id of members) {
const { width, height } = getDimensions(id)
const column = depth.get(id)
positions[id] = {
x: columnX.get(column) + (columnWidth.get(column) - width) / 2,
y: bandTop + (centerY.get(id) - height / 2) - groupTop
}
}
bandTop += (groupBottom - groupTop) + groupGap
}
return positions
}
export function getPointerClientPosition(event) {
if ('clientX' in event && 'clientY' in event) {
return { x: event.clientX, y: event.clientY }