-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #123 from bcgov/feature/intake-from-autosave
Implemented autosave functionality for intake forms that utilize a save draft feature
- Loading branch information
Showing
3 changed files
with
99 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import { ref, onMounted, onBeforeUnmount } from 'vue'; | ||
|
||
import type { Ref } from 'vue'; | ||
|
||
// autosave functionality for forms, saves on inactivity after the delay (default 10 seconds) | ||
export function useAutoSave(saveCallback: () => void, delay: number = 10000) { | ||
const formUpdated: Ref<Boolean> = ref(false); | ||
let timeoutId: ReturnType<typeof setTimeout> | null = null; | ||
|
||
const startTimer = () => { | ||
if (timeoutId) { | ||
clearTimeout(timeoutId); | ||
} | ||
timeoutId = setTimeout(async () => { | ||
if (formUpdated.value) { | ||
await saveCallback(); | ||
formUpdated.value = false; | ||
timeoutId = null; | ||
} | ||
}, delay); | ||
}; | ||
|
||
const onActivity = () => { | ||
startTimer(); | ||
}; | ||
|
||
onMounted(() => { | ||
window.addEventListener('keydown', onActivity); | ||
window.addEventListener('focus', onActivity); | ||
window.addEventListener('click', onActivity); | ||
}); | ||
|
||
onBeforeUnmount(() => { | ||
window.removeEventListener('keydown', onActivity); | ||
window.removeEventListener('focus', onActivity); | ||
window.removeEventListener('click', onActivity); | ||
if (timeoutId) clearTimeout(timeoutId); | ||
}); | ||
|
||
return { | ||
formUpdated, | ||
stopAutoSave: () => { | ||
if (timeoutId) { | ||
clearTimeout(timeoutId); | ||
timeoutId = null; | ||
} | ||
} | ||
}; | ||
} |