diff --git a/browser_tests/tests/canvasSettings.spec.ts b/browser_tests/tests/canvasSettings.spec.ts index 366472d07f8..ddf298f6e24 100644 --- a/browser_tests/tests/canvasSettings.spec.ts +++ b/browser_tests/tests/canvasSettings.spec.ts @@ -367,7 +367,7 @@ test.describe('Canvas settings', { tag: '@canvas' }, () => { /** * Press left-mouse at canvas-relative `pos`, hold for `holdMs` (0 = no * hold), nudge by `(dx, dy)` absolute pixels, then release. Spec-local - * because it exists only to probe the CanvasPointer timing thresholds. + * because it exists only to probe the CanvasPointer gesture thresholds. */ const holdDragAt = async ( comfyPage: ComfyPage, @@ -422,54 +422,31 @@ test.describe('Canvas settings', { tag: '@canvas' }, () => { }) }) - test('ClickBufferTime governs the click-vs-drag time threshold', async ({ + test('ClickBufferTime does not promote movement within drift', async ({ comfyPage }) => { - // Keep drift generous so only elapsed time distinguishes click vs drag. - await comfyPage.settings.setSetting('Comfy.Pointer.ClickDrift', 20) const node = ( await comfyPage.nodeOps.getNodeRefsByType('CLIPTextEncode') )[0] + await comfyPage.settings.setSetting('Comfy.Pointer.ClickDrift', 6) + await comfyPage.settings.setSetting('Comfy.Pointer.ClickBufferTime', 0) const titlePos = await node.getTitlePosition() - const NUDGE = 2 - const HOLD_MS = 250 + const before = await node.getPosition() - await test.step(`Buffer=2000ms (hold=${HOLD_MS}ms within buffer) → click, node stays put`, async () => { - await comfyPage.settings.setSetting( - 'Comfy.Pointer.ClickBufferTime', - 2000 - ) - const before = await node.getPosition() - await holdDragAt(comfyPage, titlePos, { - dx: NUDGE, - dy: NUDGE, - holdMs: HOLD_MS - }) - const after = await node.getPosition() - expect(after.x).toBeCloseTo(before.x, 0) - expect(after.y).toBeCloseTo(before.y, 0) + await holdDragAt(comfyPage, titlePos, { + dx: 2, + dy: 0, + holdMs: 250 }) - await test.step(`Buffer=50ms (hold=${HOLD_MS}ms exceeds buffer) → drag, node moves`, async () => { - await comfyPage.settings.setSetting('Comfy.Pointer.ClickBufferTime', 50) - const before = await node.getPosition() - await holdDragAt(comfyPage, titlePos, { - dx: NUDGE, - dy: NUDGE, - holdMs: HOLD_MS - }) - const after = await node.getPosition() - expect( - Math.abs(after.x - before.x) + Math.abs(after.y - before.y) - ).toBeGreaterThan(0) - }) + const after = await node.getPosition() + expect(after.x).toBeCloseTo(before.x, 0) + expect(after.y).toBeCloseTo(before.y, 0) }) test('ClickDrift governs the click-vs-drag distance threshold', async ({ comfyPage }) => { - // Keep buffer generous so only drift distance matters. - await comfyPage.settings.setSetting('Comfy.Pointer.ClickBufferTime', 2000) const node = ( await comfyPage.nodeOps.getNodeRefsByType('CLIPTextEncode') )[0] diff --git a/browser_tests/tests/interaction.spec.ts b/browser_tests/tests/interaction.spec.ts index 93245f643e1..9d038b00e28 100644 --- a/browser_tests/tests/interaction.spec.ts +++ b/browser_tests/tests/interaction.spec.ts @@ -465,6 +465,7 @@ test.describe('Node Interaction', () => { // getNodeRefsByType order is non-deterministic, so identify by proximity. const nodes = await comfyPage.nodeOps.getNodeRefsByType('CLIPTextEncode') const togglerPos = DefaultGraphPositions.textEncodeNodeToggler + await comfyPage.settings.setSetting('Comfy.Pointer.DoubleClickTime', 0) let targetNode = nodes[0] let minDist = Infinity for (const n of nodes) { @@ -484,17 +485,6 @@ test.describe('Node Interaction', () => { await expect(comfyPage.canvas).toHaveScreenshot( 'text-encode-toggled-off.png' ) - // Wait for the double-click window (300ms) to expire so the next - // click at the same position isn't interpreted as a double-click. - await expect - .poll(() => - comfyPage.page.evaluate(() => { - const pointer = window.app!.canvas.pointer - if (!pointer.eLastDown) return true - return performance.now() - pointer.eLastDown.timeStamp > 300 - }) - ) - .toBe(true) await comfyPage.canvas.click({ position: togglerPos }) diff --git a/browser_tests/tests/vueNodes/interactions/canvas/pointerGestures.spec.ts b/browser_tests/tests/vueNodes/interactions/canvas/pointerGestures.spec.ts index a390addff04..51e7c960b13 100644 --- a/browser_tests/tests/vueNodes/interactions/canvas/pointerGestures.spec.ts +++ b/browser_tests/tests/vueNodes/interactions/canvas/pointerGestures.spec.ts @@ -46,10 +46,6 @@ test.describe( await expect(comfyPage.selectionToolbox).toBeVisible() await expect(comfyPage.vueNodes.selectedNodes).toHaveCount(0) - test.fail( - true, - 'FE-2040 / time-based promotion moves the group after 150 ms and 1 px of drift' - ) await expect.poll(() => groupBounds(comfyPage, 'Pair')).toEqual(before) }) diff --git a/docs/adr/CANVAS-GESTURE-0029-pointer-gesture-state-machine.md b/docs/adr/CANVAS-GESTURE-0029-pointer-gesture-state-machine.md index 1d4fa8a6135..c51b4ff7f61 100644 --- a/docs/adr/CANVAS-GESTURE-0029-pointer-gesture-state-machine.md +++ b/docs/adr/CANVAS-GESTURE-0029-pointer-gesture-state-machine.md @@ -93,8 +93,12 @@ the interpretation of a gesture, and both renderers feed it. - `idle` + `down` → `pressed`. Emits press-time commands such as `bringToFront` and sticky selection for the right button. + - `pressed` + `move` within the drift threshold → `pressed`. Emits + `movePress`, which only the `CanvasPointer` adapter consumes (see + Compatibility requirements). The Vue adapter ignores it. - `pressed` + `move` beyond the drift threshold → `dragging`. Emits - `startDrag` with the drag kind derived from the target and policy. + `startDrag` with the drag kind derived from the target and policy, + followed by `moveDrag` for the same event. - `pressed` + `up` beyond the drift threshold → `idle`. Emits `startDrag` followed by `endDrag`, even if no `move` arrived. It emits no click command and does not replace the previous-click record. @@ -111,19 +115,19 @@ the interpretation of a gesture, and both renderers feed it. and any drop target. - `pressed` + `cancel` → `idle`. Preserves the previous-click record and emits no command. - - `dragging` + `cancel` → `idle`. Emits `cancelDrag`, which the - interpreter uses to release the drag, restore canvas flags, and release - pointer capture. This transition clears the previous-click record. + - `dragging` + `cancel` → `idle`. Preserves the previous-click record and + emits no command. During migration, `CanvasPointer.reset()` runs `finally` + and releases pointer capture. - Any other pair returns the state unchanged with no commands. 2. **Commands are the only output.** The reducer returns plain, serializable - command values. They include `select`, `startDrag`, `moveDrag`, `endDrag`, - `openContextMenu`, `bringToFront`, and `marquee`. An interpreter applies them - to `selectionStore`, `layoutStore`, and canvas services. Nothing else writes - selection or drag state during a gesture. Existing node hooks and extension - callbacks are outward effects emitted by the interpreter in the required - order. This follows the command and effect distinction in - [State, effects and workflows](../guidance/state-and-effects.md). + command values. They include `select`, `startDrag`, `movePress`, `moveDrag`, + `endDrag`, `openContextMenu`, `bringToFront`, and `marquee`. An interpreter + applies them to `selectionStore`, `layoutStore`, and canvas services. Nothing + else writes selection or drag state during a gesture. Existing node hooks and + extension callbacks are outward effects emitted by the interpreter in the + required order. This follows the command and effect distinction in [State, + effects and workflows](../guidance/state-and-effects.md). 3. **Hit-test once per press.** The `down` event carries a `PointerTarget` union (`canvas`, `node`, `nodeTitle`, `widget`, `slot`, `group`, `groupTitle`, `reroute`, `link`, `linkCenter`, `resizeHandle`, and @@ -169,12 +173,20 @@ the interpretation of a gesture, and both renderers feed it. the first `moveDrag`, and no `moveDrag` fires inside the click threshold. `CanvasPointer` currently invokes `onDrag` before `onDragStart` on the promoting move and invokes `onDrag` for movement inside the threshold. - Characterization tests cover every current `onDrag` assignment and record - the reduced callback count. + Legacy `onDrag` consumers such as number-widget drag adjustment depend on + that in-threshold movement, so the `CanvasPointer` adapter forwards + `movePress` to `onDrag` while the Vue adapter ignores it. A number-widget + press that moves within the drift threshold can therefore adjust the value + and then open its prompt on release. Characterization + tests cover every current `onDrag` assignment and record the callback count. - The adapter that accepts `down` owns the gesture until `up` or `cancel`. Renderer, mode, and feature-flag changes take effect only after the gesture - returns to `idle`. Teardown, lost pointer capture, blur, and visibility loss - dispatch `cancel` to the current owner before ownership ends. + returns to `idle`. Teardown and lost pointer capture dispatch `cancel` to + the current owner before ownership ends. The browser releases capture + immediately after `pointerup` or `pointercancel`, so `lostpointercapture` + reports interruptions that deliver neither event. Window blur and + visibility listeners are added only if a browser is shown to end a gesture + without firing `lostpointercapture`. - `CanvasPointer` remains exported with its current callback surface until the corpus check shows no extension assigns any of `pointer.onClick`, `pointer.onDoubleClick`, `pointer.onDragStart`, `pointer.onDrag`, diff --git a/src/lib/litegraph/API.md b/src/lib/litegraph/API.md index d763c611c30..31adec75aca 100644 --- a/src/lib/litegraph/API.md +++ b/src/lib/litegraph/API.md @@ -40,9 +40,8 @@ CanvasPointer replaces much of the original pointer handling code. It provides a ### Click "drift" -A small amount of buffering is performed between down/up events to prevent accidental micro-drag events. If either of the two controls are exceeded, the event will be considered a drag event, not a click. +A small amount of movement is tolerated between down/up events to prevent accidental micro-drag events. Once the pointer travels further than the limit, the event is considered a drag event, not a click. Time does not affect the decision. -- `bufferTime` is the maximum time that tiny movements can be ignored (Default: 32ms) - `maxClickDrift` controls how far a click can drift from its down event before it is considered a drag (Default: 6) ### Double-click @@ -57,7 +56,6 @@ When double clicking, the double click callback is executed shortly after one no All above configuration is via class static. ```ts -CanvasPointer.bufferTime = 32 CanvasPointer.maxClickDrift = 6 CanvasPointer.doubleClickTime = 300 ``` diff --git a/src/lib/litegraph/src/CanvasPointer.ts b/src/lib/litegraph/src/CanvasPointer.ts index f296756f62a..af50dac4e2d 100644 --- a/src/lib/litegraph/src/CanvasPointer.ts +++ b/src/lib/litegraph/src/CanvasPointer.ts @@ -1,7 +1,17 @@ +import type { + GestureEffect, + GestureEvent, + GesturePoint, + GestureState +} from './canvas/reduceGesture' +import { idleGesture, reduceGesture } from './canvas/reduceGesture' import type { CompassCorners } from './interfaces' -import { dist2 } from './measure' import type { CanvasPointerEvent } from './types/events' +function positionOf(e: PointerEvent): GesturePoint { + return { x: e.clientX, y: e.clientY } +} + /** * Allows click and drag actions to be declared ahead of time during a pointerdown event. * @@ -23,36 +33,11 @@ import type { CanvasPointerEvent } from './types/events' * - {@link LGraphCanvas.processMouseUp} */ export class CanvasPointer { - /** - * Maximum time in milliseconds to ignore click drift. - * - * This is the upper bound on how long after pointerdown the system will wait - * before deciding "this is a drag, not a click" when the pointer hasn't moved - * past {@link maxClickDrift}. Keep this short — drags should feel instant. - * Disambiguation between click and drag is primarily handled by distance - * ({@link maxClickDrift}); this time threshold only matters when the user - * holds the pointer still then releases. ~2 frames at 60fps is plenty. - * - * Overridden at runtime by the `Comfy.Pointer.ClickBufferTime` user setting. - */ - static bufferTime = 32 - /** Maximum gap between pointerup and pointerdown events to be considered as a double click */ static doubleClickTime = 300 /** Maximum offset from click location */ - static get maxClickDrift() { - return this._maxClickDrift - } - - static set maxClickDrift(value) { - this._maxClickDrift = value - this._maxClickDrift2 = value * value - } - - private static _maxClickDrift = 6 - /** {@link maxClickDrift} squared. Used to calculate click drift without `sqrt`. */ - private static _maxClickDrift2 = this._maxClickDrift ** 2 + static maxClickDrift = 6 /** Assume that "wheel" events with both deltaX and deltaY less than this value are trackpad gestures. */ static trackpadThreshold = 60 @@ -75,11 +60,12 @@ export class CanvasPointer { /** Pointer ID used by drag capture. */ pointerId?: number - /** Set to true when if the pointer moves far enough after a down event, before the corresponding up event is fired. */ - dragStarted: boolean = false + /** `true` once the pointer has moved far enough after a down event to be a drag, until the corresponding up event. */ + get dragStarted(): boolean { + return this.state.phase === 'dragging' + } - /** The {@link eUp} from the last successful click */ - eLastDown?: CanvasPointerEvent + private state: GestureState = idleGesture /** Used downstream for touch event support. */ isDouble: boolean = false @@ -177,6 +163,13 @@ export class CanvasPointer { private _finally?: () => unknown + private captureElement?: Element + + private readonly onLostPointerCapture = (e: Event) => { + if (e instanceof PointerEvent && e.pointerId === this.pointerId) + this.reset() + } + constructor(element: Element) { this.element = element } @@ -189,7 +182,16 @@ export class CanvasPointer { this.reset() this.eDown = e this.pointerId = e.pointerId - this.element.setPointerCapture(e.pointerId) + this.captureElement = this.element + this.captureElement.addEventListener( + 'lostpointercapture', + this.onLostPointerCapture + ) + this.captureElement.setPointerCapture(e.pointerId) + this.dispatch( + { type: 'down', position: positionOf(e), timeStamp: e.timeStamp }, + e + ) } /** @@ -208,98 +210,67 @@ export class CanvasPointer { // Primary button released - treat as pointerup. if (!(e.buttons & eDown.buttons)) { - this._completeClick(e) + this.eUp = e + this.dispatch({ type: 'up', position: positionOf(e) }, e) this.reset() return } this.eMove = e - this.onDrag?.(e) - - // Dragging, but no callback to run - if (this.dragStarted) return - - const longerThanBufferTime = - e.timeStamp - eDown.timeStamp > CanvasPointer.bufferTime - if (longerThanBufferTime || !this._hasSamePosition(e, eDown)) { - this._setDragStarted(e) - } + this.dispatch({ type: 'move', position: positionOf(e) }, e) } /** * Callback for `pointerup` events. To be used as the event handler (or called by it). * @param e The `pointerup` event + * @returns `true` if the gesture ended as a click rather than a drag */ up(e: CanvasPointerEvent): boolean { if (e.button !== this.eDown?.button) return false - this._completeClick(e) - const { dragStarted } = this + this.eUp = e + const effects = this.dispatch({ type: 'up', position: positionOf(e) }, e) this.reset() - return !dragStarted + return effects.includes('click') || effects.includes('doubleClick') } - private _completeClick(e: CanvasPointerEvent): void { - const { eDown } = this - if (!eDown) return - - this.eUp = e - - if (this.dragStarted) { - // A move event already started drag - this.onDragEnd?.(e) - } else if (!this._hasSamePosition(e, eDown)) { - // Teleport without a move event (e.g. tab out, move, tab back) - this._setDragStarted() - this.onDragEnd?.(e) - } else if (this.onDoubleClick && this._isDoubleClick()) { - // Double-click event - this.onDoubleClick(e) - this.eLastDown = undefined - } else { - // Normal click event - this.onClick?.(e) - this.eLastDown = eDown + private dispatch( + event: GestureEvent, + e: CanvasPointerEvent + ): GestureEffect[] { + const { state, effects } = reduceGesture(this.state, event, { + clickDrift: CanvasPointer.maxClickDrift, + doubleClickTime: CanvasPointer.doubleClickTime + }) + this.state = state + const eMove = event.type === 'move' ? e : undefined + const handlers: Record void> = { + click: () => this.onClick?.(e), + doubleClick: () => this.runDoubleClick(e), + startDrag: () => { + this.onDragStart?.(this, eMove) + delete this.onDragStart + }, + movePress: () => this.onDrag?.(e), + moveDrag: () => this.onDrag?.(e), + endDrag: () => this.onDragEnd?.(e) } + for (const effect of effects) handlers[effect]() + return effects } - /** - * Checks if two events occurred near each other - not further apart than the maximum click drift. - * @param a The first event to compare - * @param b The second event to compare - * @param tolerance2 The maximum distance (squared) before the positions are considered different - * @returns `true` if the two events were no more than {@link maxClickDrift} apart, otherwise `false` - */ - private _hasSamePosition( - a: PointerEvent, - b: PointerEvent, - tolerance2 = CanvasPointer._maxClickDrift2 - ): boolean { - const drift = dist2(a.clientX, a.clientY, b.clientX, b.clientY) - return drift <= tolerance2 - } - - /** - * Checks whether the pointer is currently past the max click drift threshold. - * @returns `true` if the latest pointer event is past the the click drift threshold - */ - private _isDoubleClick(): boolean { - const { eDown, eLastDown } = this - if (!eDown || !eLastDown) return false - - // Use thrice the drift distance for double-click gap - const tolerance2 = (3 * CanvasPointer._maxClickDrift) ** 2 - const diff = eDown.timeStamp - eLastDown.timeStamp - return ( - diff > 0 && - diff < CanvasPointer.doubleClickTime && - this._hasSamePosition(eDown, eLastDown, tolerance2) - ) - } - - private _setDragStarted(eMove?: CanvasPointerEvent): void { - this.dragStarted = true - this.onDragStart?.(this, eMove) - delete this.onDragStart + private runDoubleClick(e: CanvasPointerEvent): void { + if (this.onDoubleClick) { + this.onDoubleClick(e) + return + } + this.onClick?.(e) + this.state = { + phase: 'idle', + lastClick: { + position: positionOf(this.eDown ?? e), + timeStamp: this.eDown?.timeStamp ?? e.timeStamp + } + } } /** @@ -484,6 +455,13 @@ export class CanvasPointer { * state is cleared. */ reset(): void { + this.captureElement?.removeEventListener( + 'lostpointercapture', + this.onLostPointerCapture + ) + this.captureElement = undefined + if (this.eDown) this.dispatch({ type: 'cancel' }, this.eDown) + // The setter executes the callback before clearing it this.finally = undefined delete this.onClick @@ -494,7 +472,6 @@ export class CanvasPointer { this.isDown = false this.isDouble = false - this.dragStarted = false this.resizeDirection = undefined if (this.clearEventsOnReset) { diff --git a/src/lib/litegraph/src/LGraphCanvas.gesture.test.ts b/src/lib/litegraph/src/LGraphCanvas.gesture.test.ts index 8170c8c3c9c..98bf39fca74 100644 --- a/src/lib/litegraph/src/LGraphCanvas.gesture.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.gesture.test.ts @@ -178,6 +178,66 @@ describe('CanvasPointer lifecycle callbacks', () => { expect(onDragEnd).toHaveBeenCalledWith(up) expect(finallyCallback).toHaveBeenCalledOnce() }) + + it('cancels an active drag when the element loses pointer capture', () => { + const element = document.createElement('canvas') + const pointer = new CanvasPointer(element) + const onDragEnd = vi.fn() + const finallyCallback = vi.fn() + + pointer.down(pointerEvent('pointerdown', 10, 20)) + pointer.onDragEnd = onDragEnd + pointer.finally = finallyCallback + pointer.move(pointerEvent('pointermove', 30, 40)) + element.dispatchEvent( + new PointerEvent('lostpointercapture', { pointerId: 1 }) + ) + + expect(pointer.dragStarted).toBe(false) + expect(pointer.eDown).toBeUndefined() + expect(onDragEnd).not.toHaveBeenCalled() + expect(finallyCallback).toHaveBeenCalledOnce() + }) + + it('ignores lost capture for a different pointer', () => { + const element = document.createElement('canvas') + const pointer = new CanvasPointer(element) + const finallyCallback = vi.fn() + + pointer.down(pointerEvent('pointerdown', 10, 20)) + pointer.finally = finallyCallback + element.dispatchEvent( + new PointerEvent('lostpointercapture', { pointerId: 2 }) + ) + + expect(finallyCallback).not.toHaveBeenCalled() + }) + + it('treats callback-less double clicks as normal clicks', () => { + const pointer = new CanvasPointer(document.createElement('canvas')) + const onClick = vi.fn() + + for (const timeStamp of [100, 200, 300]) { + pointer.down(pointerEvent('pointerdown', 10, 20, { timeStamp })) + pointer.onClick = onClick + pointer.up( + pointerEvent('pointerup', 10, 20, { timeStamp: timeStamp + 1 }) + ) + } + + expect(onClick).toHaveBeenCalledTimes(3) + }) + + it('records pointermove as eUp when it detects a released button', () => { + const pointer = new CanvasPointer(document.createElement('canvas')) + pointer.clearEventsOnReset = false + pointer.down(pointerEvent('pointerdown', 10, 20)) + const releasedMove = pointerEvent('pointermove', 30, 40, { buttons: 2 }) + + pointer.move(releasedMove) + + expect(pointer.eUp).toBe(releasedMove) + }) }) describe('LGraphCanvas pointer gestures', () => { @@ -277,9 +337,9 @@ describe('LGraphCanvas pointer gestures', () => { expect(log).not.toContain('canvas.onNodeMoved') }) - it.fails('slow movement within the drift threshold stays a click', () => { + it('slow movement within the drift threshold stays a click', () => { gesture.press(A_BODY) - gesture.move(shifted(A_BODY, NEAR), {}, CanvasPointer.bufferTime + 100) + gesture.move(shifted(A_BODY, NEAR), {}, 500) gesture.release(shifted(A_BODY, NEAR)) expect({ @@ -288,15 +348,6 @@ describe('LGraphCanvas pointer gestures', () => { }).toEqual({ moved: false, position: [20, 40] }) }) - it('records the current slow movement promotion', () => { - gesture.press(A_BODY) - gesture.move(shifted(A_BODY, NEAR), {}, CanvasPointer.bufferTime + 100) - gesture.release(shifted(A_BODY, NEAR)) - - expect(posOf(a)).toEqual([21, 40]) - expect(log).toContain('canvas.onNodeMoved') - }) - it('currently emits onNodeMoved for a far release that did not move the node', () => { gesture.press(A_BODY) gesture.release(shifted(A_BODY, FAR)) diff --git a/src/lib/litegraph/src/__fixtures__/canvasHarness.ts b/src/lib/litegraph/src/__fixtures__/canvasHarness.ts index 556ff5a5107..e4c36efd318 100644 --- a/src/lib/litegraph/src/__fixtures__/canvasHarness.ts +++ b/src/lib/litegraph/src/__fixtures__/canvasHarness.ts @@ -14,6 +14,7 @@ export type Modifiers = Partial< export type PointerEventOptions = Modifiers & { button?: number + buttons?: number timeStamp?: number } @@ -49,12 +50,12 @@ export function pointerEvent( type: PointerEventType, x: number, y: number, - { button = 0, timeStamp, ...modifiers }: PointerEventOptions = {} + { button = 0, buttons, timeStamp, ...modifiers }: PointerEventOptions = {} ): CanvasPointerEvent { const pressed = type === 'pointerdown' || type === 'pointermove' const event = new PointerEvent(type, { button, - buttons: pressed ? (button === 2 ? 2 : 1) : 0, + buttons: buttons ?? (pressed ? (button === 2 ? 2 : 1) : 0), clientX: x, clientY: y, isPrimary: true, diff --git a/src/lib/litegraph/src/canvas/reduceGesture.test.ts b/src/lib/litegraph/src/canvas/reduceGesture.test.ts new file mode 100644 index 00000000000..5fd41f4f544 --- /dev/null +++ b/src/lib/litegraph/src/canvas/reduceGesture.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it } from 'vitest' + +import type { + GestureEvent, + GestureState +} from '@/lib/litegraph/src/canvas/reduceGesture' +import { + idleGesture, + reduceGesture +} from '@/lib/litegraph/src/canvas/reduceGesture' + +const policy = { + clickDrift: 6, + doubleClickTime: 300 +} + +const origin = { x: 100, y: 100 } +const nearby = { x: 104, y: 103 } +const far = { x: 120, y: 130 } + +function down(timeStamp: number): GestureEvent { + return { type: 'down', position: origin, timeStamp } +} + +function run(events: GestureEvent[], from: GestureState = idleGesture) { + const effects: string[] = [] + const state = events.reduce((state, event) => { + const result = reduceGesture(state, event, policy) + effects.push(...result.effects) + return result.state + }, from) + return { state, effects } +} + +describe('reduceGesture', () => { + it('ignores events other than down while idle', () => { + const events: GestureEvent[] = [ + { type: 'move', position: far }, + { type: 'up', position: far }, + { type: 'cancel' } + ] + + expect(run(events)).toEqual({ state: idleGesture, effects: [] }) + }) + + it('release within the drift threshold is a click and is remembered', () => { + const { state, effects } = run([ + down(10), + { type: 'move', position: nearby }, + { type: 'up', position: nearby } + ]) + + expect(effects).toEqual(['movePress', 'click']) + expect(state).toEqual({ + phase: 'idle', + lastClick: { position: origin, timeStamp: 10 } + }) + }) + + it('movement past the drift threshold starts and moves a drag, however slow', () => { + const { state, effects } = run([ + down(0), + { type: 'move', position: nearby }, + { type: 'move', position: far } + ]) + + expect(effects).toEqual(['movePress', 'startDrag', 'moveDrag']) + expect(state.phase).toBe('dragging') + }) + + it('movement within the drift threshold stays pressed', () => { + const { state, effects } = run([ + down(0), + { type: 'move', position: nearby } + ]) + + expect(effects).toEqual(['movePress']) + expect(state.phase).toBe('pressed') + }) + + it('movement exactly at the drift threshold stays pressed', () => { + const boundary = { x: origin.x + policy.clickDrift, y: origin.y } + + const { state, effects } = run([ + down(0), + { type: 'move', position: boundary } + ]) + + expect(effects).toEqual(['movePress']) + expect(state.phase).toBe('pressed') + }) + + it.for([ + { name: 'pressed', before: [down(0)] }, + { name: 'dragging', before: [down(0), { type: 'move', position: far }] } + ] satisfies { name: string; before: GestureEvent[] }[])( + 'ignores a repeated down while $name', + ({ before }) => { + const current = run(before).state + + const result = reduceGesture(current, down(100), policy) + + expect(result).toEqual({ state: current, effects: [] }) + } + ) + + it('release while dragging ends the drag and keeps the click record', () => { + const remembered = run([down(0), { type: 'up', position: origin }]).state + + const { state, effects } = run( + [ + down(1000), + { type: 'move', position: far }, + { type: 'up', position: far } + ], + remembered + ) + + expect(effects).toEqual(['startDrag', 'moveDrag', 'endDrag']) + expect(state).toEqual(remembered) + }) + + it('release far from the press without a move is a drag', () => { + const { effects } = run([down(0), { type: 'up', position: far }]) + + expect(effects).toEqual(['startDrag', 'endDrag']) + }) + + it.for([ + { name: 'inside the window and near', gap: 200, at: nearby, double: true }, + { name: 'inside the window and far', gap: 200, at: far, double: false }, + { name: 'after the window', gap: 300, at: origin, double: false }, + { name: 'with no time between presses', gap: 0, at: origin, double: false }, + { + name: 'with a negative timestamp gap', + gap: -1, + at: origin, + double: false + } + ])('second click $name is double: $double', ({ gap, at, double }) => { + const first = run([down(100), { type: 'up', position: origin }]).state + + const { state, effects } = run( + [ + { type: 'down', position: at, timeStamp: 100 + gap }, + { type: 'up', position: at } + ], + first + ) + + expect(effects).toEqual([double ? 'doubleClick' : 'click']) + expect(state.phase === 'idle' && state.lastClick === undefined).toBe(double) + }) + + it('cancel while pressed emits nothing and keeps the click record', () => { + const remembered = run([down(0), { type: 'up', position: origin }]).state + + const { state, effects } = run([down(50), { type: 'cancel' }], remembered) + + expect(effects).toEqual([]) + expect(state).toEqual(remembered) + }) + + it('cancel while dragging emits nothing and keeps the click record', () => { + const remembered = run([down(0), { type: 'up', position: origin }]).state + + const { state, effects } = run( + [down(50), { type: 'move', position: far }, { type: 'cancel' }], + remembered + ) + + expect(effects).toEqual(['startDrag', 'moveDrag']) + expect(state).toEqual(remembered) + }) + + it('does not mutate frozen state or events', () => { + const state = Object.freeze({ + phase: 'pressed' as const, + origin: Object.freeze({ ...origin }), + timeStamp: 10, + lastClick: Object.freeze({ position: origin, timeStamp: 0 }) + }) + const event = Object.freeze({ + type: 'move' as const, + position: Object.freeze({ ...far }) + }) + + const result = reduceGesture(state, event, policy) + + expect(result).toEqual({ + state: { phase: 'dragging', lastClick: state.lastClick }, + effects: ['startDrag', 'moveDrag'] + }) + expect(state.phase).toBe('pressed') + expect(event.position).toEqual(far) + }) +}) diff --git a/src/lib/litegraph/src/canvas/reduceGesture.ts b/src/lib/litegraph/src/canvas/reduceGesture.ts new file mode 100644 index 00000000000..a1e3cb16a72 --- /dev/null +++ b/src/lib/litegraph/src/canvas/reduceGesture.ts @@ -0,0 +1,180 @@ +import { dist2 } from '@/lib/litegraph/src/measure' + +export interface GesturePoint { + x: number + y: number +} + +interface ClickRecord { + position: GesturePoint + timeStamp: number +} + +export type GestureState = + | { phase: 'idle'; lastClick?: ClickRecord } + | { + phase: 'pressed' + origin: GesturePoint + timeStamp: number + lastClick?: ClickRecord + } + | { phase: 'dragging'; lastClick?: ClickRecord } + +export type GestureEvent = + | { type: 'down'; position: GesturePoint; timeStamp: number } + | { type: 'move'; position: GesturePoint } + | { type: 'up'; position: GesturePoint } + | { type: 'cancel' } + +export type GestureEffect = + | 'click' + | 'doubleClick' + | 'startDrag' + | 'movePress' + | 'moveDrag' + | 'endDrag' + +interface GesturePolicy { + /** Maximum pointer travel, in pixels, for a press to remain a click. */ + clickDrift: number + /** Maximum gap, in milliseconds, between two presses for a double click. */ + doubleClickTime: number +} + +interface GestureResult { + state: GestureState + effects: GestureEffect[] +} + +export const idleGesture: GestureState = { phase: 'idle' } + +function within(a: GesturePoint, b: GesturePoint, distance: number): boolean { + return dist2(a.x, a.y, b.x, b.y) <= distance * distance +} + +function isDoubleClick( + state: Extract, + policy: GesturePolicy +): boolean { + const { lastClick, origin, timeStamp } = state + if (!lastClick) return false + const gap = timeStamp - lastClick.timeStamp + return ( + gap > 0 && + gap < policy.doubleClickTime && + within(origin, lastClick.position, 3 * policy.clickDrift) + ) +} + +function unchanged(state: GestureState): GestureResult { + return { state, effects: [] } +} + +function reduceIdle( + state: Extract, + event: GestureEvent +): GestureResult { + switch (event.type) { + case 'down': + return { + state: { + phase: 'pressed', + origin: event.position, + timeStamp: event.timeStamp, + lastClick: state.lastClick + }, + effects: [] + } + case 'move': + case 'up': + case 'cancel': + return unchanged(state) + default: + event satisfies never + return unchanged(state) + } +} + +function reducePressed( + state: Extract, + event: GestureEvent, + policy: GesturePolicy +): GestureResult { + switch (event.type) { + case 'move': + if (within(event.position, state.origin, policy.clickDrift)) + return { state, effects: ['movePress'] } + return { + state: { phase: 'dragging', lastClick: state.lastClick }, + effects: ['startDrag', 'moveDrag'] + } + case 'up': + if (!within(event.position, state.origin, policy.clickDrift)) + return { + state: { phase: 'idle', lastClick: state.lastClick }, + effects: ['startDrag', 'endDrag'] + } + if (isDoubleClick(state, policy)) + return { state: idleGesture, effects: ['doubleClick'] } + return { + state: { + phase: 'idle', + lastClick: { position: state.origin, timeStamp: state.timeStamp } + }, + effects: ['click'] + } + case 'cancel': + return { + state: { phase: 'idle', lastClick: state.lastClick }, + effects: [] + } + case 'down': + return unchanged(state) + default: + event satisfies never + return unchanged(state) + } +} + +function reduceDragging( + state: Extract, + event: GestureEvent +): GestureResult { + switch (event.type) { + case 'move': + return { state, effects: ['moveDrag'] } + case 'up': + return { + state: { phase: 'idle', lastClick: state.lastClick }, + effects: ['endDrag'] + } + case 'cancel': + return { + state: { phase: 'idle', lastClick: state.lastClick }, + effects: [] + } + case 'down': + return unchanged(state) + default: + event satisfies never + return unchanged(state) + } +} + +export function reduceGesture( + state: GestureState, + event: GestureEvent, + policy: GesturePolicy +): GestureResult { + switch (state.phase) { + case 'idle': + return reduceIdle(state, event) + case 'pressed': + return reducePressed(state, event, policy) + case 'dragging': + return reduceDragging(state, event) + default: + state satisfies never + return unchanged(state) + } +} diff --git a/src/locales/ar/settings.json b/src/locales/ar/settings.json index 60ffd49bcb6..de23ce0f315 100644 --- a/src/locales/ar/settings.json +++ b/src/locales/ar/settings.json @@ -339,10 +339,6 @@ "name": "عرض تحديثات الإصدار", "tooltip": "عرض التحديثات للنماذج الجديدة والميزات الرئيسية." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "تأخير انحراف نقرة المؤشر", - "tooltip": "بعد الضغط على زر المؤشر، هذا هو الوقت الأقصى (بالملي ثانية) الذي يمكن تجاهل حركة المؤشر خلاله.\n\nيساعد على منع دفع الكائنات عن طريق الخطأ إذا تم تحريك المؤشر أثناء النقر." - }, "Comfy_Pointer_ClickDrift": { "name": "انحراف نقرة المؤشر (أقصى مسافة)", "tooltip": "إذا تحرك المؤشر أكثر من هذه المسافة أثناء الضغط على زر، يعتبر سحبًا بدلاً من نقرة.\n\nيساعد على منع دفع الكائنات عن طريق الخطأ إذا تم تحريك المؤشر أثناء النقر." diff --git a/src/locales/de/settings.json b/src/locales/de/settings.json index cac44f7b95e..86e7bf07772 100644 --- a/src/locales/de/settings.json +++ b/src/locales/de/settings.json @@ -339,10 +339,6 @@ "name": "Versionsupdates anzeigen", "tooltip": "Updates für neue Modelle und wichtige neue Funktionen anzeigen." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Verzögerung bei Zeigerklickabweichung", - "tooltip": "Nach dem Drücken einer Zeigertaste ist dies die maximale Zeit (in Millisekunden), für die Zeigerbewegungen ignoriert werden können.\n\nDies verhindert, dass Objekte unbeabsichtigt verschoben werden, wenn der Zeiger beim Klicken bewegt wird.\n\nDer Distanzschwellenwert (Zeigerklickabweichung) unterscheidet bereits zwischen Klicks und Ziehvorgängen; dieser Zeitschwellenwert ist nur relevant, wenn der Zeiger stillgehalten und dann losgelassen wird. Eine lange Verzögerung zwingt bei jedem pointerdown zum Warten, bevor das Ziehen beginnt, was sich beim Klicken und Ziehen eines nicht ausgewählten Node verzögert anfühlt. ~2 Frames bei 60 fps sind ausreichend." - }, "Comfy_Pointer_ClickDrift": { "name": "Zeigerbewegung beim Klicken (maximale Entfernung)", "tooltip": "Wenn sich der Zeiger beim Gedrückthalten einer Maustaste weiter als diese Entfernung bewegt, wird dies als Ziehen (statt als Klicken) betrachtet.\n\nHilft, unbeabsichtigtes Verschieben von Objekten zu verhindern, wenn der Zeiger beim Klicken bewegt wird." diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index f8f06ec7a5c..fa408f58542 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -339,10 +339,6 @@ "name": "Show version updates", "tooltip": "Show updates for new models, and major new features." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Pointer click drift delay", - "tooltip": "After pressing a pointer button down, this is the maximum time (in milliseconds) that pointer movement can be ignored for.\n\nHelps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking.\n\nThe distance threshold (Pointer click drift) already disambiguates clicks from drags; this time threshold only matters when the pointer is held still then released. A long delay here forces every pointerdown to wait before drag begins, which feels laggy when click+dragging an unselected node. ~2 frames at 60fps is plenty." - }, "Comfy_Pointer_ClickDrift": { "name": "Pointer click drift (maximum distance)", "tooltip": "If the pointer moves more than this distance while holding a button down, it is considered dragging (rather than clicking).\n\nHelps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking." diff --git a/src/locales/es/settings.json b/src/locales/es/settings.json index bc0a88034d4..7f592181fae 100644 --- a/src/locales/es/settings.json +++ b/src/locales/es/settings.json @@ -339,10 +339,6 @@ "name": "Mostrar actualizaciones de versión", "tooltip": "Mostrar actualizaciones para nuevos modelos y funciones principales nuevas." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Retraso de deriva del clic del puntero", - "tooltip": "Después de presionar un botón del puntero, este es el tiempo máximo (en milisegundos) que se puede ignorar el movimiento del puntero.\n\nAyuda a prevenir que los objetos sean movidos involuntariamente si el puntero se mueve al hacer clic." - }, "Comfy_Pointer_ClickDrift": { "name": "Deriva del clic del puntero (distancia máxima)", "tooltip": "Si el puntero se mueve más de esta distancia mientras se mantiene presionado un botón, se considera arrastrar (en lugar de hacer clic).\n\nAyuda a prevenir que los objetos sean movidos involuntariamente si el puntero se mueve al hacer clic." diff --git a/src/locales/fa/settings.json b/src/locales/fa/settings.json index 5bdf1b1fc44..c5716b0ff11 100644 --- a/src/locales/fa/settings.json +++ b/src/locales/fa/settings.json @@ -339,10 +339,6 @@ "name": "نمایش به‌روزرسانی نسخه‌ها", "tooltip": "نمایش به‌روزرسانی‌ها برای مدل‌های جدید و ویژگی‌های اصلی جدید." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "تاخیر حرکت اشاره‌گر پس از کلیک", - "tooltip": "پس از فشردن دکمه اشاره‌گر، این بیشترین زمان (بر حسب میلی‌ثانیه) است که حرکت اشاره‌گر می‌تواند نادیده گرفته شود.\n\nبه جلوگیری از جابجایی ناخواسته اشیاء هنگام حرکت اشاره‌گر در حین کلیک کمک می‌کند." - }, "Comfy_Pointer_ClickDrift": { "name": "میزان جابجایی اشاره‌گر هنگام کلیک (حداکثر فاصله)", "tooltip": "اگر اشاره‌گر بیش از این فاصله در هنگام نگه داشتن دکمه حرکت کند، به عنوان کشیدن (drag) در نظر گرفته می‌شود نه کلیک.\n\nبه جلوگیری از جابجایی ناخواسته اشیاء هنگام حرکت اشاره‌گر در حین کلیک کمک می‌کند." diff --git a/src/locales/fr/settings.json b/src/locales/fr/settings.json index 56ea4d3e47d..b3aae625f74 100644 --- a/src/locales/fr/settings.json +++ b/src/locales/fr/settings.json @@ -339,10 +339,6 @@ "name": "Afficher les mises à jour de version", "tooltip": "Afficher les mises à jour pour les nouveaux modèles et les nouvelles fonctionnalités majeures." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Délai de dérive du clic du pointeur", - "tooltip": "Après avoir appuyé sur un bouton de pointeur, c'est le temps maximum (en millisecondes) que le mouvement du pointeur peut être ignoré.\n\nAide à prévenir que les objets soient déplacés involontairement si le pointeur est déplacé lors du clic." - }, "Comfy_Pointer_ClickDrift": { "name": "Dérive du clic du pointeur (distance maximale)", "tooltip": "Si le pointeur se déplace plus que cette distance en maintenant un bouton enfoncé, il est considéré comme un glissement (plutôt qu'un clic).\n\nAide à prévenir que les objets soient déplacés involontairement si le pointeur est déplacé lors du clic." diff --git a/src/locales/he/settings.json b/src/locales/he/settings.json index 38fe61e1555..2abdc2d39e4 100644 --- a/src/locales/he/settings.json +++ b/src/locales/he/settings.json @@ -339,10 +339,6 @@ "name": "הצגת עדכוני גרסה", "tooltip": "הצגת עדכונים על מודלים חדשים ותכונות מרכזיות חדשות." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "השהיית סחיפת לחיצת המצביע", - "tooltip": "לאחר לחיצה על כפתור המצביע, זהו הזמן המרבי (באלפיות שנייה) שבמהלכו ניתן להתעלם מתנועת המצביע.\n\nמסייע למנוע הזזה לא מכוונת של אובייקטים אם המצביע זז תוך כדי לחיצה.\n\nסף המרחק (סחיפת לחיצת המצביע) כבר מבחין בין לחיצות לגרירות; סף הזמן הזה רלוונטי רק כאשר המצביע מוחזק במקום ואז משוחרר. השהיה ארוכה כאן מכריחה כל לחיצה להמתין לפני שמתחילה גרירה, מה שמרגיש איטי בעת לחיצה+גרירה של צומת שאינו נבחר. כ-2 פריימים ב-60fps מספיקים בהחלט." - }, "Comfy_Pointer_ClickDrift": { "name": "סחיפת לחיצת המצביע (מרחק מרבי)", "tooltip": "אם המצביע זז יותר מהמרחק הזה בזמן לחיצה על כפתור, הדבר נחשב כגרירה (ולא כלחיצה).\n\nמסייע למנוע הזזה לא מכוונת של אובייקטים אם המצביע זז תוך כדי לחיצה." diff --git a/src/locales/it/settings.json b/src/locales/it/settings.json index 719365bcd44..d98399aa009 100644 --- a/src/locales/it/settings.json +++ b/src/locales/it/settings.json @@ -339,10 +339,6 @@ "name": "Mostra aggiornamenti di versione", "tooltip": "Mostra aggiornamenti per nuovi modelli e nuove funzionalità principali." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Ritardo tolleranza clic puntatore", - "tooltip": "Dopo aver premuto un pulsante del puntatore, questo è il tempo massimo (in millisecondi) in cui il movimento del puntatore può essere ignorato.\n\nAiuta a prevenire spostamenti involontari degli oggetti se il puntatore viene mosso durante il clic.\n\nLa soglia di distanza (tolleranza clic puntatore) già distingue tra clic e trascinamento; questa soglia temporale conta solo quando il puntatore resta fermo e poi viene rilasciato. Un ritardo lungo qui obbliga ogni pressione a dover attendere prima che inizi il trascinamento, il che può risultare lento durante il click+drag di un nodo non selezionato. ~2 frame a 60fps sono sufficienti." - }, "Comfy_Pointer_ClickDrift": { "name": "Tolleranza clic puntatore (distanza massima)", "tooltip": "Se il puntatore si sposta oltre questa distanza mentre si tiene premuto un pulsante, viene considerato come trascinamento (anziché clic).\n\nAiuta a prevenire spostamenti involontari degli oggetti se il puntatore viene mosso durante il clic." diff --git a/src/locales/ja/settings.json b/src/locales/ja/settings.json index 8a87b0a3024..ca9000a57e9 100644 --- a/src/locales/ja/settings.json +++ b/src/locales/ja/settings.json @@ -339,10 +339,6 @@ "name": "バージョン更新を表示", "tooltip": "新しいモデルや主要な新機能のアップデートを表示します。" }, - "Comfy_Pointer_ClickBufferTime": { - "name": "ポインタークリックドリフト遅延", - "tooltip": "ポインターボタンを押した後、ポインタの動きが無視される最大時間(ミリ秒単位)です。\n\nクリック中にポインタが移動した場合、オブジェクトが意図せず動かされるのを防ぎます。" - }, "Comfy_Pointer_ClickDrift": { "name": "ポインタークリックドリフト(最大距離)", "tooltip": "ボタンを押し続けている間にポインタがこの距離以上移動した場合、クリックではなくドラッグと見なされます。\n\nクリック中にポインタが移動した場合、オブジェクトが意図せず動かされるのを防ぎます。" diff --git a/src/locales/ko/settings.json b/src/locales/ko/settings.json index d585c78fb86..9d2dbad5bdd 100644 --- a/src/locales/ko/settings.json +++ b/src/locales/ko/settings.json @@ -339,10 +339,6 @@ "name": "버전 업데이트 표시", "tooltip": "새 모델과 주요 신규 기능에 대한 업데이트를 표시합니다." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "포인터 클릭 드리프트 지연", - "tooltip": "포인터 버튼을 누른 후, 포인터 움직임을 무시할 수 있는 최대 시간(밀리초)입니다.\n\n클릭하는 동안 포인터가 움직여 의도치 않게 객체가 밀리는 것을 방지합니다." - }, "Comfy_Pointer_ClickDrift": { "name": "포인터 클릭 드리프트 (최대 거리)", "tooltip": "버튼을 누른 상태에서 포인터가 이 거리보다 더 많이 움직이면, 클릭이 아닌 드래그로 간주됩니다.\n\n클릭하는 동안 포인터가 움직여 의도치 않게 객체가 밀리는 것을 방지합니다." diff --git a/src/locales/pt-BR/settings.json b/src/locales/pt-BR/settings.json index 9fdc6db2d20..9716498cfdc 100644 --- a/src/locales/pt-BR/settings.json +++ b/src/locales/pt-BR/settings.json @@ -339,10 +339,6 @@ "name": "Mostrar atualizações de versão", "tooltip": "Mostrar atualizações para novos modelos e grandes novos recursos." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Atraso de tolerância de clique do ponteiro", - "tooltip": "Após pressionar um botão do ponteiro, este é o tempo máximo (em milissegundos) em que o movimento do ponteiro pode ser ignorado.\n\nAjuda a evitar que objetos sejam movidos acidentalmente se o ponteiro for movido ao clicar." - }, "Comfy_Pointer_ClickDrift": { "name": "Tolerância de movimento do clique do ponteiro (distância máxima)", "tooltip": "Se o ponteiro se mover mais do que esta distância enquanto um botão estiver pressionado, será considerado arrastar (em vez de clicar).\n\nAjuda a evitar que objetos sejam movidos acidentalmente se o ponteiro for movido ao clicar." diff --git a/src/locales/ru/settings.json b/src/locales/ru/settings.json index 92b16ef9143..d66f2edf4ea 100644 --- a/src/locales/ru/settings.json +++ b/src/locales/ru/settings.json @@ -339,10 +339,6 @@ "name": "Показывать обновления версий", "tooltip": "Показывать обновления новых моделей и основные новые функции." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "Задержка дрейфа щелчка указателя", - "tooltip": "После нажатия кнопки указателя, это максимальное время (в миллисекундах), в течение которого движение указателя может быть проигнорировано.\n\nПомогает предотвратить непреднамеренное смещение объектов, если указатель перемещается во время щелчка." - }, "Comfy_Pointer_ClickDrift": { "name": "Дрейф щелчка указателя (максимальное расстояние)", "tooltip": "Если указатель перемещается более чем на это расстояние, удерживая кнопку, это считается перетаскиванием (а не щелчком).\n\nПомогает предотвратить непреднамеренное смещение объектов, если указатель перемещается во время щелчка." diff --git a/src/locales/tr/settings.json b/src/locales/tr/settings.json index d1d9f0653b7..24b11283782 100644 --- a/src/locales/tr/settings.json +++ b/src/locales/tr/settings.json @@ -339,10 +339,6 @@ "name": "Sürüm güncellemelerini göster", "tooltip": "Yeni modeller ve önemli yeni özellikler için güncellemeleri göster." }, - "Comfy_Pointer_ClickBufferTime": { - "name": "İşaretçi tıklama kayma gecikmesi", - "tooltip": "Bir işaretçi düğmesine bastıktan sonra, bu, işaretçi hareketinin göz ardı edilebileceği maksimum süredir (milisaniye cinsinden).\n\nTıklarken işaretçi hareket ettirilirse nesnelerin istemeden dürtülmesini önlemeye yardımcı olur." - }, "Comfy_Pointer_ClickDrift": { "name": "İşaretçi tıklama kayması (maksimum mesafe)", "tooltip": "İşaretçi bir düğmeyi basılı tutarken bu mesafeden daha fazla hareket ederse, bu sürükleme olarak kabul edilir (tıklama yerine).\n\nTıklarken işaretçi hareket ettirilirse nesnelerin istemeden dürtülmesini önlemeye yardımcı olur." diff --git a/src/locales/zh-TW/settings.json b/src/locales/zh-TW/settings.json index 69a58ac6fa8..e47efb7ca7f 100644 --- a/src/locales/zh-TW/settings.json +++ b/src/locales/zh-TW/settings.json @@ -339,10 +339,6 @@ "name": "顯示版本更新", "tooltip": "顯示新模型和主要新功能的更新。" }, - "Comfy_Pointer_ClickBufferTime": { - "name": "指標點擊漂移延遲", - "tooltip": "按下指標按鈕後,這是可忽略指標移動的最長時間(以毫秒為單位)。\n\n可防止在點擊時移動指標導致物件被意外推動。" - }, "Comfy_Pointer_ClickDrift": { "name": "指標點擊漂移(最大距離)", "tooltip": "如果在按住按鈕時指標移動超過此距離,則視為拖曳(而非點擊)。\n\n可防止在點擊時不小心移動指標導致物件被意外推動。" diff --git a/src/locales/zh/settings.json b/src/locales/zh/settings.json index 5049ac8046f..04d996ee9c2 100644 --- a/src/locales/zh/settings.json +++ b/src/locales/zh/settings.json @@ -339,10 +339,6 @@ "name": "显示版本更新", "tooltip": "显示新模型和主要新功能的更新。" }, - "Comfy_Pointer_ClickBufferTime": { - "name": "指针点击漂移延迟", - "tooltip": "按下指针按钮后,忽略指针移动的最大时间(毫秒)。\n\n有助于防止在点击时意外移动鼠标。" - }, "Comfy_Pointer_ClickDrift": { "name": "指针点击漂移(距离)", "tooltip": "如果指针在按住按钮时移动超过此距离,则视为拖动(而不是点击)。\n\n有助于防止在点击时意外移动鼠标" diff --git a/src/platform/settings/composables/useLitegraphSettings.ts b/src/platform/settings/composables/useLitegraphSettings.ts index 9fbcc57cb4d..e7b957ef842 100644 --- a/src/platform/settings/composables/useLitegraphSettings.ts +++ b/src/platform/settings/composables/useLitegraphSettings.ts @@ -134,10 +134,6 @@ export const useLitegraphSettings = () => { ) }) - watchEffect(() => { - CanvasPointer.bufferTime = settingStore.get('Comfy.Pointer.ClickBufferTime') - }) - watchEffect(() => { CanvasPointer.maxClickDrift = settingStore.get('Comfy.Pointer.ClickDrift') }) diff --git a/src/platform/settings/constants/coreSettings.ts b/src/platform/settings/constants/coreSettings.ts index 8c463e5291b..8fd57be7e7f 100644 --- a/src/platform/settings/constants/coreSettings.ts +++ b/src/platform/settings/constants/coreSettings.ts @@ -790,20 +790,12 @@ export const CORE_SETTINGS: SettingParams[] = [ }, { id: 'Comfy.Pointer.ClickBufferTime', - category: ['LiteGraph', 'Pointer', 'ClickBufferTime'], - name: 'Pointer click drift delay', - tooltip: - 'After pressing a pointer button down, this is the maximum time (in milliseconds) that pointer movement can be ignored for.\n\nHelps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking.\n\nThe distance threshold (Pointer click drift) already disambiguates clicks from drags; this time threshold only matters when the pointer is held still then released. A long delay here forces every pointerdown to wait before drag begins, which feels laggy when click+dragging an unselected node. ~2 frames at 60fps is plenty.', - experimental: true, - type: 'slider', - attrs: { - min: 0, - max: 1000, - step: 1 - }, + name: 'Pointer click drift delay (deprecated)', + type: 'hidden', + deprecated: true, defaultValue: 32, versionAdded: '1.4.3', - versionModified: '1.44.19' + versionModified: '1.54.3' }, { id: 'Comfy.Pointer.DoubleClickTime',