diff --git a/src/components/graph/selectionToolbox/ColorPickerButton.test.ts b/src/components/graph/selectionToolbox/ColorPickerButton.test.ts index cfb1ce74000..25baccc0733 100644 --- a/src/components/graph/selectionToolbox/ColorPickerButton.test.ts +++ b/src/components/graph/selectionToolbox/ColorPickerButton.test.ts @@ -70,8 +70,7 @@ vi.mock(import('@/utils/colorUtil'), () => ({ vi.mock(import('@/utils/litegraphUtil'), () => ({ getItemsColorOption: vi.fn(() => null), isLGraphNode: vi.fn((item) => item?.type === 'LGraphNode'), - isLGraphGroup: vi.fn((item) => item?.type === 'LGraphGroup'), - isReroute: vi.fn(() => false) + isLGraphGroup: vi.fn((item) => item?.type === 'LGraphGroup') })) describe('ColorPickerButton', () => { diff --git a/src/lib/litegraph/src/LGraphCanvas.selection.test.ts b/src/lib/litegraph/src/LGraphCanvas.selection.test.ts new file mode 100644 index 00000000000..65c927c9c89 --- /dev/null +++ b/src/lib/litegraph/src/LGraphCanvas.selection.test.ts @@ -0,0 +1,385 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { Positionable, Rect } from '@/lib/litegraph/src/interfaces' +import type { CanvasPointerEvent } from '@/lib/litegraph/src/types/events' +import { + LGraph, + LGraphCanvas, + LGraphGroup, + LGraphNode, + LiteGraph +} from '@/lib/litegraph/src/litegraph' +import { createMockCanvasRenderingContext2D } from '@/utils/__tests__/litegraphTestUtils' + +vi.mock(import('@/renderer/core/layout/store/layoutStore')) + +type Modifiers = Partial< + Pick +> + +function createCanvas(graph: LGraph): LGraphCanvas { + const canvasElement = document.createElement('canvas') + canvasElement.width = 800 + canvasElement.height = 600 + canvasElement.getContext = vi + .fn() + .mockReturnValue(createMockCanvasRenderingContext2D()) + canvasElement.getBoundingClientRect = vi.fn().mockReturnValue({ + left: 0, + top: 0, + width: 800, + height: 600 + }) + return new LGraphCanvas(canvasElement, graph, { skip_render: true }) +} + +function addNode(graph: LGraph, title: string, x: number, y: number) { + const node = new LGraphNode(title) + node.pos = [x, y] + node.size = [100, 60] + node.updateArea() + graph.add(node) + return node +} + +function addGroup(graph: LGraph, title: string, bounds: Rect) { + const group = new LGraphGroup(title) + group._bounding.set(bounds) + graph.add(group) + return group +} + +function pointerEvent( + type: 'pointerdown' | 'pointerup', + x: number, + y: number, + modifiers: Modifiers +): PointerEvent { + const event = new MouseEvent(type, { + button: 0, + buttons: type === 'pointerdown' ? 1 : 0, + clientX: x, + clientY: y, + ...modifiers + }) + Object.defineProperty(event, 'isPrimary', { value: true }) + Object.defineProperty(event, 'pointerId', { value: 1 }) + return event as PointerEvent +} + +function click( + canvas: LGraphCanvas, + x: number, + y: number, + modifiers: Modifiers = {} +) { + canvas.visible_nodes = [...canvas.graph!.nodes] + canvas.processMouseDown(pointerEvent('pointerdown', x, y, modifiers)) + canvas.processMouseUp(pointerEvent('pointerup', x, y, modifiers)) +} + +function marquee( + canvas: LGraphCanvas, + from: [number, number], + to: [number, number], + modifiers: Modifiers +) { + const initialSelection = new Set(canvas.selectedItems) + const dragRect: Rect = [from[0], from[1], to[0] - from[0], to[1] - from[1]] + const event = { + canvasX: to[0], + canvasY: to[1], + ...modifiers + } as CanvasPointerEvent + if (canvas.liveSelection) { + canvas['handleLiveSelect'](event, dragRect, initialSelection) + canvas['finalizeLiveSelect']() + } else { + canvas['_handleMultiSelect'](event, dragRect) + } +} + +function keyEvent(type: 'keydown' | 'keyup', key: string): KeyboardEvent { + const event = new KeyboardEvent(type, { key }) + Object.defineProperty(event, 'target', { value: { localName: 'div' } }) + return event +} + +function selectedTitles(canvas: LGraphCanvas): string[] { + return [...canvas.selectedItems] + .map((item) => ('title' in item ? String(item.title) : String(item))) + .sort() +} + +describe('LGraphCanvas selection', () => { + let graph: LGraph + let canvas: LGraphCanvas + let a: LGraphNode + let b: LGraphNode + let onSelectionChange: NonNullable + + beforeEach(() => { + LiteGraph.vueNodesMode = false + graph = new LGraph() + canvas = createCanvas(graph) + a = addNode(graph, 'A', 20, 40) + b = addNode(graph, 'B', 300, 40) + onSelectionChange = vi.fn() + canvas.onSelectionChange = onSelectionChange + }) + + describe('click', () => { + it.for<{ name: string; modifiers: Modifiers; expected: string[] }>([ + { name: 'plain click replaces', modifiers: {}, expected: ['B'] }, + { + name: 'shift click adds', + modifiers: { shiftKey: true }, + expected: ['A', 'B'] + }, + { + name: 'ctrl click adds', + modifiers: { ctrlKey: true }, + expected: ['A', 'B'] + }, + { + name: 'meta click adds', + modifiers: { metaKey: true }, + expected: ['A', 'B'] + } + ])('$name', ({ modifiers, expected }) => { + click(canvas, 60, 60) + click(canvas, 340, 60, modifiers) + + expect(selectedTitles(canvas)).toEqual(expected) + }) + + it.fails('a replacing click reports one change', () => { + click(canvas, 60, 60) + click(canvas, 340, 60) + + expect(onSelectionChange).toHaveBeenCalledTimes(2) + }) + + it('ctrl click on a selected item removes it', () => { + click(canvas, 60, 60) + click(canvas, 340, 60, { ctrlKey: true }) + click(canvas, 60, 60, { ctrlKey: true }) + + expect(selectedTitles(canvas)).toEqual(['B']) + expect(a.selected).toBe(false) + }) + + it('plain click on empty canvas clears', () => { + click(canvas, 60, 60) + click(canvas, 600, 500) + + expect(canvas.selectedItems.size).toBe(0) + expect(a.selected).toBe(false) + }) + + it.fails('a clearing click reports one change', () => { + click(canvas, 60, 60) + click(canvas, 600, 500) + + expect(onSelectionChange).toHaveBeenCalledTimes(2) + }) + + it('modifier click on empty canvas keeps the selection', () => { + click(canvas, 60, 60) + click(canvas, 600, 500, { shiftKey: true }) + + expect(selectedTitles(canvas)).toEqual(['A']) + }) + + it('click on a group title selects the group only', () => { + const group = addGroup(graph, 'G', [0, 0, 500, 300]) + + click(canvas, 250, 10) + + expect(selectedTitles(canvas)).toEqual(['G']) + expect(group.selected).toBe(true) + expect(a.selected).toBeFalsy() + }) + + it('click on a node inside a group selects the node only', () => { + addGroup(graph, 'G', [0, 0, 500, 300]) + + click(canvas, 60, 60) + + expect(selectedTitles(canvas)).toEqual(['A']) + }) + + it('keeps item flags, selected_nodes and highlighted links aligned', () => { + a.addOutput('out', 'number') + b.addInput('in', 'number') + a.connect(0, b, 0) + + click(canvas, 60, 60) + click(canvas, 340, 60, { shiftKey: true }) + expect(Object.keys(canvas.highlighted_links)).toHaveLength(1) + expect(Object.keys(canvas.selected_nodes)).toHaveLength(2) + + click(canvas, 600, 500) + expect(Object.keys(canvas.highlighted_links)).toHaveLength(0) + expect(Object.keys(canvas.selected_nodes)).toHaveLength(0) + expect(a.selected).toBe(false) + expect(b.selected).toBe(false) + }) + }) + + describe('programmatic API', () => { + it.fails('select() reports the change', () => { + canvas.select(a) + + expect(onSelectionChange).toHaveBeenCalledTimes(1) + }) + + it.fails('deselect() reports the change', () => { + canvas.select(a) + canvas.deselect(a) + + expect(onSelectionChange).toHaveBeenCalledTimes(2) + }) + + it('deselectAll() reports only when something was selected', () => { + canvas.deselectAll() + expect(onSelectionChange).not.toHaveBeenCalled() + + canvas.select(a) + canvas.deselectAll() + expect(onSelectionChange).toHaveBeenCalledTimes(1) + expect(a.selected).toBe(false) + }) + }) + + describe('marquee', () => { + beforeEach(() => { + addNode(graph, 'C', 300, 300) + }) + + describe.for([{ liveSelection: false }, { liveSelection: true }])( + 'liveSelection=$liveSelection', + ({ liveSelection }) => { + beforeEach(() => { + canvas.liveSelection = liveSelection + }) + + it('plain marquee replaces the selection', () => { + click(canvas, 60, 60) + + marquee(canvas, [250, 0], [450, 400], {}) + + expect(selectedTitles(canvas)).toEqual(['B', 'C']) + expect(a.selected).toBe(false) + }) + + it('shift marquee adds to the selection', () => { + click(canvas, 60, 60) + + marquee(canvas, [250, 0], [450, 400], { shiftKey: true }) + + expect(selectedTitles(canvas)).toEqual(['A', 'B', 'C']) + }) + + it('alt marquee removes from the selection', () => { + click(canvas, 60, 60) + click(canvas, 340, 60, { shiftKey: true }) + click(canvas, 340, 320, { shiftKey: true }) + + marquee(canvas, [250, 0], [450, 100], { altKey: true }) + + expect(selectedTitles(canvas)).toEqual(['A', 'C']) + expect(b.selected).toBe(false) + }) + } + ) + + it.fails('shift+alt marquee resolves the same way in both modes', () => { + click(canvas, 60, 60) + canvas.liveSelection = false + marquee(canvas, [250, 0], [450, 400], { shiftKey: true, altKey: true }) + const classic = selectedTitles(canvas) + + click(canvas, 60, 60) + canvas.liveSelection = true + marquee(canvas, [250, 0], [450, 400], { shiftKey: true, altKey: true }) + + expect(selectedTitles(canvas)).toEqual(classic) + }) + + it.fails('live marquee reports one change', () => { + canvas.liveSelection = true + + marquee(canvas, [250, 0], [450, 400], {}) + + expect(onSelectionChange).toHaveBeenCalledTimes(1) + }) + }) + + describe('groups with groupSelectChildren', () => { + let group: LGraphGroup + + beforeEach(() => { + canvas.groupSelectChildren = true + group = addGroup(graph, 'G', [0, 0, 500, 300]) + group.recomputeInsideNodes() + }) + + it('selecting the group selects its children', () => { + click(canvas, 250, 10) + + expect(selectedTitles(canvas)).toEqual(['A', 'B', 'G']) + }) + + it.fails('nested groups receive onSelected', () => { + const inner = addGroup(graph, 'Inner', [10, 30, 200, 200]) + inner.recomputeInsideNodes() + group.recomputeInsideNodes() + const onSelected = vi.fn() + Object.assign(inner, { onSelected }) + + canvas.select(group) + + expect(inner.selected).toBe(true) + expect(onSelected).toHaveBeenCalledTimes(1) + }) + }) + + describe('space bar pan override', () => { + it.for([{ readOnly: true }, { readOnly: false }])( + 'restores read_only=$readOnly after release', + ({ readOnly }) => { + canvas.read_only = readOnly + + canvas.processKey(keyEvent('keydown', ' ')) + expect(canvas.read_only).toBe(true) + + canvas.processKey(keyEvent('keyup', ' ')) + expect(canvas.read_only).toBe(readOnly) + } + ) + + it('ignores a release without a matching press', () => { + canvas.read_only = true + + canvas.processKey(keyEvent('keyup', ' ')) + + expect(canvas.read_only).toBe(true) + }) + + it('clears held state when the graph is detached before release', () => { + canvas.processKey(keyEvent('keydown', ' ')) + graph.detachCanvas(canvas) + + canvas.processKey(keyEvent('keyup', ' ')) + expect(canvas.read_only).toBe(false) + + new LGraph().attachCanvas(canvas) + canvas.read_only = true + canvas.processKey(keyEvent('keydown', ' ')) + canvas.processKey(keyEvent('keyup', ' ')) + + expect(canvas.read_only).toBe(true) + }) + }) +}) diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index 379768584d7..1597ad02e5d 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -416,9 +416,8 @@ export class LGraphCanvas implements CustomEventDispatcher this._setCursor(cursor) } - // Whether the canvas was previously being dragged prior to pressing space key. - // null if space key is not pressed. - private _previously_dragging_canvas: boolean | null = null + private _spaceKeyHeld: { draggingCanvas: boolean; readOnly: boolean } | null = + null // #region Legacy accessors /** @deprecated @inheritdoc {@link LGraphCanvasState.readOnly} */ @@ -595,7 +594,6 @@ export class LGraphCanvas implements CustomEventDispatcher pause_rendering: boolean clear_background: boolean clear_background_color: string - render_only_selected: boolean show_info: boolean /** Additional text appended to the canvas info overlay (rendered by {@link renderInfo}). */ info_text: string | undefined @@ -979,7 +977,6 @@ export class LGraphCanvas implements CustomEventDispatcher this.clear_background = true this.clear_background_color = '#222' - this.render_only_selected = true this.show_info = true this.allow_dragcanvas = true this.allow_dragnodes = true @@ -3933,6 +3930,22 @@ export class LGraphCanvas implements CustomEventDispatcher processKey(e: KeyboardEvent): void { this._shiftDown = e.shiftKey + if (e.type == 'keyup' && e.key === ' ') { + const held = this._spaceKeyHeld + this._spaceKeyHeld = null + if (held) { + this.read_only = held.readOnly + this.dragging_canvas = held.draggingCanvas && this.pointer.isDown + if ( + this.pointer.isDown && + (this.isDragging || this.linkConnector.isConnecting) + ) { + this._autoPan?.updatePointer(this.mouse[0], this.mouse[1]) + this._autoPan?.start() + } + } + } + const { graph } = this if (!graph) return @@ -3944,11 +3957,12 @@ export class LGraphCanvas implements CustomEventDispatcher // TODO: Switch if (e.key === ' ') { // space + this._spaceKeyHeld ??= { + draggingCanvas: this.dragging_canvas, + readOnly: this.read_only + } this.read_only = true this._autoPan?.stop() - if (this._previously_dragging_canvas === null) { - this._previously_dragging_canvas = this.dragging_canvas - } this.dragging_canvas = this.pointer.isDown || !!this.linkConnector.renderLinks.length block_default = true @@ -3969,21 +3983,6 @@ export class LGraphCanvas implements CustomEventDispatcher node.onKeyDown?.(e) } } else if (e.type == 'keyup') { - if (e.key === ' ') { - // space - this.read_only = false - this.dragging_canvas = - (this._previously_dragging_canvas ?? false) && this.pointer.isDown - this._previously_dragging_canvas = null - if ( - this.pointer.isDown && - (this.isDragging || this.linkConnector.isConnecting) - ) { - this._autoPan?.updatePointer(this.mouse[0], this.mouse[1]) - this._autoPan?.start() - } - } - for (const node of Object.values(this.selected_nodes)) { node.onKeyUp?.(e) } diff --git a/src/renderer/core/canvas/canvasStore.ts b/src/renderer/core/canvas/canvasStore.ts index cc842332320..323f979d8ae 100644 --- a/src/renderer/core/canvas/canvasStore.ts +++ b/src/renderer/core/canvas/canvasStore.ts @@ -18,7 +18,7 @@ import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMuta import { LayoutSource } from '@/renderer/core/layout/types' import { app } from '@/scripts/app' import type { NodeId } from '@/types/nodeId' -import { isLGraphGroup, isLGraphNode, isReroute } from '@/utils/litegraphUtil' +import { isLGraphNode } from '@/utils/litegraphUtil' function currentTransform(): LGraphCanvas['ds'] | null { return app.canvas.ds @@ -98,10 +98,6 @@ export const useCanvasStore = defineStore('canvas', () => { } } - const nodeSelected = computed(() => selectedItems.value.some(isLGraphNode)) - const groupSelected = computed(() => selectedItems.value.some(isLGraphGroup)) - const rerouteSelected = computed(() => selectedItems.value.some(isReroute)) - const getCanvas = () => { if (!canvas.value) throw new Error('getCanvas: canvas is null') return canvas.value @@ -206,9 +202,6 @@ export const useCanvasStore = defineStore('canvas', () => { canvas, selectedItems, selectedNodeIds, - nodeSelected, - groupSelected, - rerouteSelected, appScalePercentage, linearMode, isReadOnly, diff --git a/src/utils/litegraphUtil.ts b/src/utils/litegraphUtil.ts index 1b10a7b685b..c4ec29f9693 100644 --- a/src/utils/litegraphUtil.ts +++ b/src/utils/litegraphUtil.ts @@ -7,7 +7,6 @@ import { LGraphGroup, LGraphNode, LiteGraph, - Reroute, isColorable } from '@/lib/litegraph/src/litegraph' import type { @@ -153,10 +152,6 @@ export const isLGraphGroup = (item: unknown): item is LGraphGroup => { return item instanceof LGraphGroup } -export const isReroute = (item: unknown): item is Reroute => { - return item instanceof Reroute -} - /** * Get the color option of all canvas items if they are all the same. * @param items - The items to get the color option of.