Line data Source code
1 : import { computed, onUnmounted, watch } from 'vue'
2 :
3 : import { useSettingStore } from '@/platform/settings/settingStore'
4 : import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
5 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
6 : import { api } from '@/scripts/api'
7 :
8 2355 : export function useWorkflowAutoSave() {
9 2355 : const workflowStore = useWorkflowStore()
10 2355 : const settingStore = useSettingStore()
11 2355 : const workflowService = useWorkflowService()
12 :
13 : // Use computed refs to cache autosave settings
14 2355 : const autoSaveSetting = computed(() =>
15 : settingStore.get('Comfy.Workflow.AutoSave')
16 : )
17 2355 : const autoSaveDelay = computed(() =>
18 : settingStore.get('Comfy.Workflow.AutoSaveDelay')
19 : )
20 :
21 2355 : let autoSaveTimeout: NodeJS.Timeout | null = null
22 2355 : let isSaving = false
23 2355 : let needsAutoSave = false
24 :
25 2355 : const scheduleAutoSave = () => {
26 : // Clear any existing timeout
27 1589 : if (autoSaveTimeout) {
28 0 : clearTimeout(autoSaveTimeout)
29 0 : autoSaveTimeout = null
30 : }
31 :
32 : // If autosave is enabled
33 1589 : if (autoSaveSetting.value === 'after delay') {
34 : // If a save is in progress, mark that we need an autosave after saving
35 2 : if (isSaving) {
36 0 : needsAutoSave = true
37 0 : return
38 : }
39 2 : const delay = autoSaveDelay.value
40 2 : autoSaveTimeout = setTimeout(async () => {
41 2 : const activeWorkflow = workflowStore.activeWorkflow
42 2 : if (activeWorkflow?.isModified && activeWorkflow.isPersisted) {
43 2 : try {
44 2 : isSaving = true
45 2 : await workflowService.saveWorkflow(activeWorkflow)
46 : } catch (err) {
47 0 : console.error('Auto save failed:', err)
48 : } finally {
49 1 : isSaving = false
50 1 : if (needsAutoSave) {
51 0 : needsAutoSave = false
52 0 : scheduleAutoSave()
53 : }
54 : }
55 : }
56 : }, delay)
57 : }
58 : }
59 :
60 : // Watch for autosave setting changes
61 2355 : watch(
62 : autoSaveSetting,
63 : (newSetting) => {
64 : // Clear any existing timeout when settings change
65 4712 : if (autoSaveTimeout) {
66 0 : clearTimeout(autoSaveTimeout)
67 0 : autoSaveTimeout = null
68 : }
69 :
70 : // If there's an active modified workflow and autosave is enabled, schedule a save
71 4712 : if (
72 : newSetting === 'after delay' &&
73 : workflowStore.activeWorkflow?.isModified
74 : ) {
75 0 : scheduleAutoSave()
76 : }
77 : },
78 : { immediate: true }
79 : )
80 :
81 : // Listen for graph changes and schedule autosave when they occur
82 2355 : const onGraphChanged = () => {
83 1589 : scheduleAutoSave()
84 : }
85 :
86 2355 : api.addEventListener('graphChanged', onGraphChanged)
87 :
88 2355 : onUnmounted(() => {
89 0 : if (autoSaveTimeout) {
90 0 : clearTimeout(autoSaveTimeout)
91 0 : autoSaveTimeout = null
92 : }
93 0 : api.removeEventListener('graphChanged', onGraphChanged)
94 : })
95 : }
|