LCOV - code coverage report
Current view: top level - src/composables - usePaste.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 67.6 % 139 94
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useEventListener } from '@vueuse/core'
       2              : 
       3              : import { useToast } from '@/components/ui/toast/toastStore'
       4              : import { parseClipboardHtml } from '@/composables/useCopy'
       5              : import { useErrorHandling } from '@/composables/useErrorHandling'
       6              : import { t } from '@/i18n'
       7              : import { CANVAS_CLIPBOARD_KEY } from '@/lib/litegraph/src/canvas/clipboardStorage'
       8              : import type { LGraphCanvas, LGraphNode } from '@/lib/litegraph/src/litegraph'
       9              : import { zClipboardItems } from '@comfyorg/graph-model/workflowSchema'
      10              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      11              : import { useApp } from '@/scripts/appInstance'
      12              : import type { ComfyApp } from '@/types/comfy'
      13              : import { useWorkspaceStore } from '@/stores/workspaceStore'
      14              : import {
      15              :   isAudioNode,
      16              :   isImageNode,
      17              :   isSelectOnly,
      18              :   isVideoNode
      19              : } from '@/utils/litegraphUtil'
      20              : import { createNode } from '@/utils/createNode'
      21              : import { shouldIgnoreCopyPaste } from '@/workbench/eventHelpers'
      22              : 
      23           31 : export function cloneDataTransfer(original: DataTransfer): DataTransfer {
      24           31 :   const persistent = new DataTransfer()
      25              : 
      26              :   // Copy string data
      27           31 :   for (const type of original.types) {
      28           31 :     const data = original.getData(type)
      29           31 :     if (data) {
      30           27 :       persistent.setData(type, data)
      31              :     }
      32              :   }
      33              : 
      34           31 :   for (const item of original.items) {
      35           31 :     if (item.kind === 'file') {
      36            4 :       const file = item.getAsFile()
      37            4 :       if (file) {
      38            4 :         persistent.items.add(file)
      39              :       }
      40              :     }
      41              :   }
      42              : 
      43              :   // Preserve dropEffect and effectAllowed
      44           31 :   persistent.dropEffect = original.dropEffect
      45           31 :   persistent.effectAllowed = original.effectAllowed
      46              : 
      47           31 :   return persistent
      48              : }
      49              : 
      50           23 : function pasteClipboardItems(data: DataTransfer): boolean {
      51           23 :   const parsed = parseClipboardHtml(data.getData('text/html'))
      52           23 :   if (parsed.status === 'absent') return false
      53           18 :   if (parsed.status === 'unreadable') {
      54            0 :     useErrorHandling().toastErrorHandler(parsed.cause)
      55            0 :     return true
      56              :   }
      57              : 
      58           18 :   const clipboardItems = zClipboardItems.safeParse(parsed.payload)
      59           18 :   if (!clipboardItems.success) {
      60            0 :     useErrorHandling().toastErrorHandler(clipboardItems.error)
      61            0 :     return true
      62              :   }
      63              : 
      64           18 :   try {
      65           18 :     useCanvasStore().getCanvas()._deserializeItems(clipboardItems.data, {})
      66              :   } catch (err) {
      67            0 :     useErrorHandling().toastErrorHandler(err)
      68              :   }
      69           18 :   return true
      70              : }
      71              : 
      72            4 : function holdsLatestCanvasCopy(html: string): boolean {
      73            4 :   const parsed = parseClipboardHtml(html)
      74            4 :   if (parsed.status !== 'read') return false
      75            3 :   try {
      76            2 :     return parsed.text === localStorage.getItem(CANVAS_CLIPBOARD_KEY)
      77              :   } catch {
      78            0 :     return false
      79              :   }
      80              : }
      81              : 
      82            9 : function isWorkflow(
      83              :   value: unknown
      84              : ): value is Parameters<ComfyApp['loadGraphData']>[0] {
      85            9 :   return (
      86              :     typeof value === 'object' &&
      87              :     value !== null &&
      88              :     'version' in value &&
      89              :     (typeof value.version === 'number' || typeof value.version === 'string') &&
      90              :     'nodes' in value &&
      91              :     Array.isArray(value.nodes) &&
      92              :     'extra' in value &&
      93              :     typeof value.extra === 'object' &&
      94              :     value.extra !== null &&
      95              :     !Array.isArray(value.extra)
      96              :   )
      97              : }
      98              : 
      99            9 : function pasteItemsOnNode(
     100              :   items: DataTransferItemList,
     101              :   node: LGraphNode | null,
     102              :   contentType: string
     103              : ): void {
     104            9 :   if (!node) return
     105              : 
     106            9 :   const filteredItems = Array.from(items).filter((item) =>
     107              :     item.type.startsWith(contentType)
     108              :   )
     109              : 
     110            9 :   const blob = filteredItems[0]?.getAsFile()
     111            9 :   if (!blob) return
     112              : 
     113            9 :   node.pasteFile?.(blob)
     114            9 :   node.pasteFiles?.(
     115              :     Array.from(filteredItems)
     116              :       .map((i) => i.getAsFile())
     117              :       .filter((f) => f !== null)
     118              :   )
     119              : }
     120              : 
     121            7 : export async function pasteImageNode(
     122              :   canvas: LGraphCanvas,
     123              :   items: DataTransferItemList,
     124              :   imageNode: LGraphNode | null = null
     125              : ): Promise<LGraphNode | null> {
     126              :   // No image node selected: add a new one
     127            7 :   if (!imageNode) {
     128            1 :     imageNode = await createNode(canvas, 'LoadImage')
     129              :   }
     130              : 
     131            7 :   pasteItemsOnNode(items, imageNode, 'image')
     132            7 :   return imageNode
     133              : }
     134              : 
     135            0 : export async function pasteImageNodes(
     136              :   canvas: LGraphCanvas,
     137              :   fileList: File[]
     138              : ): Promise<LGraphNode[]> {
     139            0 :   const nodes: LGraphNode[] = []
     140              : 
     141            0 :   for (const file of fileList) {
     142            0 :     const transfer = new DataTransfer()
     143            0 :     transfer.items.add(file)
     144            0 :     const imageNode = await pasteImageNode(canvas, transfer.items)
     145              : 
     146            0 :     if (imageNode) {
     147            0 :       nodes.push(imageNode)
     148              :     }
     149              :   }
     150              : 
     151            0 :   return nodes
     152              : }
     153              : 
     154            0 : export async function pasteAudioNode(
     155              :   canvas: LGraphCanvas,
     156              :   items: DataTransferItemList,
     157              :   audioNode: LGraphNode | null = null
     158              : ): Promise<LGraphNode | null> {
     159            0 :   if (!audioNode) {
     160            0 :     audioNode = await createNode(canvas, 'LoadAudio')
     161              :   }
     162            0 :   pasteItemsOnNode(items, audioNode, 'audio')
     163            0 :   return audioNode
     164              : }
     165              : 
     166            0 : export async function pasteAudioNodes(
     167              :   canvas: LGraphCanvas,
     168              :   fileList: File[]
     169              : ): Promise<LGraphNode[]> {
     170            0 :   const nodes: LGraphNode[] = []
     171              : 
     172            0 :   for (const file of fileList) {
     173            0 :     const transfer = new DataTransfer()
     174            0 :     transfer.items.add(file)
     175            0 :     const node = await pasteAudioNode(canvas, transfer.items)
     176              : 
     177            0 :     if (node) {
     178            0 :       nodes.push(node)
     179              :     }
     180              :   }
     181              : 
     182            0 :   return nodes
     183              : }
     184              : 
     185            2 : export async function pasteVideoNode(
     186              :   canvas: LGraphCanvas,
     187              :   items: DataTransferItemList,
     188              :   videoNode: LGraphNode | null = null
     189              : ): Promise<LGraphNode | null> {
     190            2 :   if (!videoNode) {
     191            0 :     videoNode = await createNode(canvas, 'LoadVideo')
     192              :   }
     193            2 :   pasteItemsOnNode(items, videoNode, 'video')
     194            2 :   return videoNode
     195              : }
     196              : 
     197            0 : export async function pasteVideoNodes(
     198              :   canvas: LGraphCanvas,
     199              :   fileList: File[]
     200              : ): Promise<LGraphNode[]> {
     201            0 :   const nodes: LGraphNode[] = []
     202              : 
     203            0 :   for (const file of fileList) {
     204            0 :     const transfer = new DataTransfer()
     205            0 :     transfer.items.add(file)
     206            0 :     const node = await pasteVideoNode(canvas, transfer.items)
     207              : 
     208            0 :     if (node) {
     209            0 :       nodes.push(node)
     210              :     }
     211              :   }
     212              : 
     213            0 :   return nodes
     214              : }
     215              : 
     216              : /**
     217              :  * Adds a handler on paste that extracts and loads images or workflows from pasted JSON data
     218              :  */
     219         2356 : export const usePaste = () => {
     220         2355 :   const workspaceStore = useWorkspaceStore()
     221         2355 :   const canvasStore = useCanvasStore()
     222              : 
     223         2355 :   useEventListener(document, 'paste', async (e) => {
     224              :     // An editor claims the paste it handles by cancelling it. Its target is not
     225              :     // always editable: a caret inside an uneditable chip makes the chip the
     226              :     // target, which shouldIgnoreCopyPaste would hand to the canvas.
     227           39 :     if (e.defaultPrevented) return
     228           39 :     if (shouldIgnoreCopyPaste(e.target)) {
     229              :       // Default system copy
     230            8 :       return
     231              :     }
     232              :     // ctrl+shift+v is used to paste nodes with connections
     233              :     // this is handled by litegraph
     234           31 :     if (workspaceStore.shiftDown) return
     235              : 
     236           31 :     const { canvas } = canvasStore
     237           39 :     if (!canvas || isSelectOnly(canvas)) return
     238              : 
     239           31 :     let data: DataTransfer | string | null = e.clipboardData
     240           31 :     if (!data) {
     241            0 :       console.error('No clipboard data on clipboard event')
     242            0 :       return
     243              :     }
     244           31 :     data = cloneDataTransfer(data)
     245              : 
     246           31 :     const { items } = data
     247              : 
     248           31 :     const currentNode = canvas.current_node
     249           39 :     const isNodeSelected = currentNode?.is_selected
     250              : 
     251           39 :     const isImageNodeSelected = isNodeSelected && isImageNode(currentNode)
     252           39 :     const isVideoNodeSelected = isNodeSelected && isVideoNode(currentNode)
     253           39 :     const isAudioNodeSelected = isNodeSelected && isAudioNode(currentNode)
     254              : 
     255           39 :     const audioNode: LGraphNode | null = isAudioNodeSelected
     256              :       ? currentNode
     257              :       : null
     258           39 :     const imageNode: LGraphNode | null = isImageNodeSelected
     259              :       ? currentNode
     260              :       : null
     261           39 :     const videoNode: LGraphNode | null = isVideoNodeSelected
     262              :       ? currentNode
     263              :       : null
     264              : 
     265              :     // Look for image paste data
     266           39 :     for (const item of items) {
     267           31 :       if (item.type.startsWith('image/')) {
     268            3 :         await pasteImageNode(canvas, items, imageNode)
     269            3 :         return
     270           28 :       } else if (item.type.startsWith('video/')) {
     271            1 :         await pasteVideoNode(canvas, items, videoNode)
     272            1 :         return
     273           27 :       } else if (item.type.startsWith('audio/')) {
     274            0 :         await pasteAudioNode(canvas, items, audioNode)
     275            0 :         return
     276              :       }
     277              :     }
     278              : 
     279           39 :     const isMediaNodeSelected =
     280              :       isImageNodeSelected || isVideoNodeSelected || isAudioNodeSelected
     281           39 :     if (!isMediaNodeSelected && pasteClipboardItems(data)) return
     282            9 :     const html = data.getData('text/html')
     283              : 
     284              :     // No image found. Look for node data
     285            9 :     data = data.getData('text/plain')
     286            9 :     let workflow: unknown
     287            9 :     try {
     288            9 :       data = data.slice(data.indexOf('{'))
     289            9 :       workflow = JSON.parse(data)
     290              :     } catch {
     291            9 :       try {
     292            9 :         data = data.slice(data.indexOf('workflow\n'))
     293            9 :         data = data.slice(data.indexOf('{'))
     294            9 :         workflow = JSON.parse(data)
     295              :       } catch {
     296            9 :         workflow = null
     297              :       }
     298              :     }
     299              : 
     300            9 :     if (isWorkflow(workflow)) {
     301            0 :       await useApp().loadGraphData(workflow)
     302              :     } else {
     303            9 :       if (
     304              :         (e.target instanceof HTMLTextAreaElement &&
     305              :           e.target.type === 'textarea') ||
     306              :         (e.target instanceof HTMLInputElement && e.target.type === 'text')
     307              :       ) {
     308            0 :         return
     309              :       }
     310              : 
     311              :       // Litegraph default paste
     312            9 :       if (!isMediaNodeSelected || holdsLatestCanvasCopy(html)) {
     313            7 :         canvas.pasteFromClipboard()
     314              :       } else {
     315            2 :         useToast().info(t('toastMessages.nothingToPasteIntoNode'), {
     316              :           duration: 3000
     317              :         })
     318              :       }
     319              :     }
     320              :   })
     321              : }
        

Generated by: LCOV version 2.0-1