LCOV - code coverage report
Current view: top level - src/stores - appModeStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 84.7 % 137 116
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { defineStore } from 'pinia'
       2              : import { ref, computed, watch } from 'vue'
       3              : import { useEventListener } from '@vueuse/core'
       4              : 
       5              : import { useAppMode } from '@/composables/useAppMode'
       6              : import { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode'
       7              : import type {
       8              :   InputWidgetConfig,
       9              :   LinearData,
      10              :   LinearInput
      11              : } from '@/platform/workflow/management/stores/comfyWorkflow'
      12              : import { useSettingStore } from '@/platform/settings/settingStore'
      13              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      14              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      15              : import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore'
      16              : import { useApp } from '@/scripts/appInstance'
      17              : import type { ComfyApp } from '@/types/comfy'
      18              : import { ChangeTracker } from '@/scripts/changeTracker'
      19              : import { resolveSubgraphInputTarget } from '@/core/graph/subgraph/resolveSubgraphInputTarget'
      20              : import type { LGraph } from '@/lib/litegraph/src/litegraph'
      21              : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
      22              : import {
      23              :   getWidgetIdForNode,
      24              :   resolveNode,
      25              :   resolveNodeWidget
      26              : } from '@/utils/litegraphUtil'
      27              : import { parseNodeId } from '@comfyorg/graph-model/nodeId'
      28              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      29              : import type { WidgetId } from '@comfyorg/graph-model/widgetId'
      30              : import { isWidgetId, parseWidgetId } from '@comfyorg/graph-model/widgetId'
      31              : import type { ViewMode } from '@comfyorg/graph-model/appMode'
      32              : 
      33          881 : function findWidgetByEntityId(
      34              :   rootGraph: LGraph,
      35              :   widgetId: WidgetId
      36              : ): IBaseWidget | undefined {
      37          881 :   for (const node of rootGraph.nodes) {
      38         3782 :     const widget = node.widgets?.find(
      39              :       (w) => getWidgetIdForNode(node, w) === widgetId
      40              :     )
      41         3782 :     if (widget) return widget
      42              :   }
      43              :   return undefined
      44              : }
      45              : 
      46          373 : export function nodeTypeValidForApp(type: string) {
      47          373 :   return !['Note', 'MarkdownNote'].includes(type)
      48              : }
      49              : 
      50         2356 : export const useAppModeStore = defineStore('appMode', () => {
      51         2355 :   const { getCanvas } = useCanvasStore()
      52         2355 :   const settingStore = useSettingStore()
      53         2355 :   const workflowStore = useWorkflowStore()
      54         2355 :   const { mode, setMode, isAppMode, isBuilderMode, isSelectMode } = useAppMode()
      55              : 
      56         2355 :   const showVueNodeSwitchPopup = ref(false)
      57              : 
      58         2355 :   const viewMode = computed<ViewMode>(() => (isAppMode.value ? 'app' : 'graph'))
      59              : 
      60              :   /**
      61              :    * Frame-lagged mirror of {@link viewMode} driving the view-mode toggle's
      62              :    * segment morph. The two-frame lag lets a toggle that mounts mid-switch
      63              :    * render the previous mode first, then animate in. Kept in the store so it
      64              :    * outlives the graph-mode toggle unmounting as the app toggle replaces it.
      65              :    */
      66         2355 :   const displayViewMode = ref<ViewMode>(viewMode.value)
      67         2355 :   let outerFrame: number | undefined
      68         2355 :   let innerFrame: number | undefined
      69         2355 :   watch(viewMode, (next) => {
      70          108 :     if (outerFrame !== undefined) cancelAnimationFrame(outerFrame)
      71          108 :     if (innerFrame !== undefined) cancelAnimationFrame(innerFrame)
      72          108 :     outerFrame = requestAnimationFrame(() => {
      73          108 :       innerFrame = requestAnimationFrame(() => {
      74          108 :         displayViewMode.value = next
      75              :       })
      76              :     })
      77              :   })
      78              : 
      79         2355 :   const selectedInputs = ref<LinearInput[]>([])
      80         2355 :   const selectedOutputs = ref<NodeId[]>([])
      81         2355 :   const hasOutputs = computed(() => !!selectedOutputs.value.length)
      82         2355 :   const hasNodes = computed(() => {
      83              :     // Nodes are not reactive, so trigger recomputation when workflow changes
      84          146 :     void workflowStore.activeWorkflow
      85          146 :     void mode.value
      86          146 :     const app = useApp()
      87          146 :     return app.isGraphReady && app.rootGraph.nodes.length > 0
      88              :   })
      89              : 
      90        18248 :   function pruneLinearData(data: Partial<LinearData> | undefined): {
      91              :     inputs: LinearInput[]
      92              :     outputs: NodeId[]
      93              :   } {
      94        18248 :     const rawInputs = data?.inputs ?? []
      95        18248 :     const rawOutputs = data?.outputs ?? []
      96        18248 :     const app = useApp()
      97        18248 :     const rootGraph = app.isGraphReady ? app.rootGraph : undefined
      98        18248 :     if (!rootGraph) {
      99            0 :       return {
     100              :         inputs: rawInputs,
     101              :         outputs: rawOutputs.flatMap((nodeId) => {
     102            0 :           const parsedNodeId = parseNodeId(nodeId)
     103            0 :           return parsedNodeId ? [parsedNodeId] : []
     104              :         })
     105              :       }
     106              :     }
     107        18248 :     return {
     108              :       inputs: rawInputs
     109              :         .map((input) => upgradeAndValidateInput(input, rootGraph))
     110              :         .filter((entry): entry is LinearInput => entry !== null),
     111              :       outputs: rawOutputs.flatMap((nodeId) => {
     112          652 :         const parsedNodeId = parseNodeId(nodeId)
     113          652 :         if (!parsedNodeId) return []
     114          652 :         return ChangeTracker.isLoadingGraph || resolveNode(parsedNodeId)
     115              :           ? [parsedNodeId]
     116              :           : []
     117              :       })
     118              :     }
     119              :   }
     120              : 
     121          926 :   function buildEntry(
     122              :     widgetId: WidgetId,
     123              :     name: string,
     124              :     config: InputWidgetConfig | undefined
     125              :   ): LinearInput {
     126          926 :     return config === undefined ? [widgetId, name] : [widgetId, name, config]
     127              :   }
     128              : 
     129          979 :   function upgradeAndValidateInput(
     130              :     input: LinearInput,
     131              :     rootGraph: ComfyApp['rootGraph']
     132              :   ): LinearInput | null {
     133          979 :     const [storedId, widgetName, config] = input
     134              : 
     135          979 :     if (typeof storedId === 'string' && isWidgetId(storedId)) {
     136              :       const widget = findWidgetByEntityId(rootGraph, storedId)
     137          881 :       if (widget) return buildEntry(storedId, widgetName, config)
     138          117 :       const { nodeId } = parseWidgetId(storedId)
     139          504 :       if (rootGraph.getNodeById(nodeId)) {
     140           64 :         return buildEntry(storedId, widgetName, config)
     141              :       }
     142           53 :       return null
     143              :     }
     144              : 
     145          979 :     if (typeof storedId === 'string' && storedId.includes(':')) {
     146            0 :       const [, widget] = resolveNodeWidget(storedId, widgetName)
     147            0 :       if (!widget?.widgetId) return null
     148            0 :       return buildEntry(widget.widgetId, widgetName, config)
     149              :     }
     150              : 
     151           98 :     const directNodeId = parseNodeId(storedId)
     152          979 :     const directNode = directNodeId ? rootGraph.getNodeById(directNodeId) : null
     153          979 :     const directWidget = directNode?.widgets?.find((w) => w.name === widgetName)
     154          979 :     if (directNode && directWidget) {
     155           98 :       const derivedId = getWidgetIdForNode(directNode, directWidget)
     156           98 :       if (derivedId) return buildEntry(derivedId, widgetName, config)
     157              :     }
     158              : 
     159            0 :     const matches: LinearInput[] = rootGraph.nodes.flatMap((node) => {
     160            0 :       if (!(node instanceof SubgraphNode)) return []
     161            0 :       return node.inputs.flatMap((inputSlot): LinearInput[] => {
     162            0 :         if (!inputSlot.widgetId) return []
     163            0 :         const target = resolveSubgraphInputTarget(node, inputSlot.name)
     164            0 :         if (
     165              :           target?.nodeId !== String(storedId) ||
     166              :           target.widgetName !== widgetName
     167              :         ) {
     168            0 :           return []
     169              :         }
     170            0 :         return [buildEntry(inputSlot.widgetId, inputSlot.name, config)]
     171              :       })
     172              :     })
     173            0 :     if (matches.length === 1) return matches[0]
     174            0 :     if (matches.length > 1) {
     175            0 :       console.warn(
     176              :         '[appModeStore] dropping ambiguous legacy selectedInput tuple',
     177              :         { storedId, widgetName }
     178              :       )
     179            0 :       return null
     180              :     }
     181              : 
     182            0 :     console.warn(
     183              :       '[appModeStore] dropping legacy selectedInput tuple — no canonical identity available',
     184              :       { storedId, widgetName }
     185              :     )
     186            0 :     return null
     187              :   }
     188              : 
     189         5502 :   function warnOnUninterpretableAppConfig(
     190              :     data: Partial<LinearData> | undefined,
     191              :     resolvedInputs: LinearInput[],
     192              :     resolvedOutputs: NodeId[]
     193              :   ) {
     194         5502 :     if (ChangeTracker.isLoadingGraph) return
     195              : 
     196           95 :     const app = useApp()
     197         5502 :     if (!app.isGraphReady || !app.rootGraph.nodes.length) return
     198              : 
     199              :     const hadConfig = !!(data?.inputs?.length || data?.outputs?.length)
     200         5502 :     if (!hadConfig || resolvedInputs.length || resolvedOutputs.length) return
     201              : 
     202            0 :     console.warn(
     203              :       '[appModeStore] app config could not be interpreted; no inputs or outputs resolved from linearData',
     204              :       {
     205              :         inputs: data.inputs,
     206              :         outputs: data.outputs
     207              :       }
     208              :     )
     209              :   }
     210              : 
     211         5502 :   function loadSelections(data: Partial<LinearData> | undefined) {
     212         5502 :     const { inputs, outputs } = pruneLinearData(data)
     213         5502 :     selectedInputs.value = inputs
     214         5502 :     selectedOutputs.value = outputs
     215         5502 :     warnOnUninterpretableAppConfig(data, inputs, outputs)
     216              :   }
     217              : 
     218         3960 :   function resetSelectedToWorkflow() {
     219         3960 :     const { activeWorkflow } = workflowStore
     220         3960 :     if (!activeWorkflow) return
     221              : 
     222              :     const source =
     223              :       activeWorkflow.changeTracker.activeState.extra?.linearData ??
     224              :       activeWorkflow.initialState.extra?.linearData
     225         3960 :     loadSelections(source)
     226              :   }
     227              : 
     228         2355 :   useEventListener(
     229              :     () => {
     230         4710 :       const app = useApp()
     231         4710 :       return app.isGraphReady ? app.rootGraph.events : undefined
     232              :     },
     233              :     'configured',
     234              :     resetSelectedToWorkflow
     235              :   )
     236              : 
     237         2355 :   watch(
     238              :     () =>
     239              :       isBuilderMode.value
     240              :         ? { inputs: selectedInputs.value, outputs: selectedOutputs.value }
     241              :         : null,
     242              :     (data) => {
     243          185 :       if (!data || ChangeTracker.isLoadingGraph) return
     244          185 :       if (!useApp().isGraphReady) return
     245              :       const graph = useApp().rootGraph
     246          152 :       const extra = graph.extra
     247          152 :       extra.linearData = {
     248              :         inputs: data.inputs.map(([id, name, config]): LinearInput =>
     249              :           config
     250              :             ? [
     251              :                 id,
     252              :                 name,
     253              :                 JSON.parse(JSON.stringify(config)) as InputWidgetConfig
     254              :               ]
     255              :             : [id, name]
     256              :         ),
     257              :         outputs: [...data.outputs]
     258              :       }
     259          185 :       workflowStore.activeWorkflow?.changeTracker.captureCanvasState()
     260              :     },
     261              :     { deep: true }
     262              :   )
     263              : 
     264         2355 :   let unwatchReadOnly: (() => void) | undefined
     265           92 :   function enforceReadOnly(inSelect: boolean) {
     266           92 :     const canvas = getCanvas()
     267           92 :     canvas.read_only = inSelect
     268           92 :     unwatchReadOnly?.()
     269           92 :     if (inSelect)
     270           59 :       unwatchReadOnly = watch(
     271              :         () => canvas.read_only,
     272              :         () => (canvas.read_only = true)
     273              :       )
     274              :   }
     275              : 
     276           92 :   function autoEnableVueNodes(inSelect: boolean) {
     277           92 :     if (!inSelect) return
     278           73 :     if (!settingStore.get('Comfy.VueNodes.Enabled')) {
     279           44 :       void settingStore.set('Comfy.VueNodes.Enabled', true)
     280              : 
     281           44 :       if (!settingStore.get('Comfy.AppBuilder.VueNodeSwitchDismissed')) {
     282            6 :         showVueNodeSwitchPopup.value = true
     283              :       }
     284              :     }
     285              :   }
     286              : 
     287         2355 :   watch(isSelectMode, (inSelect) => {
     288           92 :     enforceReadOnly(inSelect)
     289           92 :     autoEnableVueNodes(inSelect)
     290              :   })
     291              : 
     292           58 :   function enterBuilder() {
     293           58 :     resetSelectedToWorkflow()
     294              : 
     295           58 :     useSidebarTabStore().activeSidebarTabId = null
     296              : 
     297           58 :     setMode(
     298              :       mode.value === 'app' && hasOutputs.value
     299              :         ? 'builder:arrange'
     300              :         : 'builder:inputs'
     301              :     )
     302              :   }
     303              : 
     304           21 :   function exitBuilder() {
     305           21 :     resetSelectedToWorkflow()
     306           21 :     setMode('graph')
     307              :   }
     308              : 
     309            1 :   function removeSelectedInput(widget: IBaseWidget) {
     310            1 :     const targetEntityId = widget.widgetId
     311            1 :     if (!targetEntityId) return
     312            1 :     const index = selectedInputs.value.findIndex(
     313              :       ([id]) => id === targetEntityId
     314              :     )
     315            1 :     if (index !== -1) selectedInputs.value.splice(index, 1)
     316              :   }
     317              : 
     318            1 :   function updateInputConfig(widget: IBaseWidget, config: InputWidgetConfig) {
     319            1 :     const targetEntityId = widget.widgetId
     320            1 :     if (!targetEntityId) return
     321            1 :     const index = selectedInputs.value.findIndex(
     322              :       ([id]) => id === targetEntityId
     323              :     )
     324            1 :     if (index === -1) return
     325            1 :     const [id, type, options] = selectedInputs.value[index]
     326            1 :     selectedInputs.value.splice(index, 1, [id, type, { ...options, ...config }])
     327              :   }
     328              : 
     329         2355 :   return {
     330              :     enterBuilder,
     331              :     exitBuilder,
     332              :     hasNodes,
     333              :     hasOutputs,
     334              :     loadSelections,
     335              :     pruneLinearData,
     336              :     removeSelectedInput,
     337              :     resetSelectedToWorkflow,
     338              :     selectedInputs,
     339              :     selectedOutputs,
     340              :     updateInputConfig,
     341              :     showVueNodeSwitchPopup,
     342              :     viewMode,
     343              :     displayViewMode
     344              :   }
     345              : })
        

Generated by: LCOV version 2.0-1