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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { expect } from '@playwright/test'

import { comfyPageFixture as test } from '../../../../fixtures/ComfyPage'

test.describe('Vue Node Drag Snapping', { tag: '@ui' }, () => {
test.beforeEach(async ({ comfyPage }) => {
await comfyPage.settings.setSetting('Comfy.UseNewMenu', 'Disabled')
await comfyPage.settings.setSetting('Comfy.VueNodes.Enabled', true)
await comfyPage.workflow.loadWorkflow('default')
await comfyPage.canvasOps.resetView()
await comfyPage.vueNodes.waitForNodes(6)
})

test('snaps a dragged node to another node in Vue nodes mode', async ({
comfyPage
}) => {
await comfyPage.settings.setSetting(
'Comfy.Canvas.AlignNodesWhileDragging',
true
)

const ksamplerNode = comfyPage.vueNodes.getNodeByTitle('KSampler').first()
const checkpointNode = comfyPage.vueNodes
.getNodeByTitle('Load Checkpoint')
.first()
const ksamplerHeader = ksamplerNode.locator('.lg-node-header')

const ksamplerBox = await ksamplerNode.boundingBox()
const checkpointBox = await checkpointNode.boundingBox()
const headerBox = await ksamplerHeader.boundingBox()

if (!ksamplerBox || !checkpointBox || !headerBox) {
throw new Error('Expected Vue node bounding boxes to be available')
}

const dragStart = {
x: headerBox.x + headerBox.width / 2,
y: headerBox.y + headerBox.height / 2
}
const targetLeft = checkpointBox.x + 5
const dragTarget = {
x: dragStart.x + (targetLeft - ksamplerBox.x),
y: dragStart.y
}

await comfyPage.canvasOps.dragAndDrop(dragStart, dragTarget)

await expect
.poll(async () => {
const draggedBox = await ksamplerNode.boundingBox()
return draggedBox ? Math.round(draggedBox.x) : null
})
.toBe(Math.round(checkpointBox.x))
})
})
11 changes: 11 additions & 0 deletions src/components/rightSidePanel/settings/TabGlobalSettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ const snapToGrid = computed({
set: (value) => settingStore.set('pysssss.SnapToGrid', value)
})

const alignNodesWhileDragging = computed({
get: () => settingStore.get('Comfy.Canvas.AlignNodesWhileDragging'),
set: (value) =>
settingStore.set('Comfy.Canvas.AlignNodesWhileDragging', value)
})

