Line data Source code
1 : // oxlint-disable-next-line comfy/no-restricted-paths
2 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
3 : /**
4 : * Utility functions for handling workbench events
5 : */
6 :
7 1973 : function activeTextSelection(): Selection | null {
8 1973 : const selection = window.getSelection()
9 1973 : return selection !== null && !selection.isCollapsed ? selection : null
10 : }
11 :
12 0 : export function hasTextSelection(target: EventTarget | null): boolean {
13 0 : if (
14 : target instanceof HTMLInputElement ||
15 : target instanceof HTMLTextAreaElement
16 : ) {
17 : if (
18 0 : target.selectionStart !== null &&
19 : target.selectionEnd !== null &&
20 : target.selectionStart !== target.selectionEnd
21 : )
22 0 : return true
23 : }
24 :
25 0 : return activeTextSelection() !== null
26 : }
27 :
28 1 : function rangesOf(selection: Selection): Range[] {
29 1 : return Array.from({ length: selection.rangeCount }, (_, i) =>
30 : selection.getRangeAt(i)
31 : )
32 : }
33 :
34 : /**
35 : * Collapse a text selection unless every range lies wholly inside
36 : * `container`, the way a plain mousedown would before the canvas called
37 : * `preventDefault()` on it. A copy or paste that follows a click on the graph
38 : * then reaches the graph instead of the stale selection.
39 : */
40 1924 : export function collapseTextSelectionOutside(container: Element): void {
41 1924 : const selection = activeTextSelection()
42 1924 : if (
43 : selection &&
44 : rangesOf(selection).some(
45 : (range) =>
46 : !container.contains(range.startContainer) ||
47 : !container.contains(range.endContainer)
48 : )
49 : )
50 1 : selection.removeAllRanges()
51 : }
52 :
53 2143 : export function collapseOutsideSelectionOnPrimaryPointerDown(
54 : event: PointerEvent
55 : ): void {
56 2143 : if (event.button === 0 && event.target instanceof Element)
57 1924 : collapseTextSelectionOutside(event.target)
58 : }
59 :
60 : /**
61 : * Used by clipboard handlers to determine if copy/paste events should be
62 : * intercepted for graph operations vs. allowing default browser behavior
63 : * for text inputs and other UI elements.
64 : *
65 : * @param target - The event target to check
66 : * @returns true if copy paste events will be handled by target
67 : */
68 66 : export function shouldIgnoreCopyPaste(target: EventTarget | null): boolean {
69 : const isTextInput =
70 : target instanceof HTMLTextAreaElement ||
71 : (target instanceof HTMLElement && target.isContentEditable) ||
72 : (target instanceof HTMLInputElement &&
73 : ![
74 : 'button',
75 : 'checkbox',
76 : 'file',
77 : 'hidden',
78 : 'image',
79 : 'radio',
80 : 'range',
81 : 'reset',
82 : 'submit'
83 : ].includes(target.type))
84 66 : return (
85 : isTextInput || useCanvasStore().linearMode || activeTextSelection() !== null
86 : )
87 : }
|