|
| 1 | +import { isHeadlessEnv, isVSCodeEnv } from '#common/utils/env.utils.ts'; |
| 2 | +import { sendToExtension } from '#common/utils/vscode-bridge.utils.ts'; |
| 3 | +import { useCanvasContext } from '#core/providers'; |
| 4 | +import { APP_MESSAGE_TYPE } from '@lemoncode/quickmock-bridge-protocol'; |
| 5 | +import { useEffect, useRef } from 'react'; |
| 6 | +import { serializeDocument } from './vscode-sync.utils'; |
| 7 | + |
| 8 | +const AUTO_SAVE_DEBOUNCE_MS = 500; |
| 9 | + |
| 10 | +export function useVSCodeAutoSave(hasReceivedFileRef: { |
| 11 | + current: boolean; |
| 12 | +}): void { |
| 13 | + const { fullDocument, howManyLoadedDocuments } = useCanvasContext(); |
| 14 | + |
| 15 | + const prevLoadCountRef = useRef(howManyLoadedDocuments); |
| 16 | + const lastSavedContentRef = useRef(''); |
| 17 | + const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 18 | + |
| 19 | + useEffect(() => { |
| 20 | + if (!isVSCodeEnv() || isHeadlessEnv() || !hasReceivedFileRef.current) |
| 21 | + return; |
| 22 | + |
| 23 | + if (prevLoadCountRef.current !== howManyLoadedDocuments) { |
| 24 | + prevLoadCountRef.current = howManyLoadedDocuments; |
| 25 | + lastSavedContentRef.current = serializeDocument(fullDocument); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + const content = serializeDocument(fullDocument); |
| 30 | + |
| 31 | + if (content === lastSavedContentRef.current) return; |
| 32 | + |
| 33 | + debounceTimerRef.current = setTimeout(() => { |
| 34 | + sendToExtension({ |
| 35 | + type: APP_MESSAGE_TYPE.SAVE, |
| 36 | + payload: { content }, |
| 37 | + }); |
| 38 | + lastSavedContentRef.current = content; |
| 39 | + debounceTimerRef.current = null; |
| 40 | + }, AUTO_SAVE_DEBOUNCE_MS); |
| 41 | + |
| 42 | + return () => { |
| 43 | + if (debounceTimerRef.current !== null) { |
| 44 | + clearTimeout(debounceTimerRef.current); |
| 45 | + debounceTimerRef.current = null; |
| 46 | + } |
| 47 | + }; |
| 48 | + }, [fullDocument, howManyLoadedDocuments]); |
| 49 | +} |
0 commit comments