// CONNECTION LINKS settings
const linkShape = computed({
get: () => settingStore.get('Comfy.Graph.LinkMarkers'),
Expand Down Expand Up @@ -160,6 +166,11 @@ function openFullSettings() {
:label="t('rightSidePanel.globalSettings.snapNodesToGrid')"
:tooltip="t('settings.pysssss_SnapToGrid.tooltip')"
/>
<FieldSwitch
v-model="alignNodesWhileDragging"
:label="t('settings.Comfy_Canvas_AlignNodesWhileDragging.name')"
:tooltip="t('settings.Comfy_Canvas_AlignNodesWhileDragging.tooltip')"
/>
</div>
</PropertiesAccordionItem>

Expand Down
36 changes: 34 additions & 2 deletions src/lib/litegraph/src/LGraphCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5007,6 +5007,9 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>

if (!LiteGraph.vueNodesMode || !this.overlayCtx) {
this._drawConnectingLinks(ctx)
if (LiteGraph.vueNodesMode) {
this._drawVueDragAlignmentGuides(ctx)
}
} else {
this._drawOverlayLinks()
}
Expand Down Expand Up @@ -5111,7 +5114,8 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>

octx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height)

if (!this.linkConnector.isConnecting) return
const hasDragGuides = layoutStore.vueDragSnapGuides.value.length > 0
if (!this.linkConnector.isConnecting && !hasDragGuides) return

octx.save()

Expand All @@ -5120,11 +5124,39 @@ export class LGraphCanvas implements CustomEventDispatcher<LGraphCanvasEventMap>

this.ds.toCanvasContext(octx)

this._drawConnectingLinks(octx)
if (this.linkConnector.isConnecting) {
this._drawConnectingLinks(octx)
}
this._drawVueDragAlignmentGuides(octx)

octx.restore()
}

private _drawVueDragAlignmentGuides(ctx: CanvasRenderingContext2D): void {
const guides = layoutStore.vueDragSnapGuides.value
if (!guides.length) return

const scale = this.ds.scale || 1
ctx.save()
ctx.beginPath()
ctx.lineWidth = 1 / scale
ctx.strokeStyle = '#ff4d4f'
ctx.setLineDash([6 / scale, 4 / scale])

for (const guide of guides) {
if (guide.axis === 'vertical') {
ctx.moveTo(guide.coordinate, guide.start)
ctx.lineTo(guide.coordinate, guide.end)
} else {
ctx.moveTo(guide.start, guide.coordinate)
ctx.lineTo(guide.end, guide.coordinate)
}
}

ctx.stroke()
ctx.restore()
}

/** Get the target snap / highlight point in graph space */
private _getHighlightPosition(): Readonly<Point> {
return LiteGraph.snaps_for_comfy
Expand Down
4 changes: 4 additions & 0 deletions src/locales/en/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@
"name": "Show selection toolbox",
"tooltip": "Display a floating toolbar when nodes are selected, providing quick access to common actions."
},
"Comfy_Canvas_AlignNodesWhileDragging": {
"name": "Align nodes while dragging",
"tooltip": "When enabled in Nodes 2.0, dragging a node selection near another node will snap matching edges and centers together."
},
"Comfy_ConfirmClear": {
"name": "Require confirmation when clearing workflow"
},
Expand Down
10 changes: 10 additions & 0 deletions src/platform/settings/constants/coreSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,16 @@ export const CORE_SETTINGS: SettingParams[] = [
defaultValue: true,
versionAdded: '1.10.5'
},
{
id: 'Comfy.Canvas.AlignNodesWhileDragging',
category: ['LiteGraph', 'Canvas', 'AlignNodesWhileDragging'],
name: 'Align nodes while dragging',
tooltip:
'When enabled in Nodes 2.0, dragging a node selection near another node will snap matching edges and centers together.',
type: 'boolean',
defaultValue: false,
versionAdded: '1.42.0'
},
{
id: 'LiteGraph.Reroute.SplineOffset',
name: 'Reroute spline offset',
Expand Down
2 changes: 2 additions & 0 deletions src/renderer/core/layout/store/layoutStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type {
LinkSegmentLayout,
MoveNodeOperation,
MoveRerouteOperation,
NodeAlignmentGuide,
NodeBoundsUpdate,
NodeId,
NodeLayout,
Expand Down Expand Up @@ -144,6 +145,7 @@ class LayoutStoreImpl implements LayoutStore {

// Vue dragging state for selection toolbox (public ref for direct mutation)
public isDraggingVueNodes = ref(false)
public vueDragSnapGuides = ref<NodeAlignmentGuide[]>([])
// Vue resizing state to prevent drag from activating during resize
public isResizingVueNodes = ref(false)

Expand Down
7 changes: 7 additions & 0 deletions src/renderer/core/layout/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ export interface Bounds {
height: number
}

export interface NodeAlignmentGuide {
axis: 'horizontal' | 'vertical'
coordinate: number
start: number
end: number
}

export interface NodeBoundsUpdate {
nodeId: NodeId
bounds: Bounds
Expand Down
8 changes: 8 additions & 0 deletions src/renderer/core/layout/utils/geometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ export function isBoundsEqual(a: Bounds, b: Bounds): boolean {
)
}

export function translateBounds(bounds: Bounds, delta: Point): Bounds {
return {
...bounds,
x: bounds.x + delta.x,
y: bounds.y + delta.y
}
}

export function isSizeEqual(a: Size, b: Size): boolean {
return a.width === b.width && a.height === b.height
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ vi.mock('@/renderer/extensions/vueNodes/layout/useNodeDrag', () => {
const startDrag = vi.fn()
const handleDrag = vi.fn()
const endDrag = vi.fn()
const cancelDrag = vi.fn()
return {
useNodeDrag: () => ({
startDrag,
handleDrag,
endDrag
endDrag,
cancelDrag
})
}
})
Expand Down Expand Up @@ -93,13 +95,15 @@ const mockData = vi.hoisted(() => {
vi.mock('@/renderer/core/layout/store/layoutStore', () => {
const isDraggingVueNodes = ref(false)
const isResizingVueNodes = ref(false)
const vueDragSnapGuides = ref([])
const fakeNodeLayoutRef = ref(mockData.fakeNodeLayout)
const getNodeLayoutRef = vi.fn(() => fakeNodeLayoutRef)
const setSource = vi.fn()
return {
layoutStore: {
isDraggingVueNodes,
isResizingVueNodes,
vueDragSnapGuides,
getNodeLayoutRef,
setSource
}
Expand Down Expand Up @@ -136,6 +140,9 @@ describe('useNodePointerInteractions', () => {
vi.resetAllMocks()
selectedItemsState.items = []
setActivePinia(createTestingPinia())
layoutStore.isDraggingVueNodes.value = false
layoutStore.isResizingVueNodes.value = false
layoutStore.vueDragSnapGuides.value = []
})

it('should only start drag on left-click', async () => {
Expand Down Expand Up @@ -184,6 +191,7 @@ describe('useNodePointerInteractions', () => {

it('should handle drag termination via cancel and context menu', async () => {
const { handleNodeSelect } = useNodeEventHandlers()
const { cancelDrag } = useNodeDrag()

const { pointerHandlers } = useNodePointerInteractions('test-node-123')

Expand Down Expand Up @@ -229,6 +237,7 @@ describe('useNodePointerInteractions', () => {
pointerHandlers.onContextmenu(contextMenuEvent)

expect(preventDefaultSpy).toHaveBeenCalled()
expect(cancelDrag).toHaveBeenCalledTimes(1)
})

it('should integrate with layout store dragging state', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { useNodeDrag } from '@/renderer/extensions/vueNodes/layout/useNodeDrag'
export function useNodePointerInteractions(
nodeIdRef: MaybeRefOrGetter<string>
) {
const { startDrag, endDrag, handleDrag } = useNodeDrag()
const { startDrag, endDrag, handleDrag, cancelDrag } = useNodeDrag()
// Use canvas interactions for proper wheel event handling and pointer event capture control
const { forwardEventToCanvas, shouldHandleNodePointerEvents } =
useCanvasInteractions()
Expand Down Expand Up @@ -102,6 +102,7 @@ export function useNodePointerInteractions(

function cleanupDragState() {
layoutStore.isDraggingVueNodes.value = false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question (non-blocking): onContextmenu (line 166) calls cleanupDragState() instead of endDrag(), which means stopShiftSync listeners are never torn down. This is a pre-existing pattern, but this PR adds vueDragSnapGuides cleanup here without the corresponding endDrag call -- so the snap guides are cleared but shift listeners still leak. Would it make sense to call safeDragEnd here (similar to onPointercancel) to clean up everything?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree, added safeDragCancel there that wraps cancelDrag and cleanupDragState

layoutStore.vueDragSnapGuides.value = []
}

function safeDragStart(event: PointerEvent, nodeId: string) {
Expand All @@ -124,6 +125,17 @@ export function useNodePointerInteractions(
}
}

function safeDragCancel() {
try {
cancelDrag()
} catch (error) {
console.error('Error during cancelDrag:', error)
} finally {
hasDraggingStarted = false
cleanupDragState()
}
}

function onPointerup(event: PointerEvent) {
if (forwardMiddlePointerIfNeeded(event)) return
// Don't handle pointer events when canvas is in panning mode - forward to canvas instead
Expand Down Expand Up @@ -166,12 +178,15 @@ export function useNodePointerInteractions(
if (!layoutStore.isDraggingVueNodes.value) return

event.preventDefault()
// Simply cleanup state without calling endDrag to avoid synthetic event creation
cleanupDragState()
safeDragCancel()
}

// Cleanup on unmount to prevent resource leaks
onScopeDispose(() => {
if (hasDraggingStarted || layoutStore.isDraggingVueNodes.value) {
safeDragCancel()
return
}
cleanupDragState()
})

Expand Down
Loading
Loading