// Composable for tracking unsaved changes and preventing accidental data loss export const useUnsavedChanges = () => { const isDirty = ref(false) const lastSavedData = ref(null) const currentData = ref(null) // Track changes by comparing current data with last saved data const trackChanges = (newData: any) => { currentData.value = JSON.stringify(newData) if (lastSavedData.value && currentData.value !== lastSavedData.value) { isDirty.value = true } else if (!lastSavedData.value) { isDirty.value = true } } // Mark data as saved const markAsSaved = (data: any) => { lastSavedData.value = JSON.stringify(data) currentData.value = lastSavedData.value isDirty.value = false } // Reset dirty state const resetDirty = () => { isDirty.value = false lastSavedData.value = currentData.value } // Warning before leaving page const beforeUnloadHandler = (event: BeforeUnloadEvent) => { if (isDirty.value) { event.preventDefault() event.returnValue = 'У вас есть несохраненные изменения. Вы уверены, что хотите уйти?' return event.returnValue } } // Setup warning on mount onMounted(() => { window.addEventListener('beforeunload', beforeUnloadHandler) }) // Cleanup on unmount onUnmounted(() => { window.removeEventListener('beforeunload', beforeUnloadHandler) }) return { isDirty: readonly(isDirty), trackChanges, markAsSaved, resetDirty } }