LCOV - code coverage report
Current view: top level - src/composables/graph - useImageMenuOptions.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 86.6 % 97 84
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
       2              : import { useI18n } from 'vue-i18n'
       3              : 
       4              : import { downloadFile, openFileInNewTab } from '@/base/common/downloadUtil'
       5              : import { useToast } from '@/components/ui/toast/toastStore'
       6              : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
       7              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
       8              : import { useNodeOutputsExport } from '@/platform/assets/composables/useNodeOutputsExport'
       9              : import { useCommandStore } from '@/platform/keybindings/commandStore'
      10              : import { useSettingStore } from '@/platform/settings/settingStore'
      11              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      12              : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
      13              : import type { CoreMediaMenuActionKind } from '@/utils/coreMediaMenuActionUtils'
      14              : import { fullResolutionSrc, getImageFileUrl } from '@/utils/hdrFormatUtil'
      15              : import { isImageNode } from '@/utils/litegraphUtil'
      16              : 
      17              : import type { MenuOption } from './menuOption'
      18              : 
      19              : type ImageMenuAvailability = Record<CoreMediaMenuActionKind, boolean>
      20              : 
      21         2355 : const DEFAULT_IMAGE_MENU_AVAILABILITY: ImageMenuAvailability = {
      22              :   input: true,
      23              :   preview: true
      24              : }
      25              : 
      26          167 : function canPasteImage(node?: LGraphNode): boolean {
      27          167 :   return typeof node?.pasteFiles === 'function'
      28              : }
      29              : 
      30            1 : async function fullResolutionImage(
      31              :   img: HTMLImageElement
      32              : ): Promise<HTMLImageElement | undefined> {
      33            1 :   const src = fullResolutionSrc(img)
      34            1 :   if (src === img.src) return img
      35            0 :   const full = new Image()
      36            0 :   full.src = src
      37            0 :   try {
      38            0 :     await full.decode()
      39            0 :     return full
      40              :   } catch {
      41            0 :     return undefined
      42              :   }
      43              : }
      44              : 
      45            1 : async function pasteClipboardImageToNode(node: LGraphNode): Promise<void> {
      46            1 :   try {
      47            1 :     const clipboardItems = await navigator.clipboard.read()
      48            1 :     for (const item of clipboardItems) {
      49            1 :       const imageType = item.types.find((type) => type.startsWith('image/'))
      50            1 :       if (!imageType) continue
      51              : 
      52            1 :       const blob = await item.getType(imageType)
      53            1 :       const ext = imageType.split('/')[1] ?? 'png'
      54            1 :       const file = new File([blob], `pasted-image.${ext}`, {
      55              :         type: imageType
      56              :       })
      57            1 :       node.pasteFile?.(file)
      58            1 :       node.pasteFiles?.([file])
      59            1 :       return
      60              :     }
      61              :   } catch (error) {
      62            0 :     console.error('Failed to paste image from clipboard:', error)
      63              :   }
      64              : }
      65              : 
      66              : /**
      67              :  * Composable for image-related menu operations
      68              :  */
      69         2355 : export function useImageMenuOptions() {
      70         2355 :   const { t } = useI18n()
      71         2355 :   const toast = useToast()
      72         2355 :   const { hasMultipleOutputs, showOutputsExportDialog } = useNodeOutputsExport()
      73         2355 :   const nodeOutputStore = useNodeOutputStore()
      74         2355 :   const settingStore = useSettingStore()
      75              : 
      76         2355 :   const showsSingleImage = (node: LGraphNode) =>
      77              :     isImageNode(node) &&
      78              :     nodeOutputStore.getNodeOutputs(node)?.images?.length === 1
      79              : 
      80         2355 :   const toggleFullResolutionPreview = (node: LGraphNode) => {
      81            2 :     node.flags.fullResolutionPreview = node.flags.fullResolutionPreview
      82              :       ? undefined
      83              :       : true
      84            2 :     useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
      85              :   }
      86              : 
      87         2355 :   const openMaskEditor = () => {
      88              :     const commandStore = useCommandStore()
      89            2 :     void commandStore.execute('Comfy.MaskEditor.OpenMaskEditor')
      90              :   }
      91              : 
      92         2355 :   const openImage = (node: LGraphNode) => {
      93            2 :     const images = node.imgs
      94            2 :     if (!images?.length) return
      95            2 :     const img = images.at(node.imageIndex ?? 0)
      96            2 :     if (!img) return
      97            2 :     const url = getImageFileUrl(img)
      98            2 :     void openFileInNewTab(url.toString())
      99              :   }
     100              : 
     101         2355 :   const copyImage = async (node: LGraphNode) => {
     102            1 :     const images = node.imgs
     103            1 :     if (!images?.length) return
     104            1 :     const img = images.at(node.imageIndex ?? 0)
     105            1 :     if (!img) return
     106              : 
     107            1 :     const canvas = document.createElement('canvas')
     108            1 :     const ctx = canvas.getContext('2d')
     109            1 :     if (!ctx) return
     110              : 
     111            1 :     const source = await fullResolutionImage(img)
     112            1 :     if (!source) {
     113            0 :       toast.warning(
     114              :         t('toastMessages.errorCopyImage', { error: t('g.unknownError') })
     115              :       )
     116            0 :       return
     117              :     }
     118              : 
     119            1 :     try {
     120            1 :       canvas.width = source.naturalWidth
     121            1 :       canvas.height = source.naturalHeight
     122            1 :       ctx.drawImage(source, 0, 0)
     123              : 
     124            1 :       const blob = await new Promise<Blob | null>((resolve) => {
     125            1 :         canvas.toBlob(resolve, 'image/png')
     126              :       })
     127              : 
     128            1 :       if (!blob) {
     129            0 :         console.warn('Failed to create image blob')
     130            0 :         return
     131              :       }
     132              : 
     133            1 :       await navigator.clipboard.write([
     134              :         new ClipboardItem({ 'image/png': blob })
     135              :       ])
     136              :     } catch (error) {
     137            0 :       toast.warning(
     138              :         t('toastMessages.errorCopyImage', {
     139              :           error: getErrorMessage(error) ?? t('g.unknownError')
     140              :         })
     141              :       )
     142              :     }
     143              :   }
     144              : 
     145         2355 :   const saveImage = (node: LGraphNode) => {
     146            2 :     const images = node.imgs
     147            2 :     if (!images?.length) return
     148            2 :     const img = images.at(node.imageIndex ?? 0)
     149            2 :     if (!img) return
     150              : 
     151            2 :     try {
     152            2 :       const url = getImageFileUrl(img)
     153            2 :       downloadFile(url.toString())
     154              :     } catch (error) {
     155            0 :       console.error('Failed to save image:', error)
     156              :     }
     157              :   }
     158              : 
     159         2355 :   const getImageMenuOptions = (
     160              :     node: LGraphNode,
     161              :     availability: ImageMenuAvailability = DEFAULT_IMAGE_MENU_AVAILABILITY
     162              :   ): MenuOption[] => {
     163          167 :     const hasImages = !!node.imgs?.length
     164          167 :     const canPaste = canPasteImage(node)
     165          167 :     const canExportOutputs = availability.preview && hasMultipleOutputs(node)
     166          167 :     if (
     167              :       (!hasImages || !availability.preview) &&
     168              :       (!canPaste || !availability.input) &&
     169              :       !canExportOutputs
     170              :     )
     171            6 :       return []
     172              : 
     173          161 :     const options: MenuOption[] = []
     174              : 
     175          167 :     if (hasImages && availability.preview) {
     176           81 :       options.push(
     177              :         {
     178              :           label: t('contextMenu.Open Image'),
     179              :           icon: 'icon-[lucide--external-link]',
     180              :           action: () => openImage(node)
     181              :         },
     182              :         {
     183              :           label: t('contextMenu.Open in Mask Editor'),
     184              :           icon: 'icon-[comfy--mask]',
     185              :           action: () => openMaskEditor()
     186              :         },
     187              :         {
     188              :           label: t('contextMenu.Copy Image'),
     189              :           icon: 'icon-[lucide--copy]',
     190              :           action: () => copyImage(node)
     191              :         }
     192              :       )
     193              :     }
     194              : 
     195          167 :     if (canPaste && availability.input) {
     196          145 :       options.push({
     197              :         label: t('contextMenu.Paste Image'),
     198              :         icon: 'icon-[lucide--clipboard-paste]',
     199              :         action: () => pasteClipboardImageToNode(node)
     200              :       })
     201              :     }
     202              : 
     203          167 :     if (hasImages && availability.preview) {
     204           81 :       options.push({
     205              :         label: t('contextMenu.Save Image'),
     206              :         icon: 'icon-[lucide--download]',
     207              :         action: () => saveImage(node)
     208              :       })
     209              :     }
     210              : 
     211          163 :     if (canExportOutputs) {
     212           18 :       options.push({
     213              :         label: t('contextMenu.Download Images'),
     214              :         icon: 'icon-[lucide--folder-down]',
     215              :         action: () => showOutputsExportDialog(node)
     216              :       })
     217              :     }
     218              : 
     219          161 :     return options
     220              :   }
     221              : 
     222         2355 :   const getPreviewResolutionOption = (
     223              :     node: LGraphNode
     224              :   ): MenuOption | undefined => {
     225         2297 :     if (
     226              :       !LiteGraph.vueNodesMode ||
     227              :       !settingStore.get('Comfy.Node.DownscaleImagePreviews') ||
     228              :       !showsSingleImage(node)
     229              :     )
     230         2194 :       return
     231         2297 :     return node.flags.fullResolutionPreview
     232              :       ? {
     233              :           label: t('contextMenu.Show Downscaled Preview'),
     234              :           icon: 'icon-[lucide--image-down]',
     235              :           action: () => toggleFullResolutionPreview(node)
     236              :         }
     237              :       : {
     238              :           label: t('contextMenu.Show Full Resolution'),
     239              :           icon: 'icon-[lucide--image-upscale]',
     240              :           action: () => toggleFullResolutionPreview(node)
     241              :         }
     242              :   }
     243              : 
     244         2355 :   return {
     245              :     getImageMenuOptions,
     246              :     getPreviewResolutionOption
     247              :   }
     248              : }
        

Generated by: LCOV version 2.0-1