useForm.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { AnyJson, AnyStore } from '~/types/interfaces'
  2. import {computed, ComputedRef, useContext} from "@nuxtjs/composition-api";
  3. /**
  4. * @category composables/form
  5. * @class UseDirtyForm
  6. * Use Classe pour gérer l'apparition de message si le formulaire est dirty
  7. */
  8. export class UseForm {
  9. private store: AnyStore
  10. private readonly handler: any
  11. constructor () {
  12. const {store} = useContext()
  13. this.store = store
  14. this.handler = getEventHandler()
  15. }
  16. /**
  17. * Composition function
  18. */
  19. public invoke (): AnyJson {
  20. const readonly: ComputedRef<boolean> = computed(() => {
  21. return this.store.state.form.readonly
  22. })
  23. return {
  24. markFormAsDirty: () => this.markAsDirty(),
  25. markFormAsNotDirty: () => this.markAsNotDirty(),
  26. readonly
  27. }
  28. }
  29. /**
  30. * définit le formulaire comme Dirty (modifié)
  31. */
  32. private markAsDirty () {
  33. this.store.commit('form/setDirty', true)
  34. this.addEventListener()
  35. }
  36. /**
  37. * Définit le formulaire comme non dirty (non modifié)
  38. */
  39. private markAsNotDirty () {
  40. this.store.commit('form/setDirty', false)
  41. this.clearEventListener()
  42. }
  43. /**
  44. * Ajoute un Event avant le départ de la page
  45. */
  46. private addEventListener () {
  47. if (process.browser) {
  48. window.addEventListener('beforeunload', this.handler)
  49. }
  50. }
  51. /**
  52. * Supprime l'Event avant le départ de la page
  53. */
  54. private clearEventListener () {
  55. if (process.browser) {
  56. window.removeEventListener('beforeunload', this.handler)
  57. }
  58. }
  59. }
  60. function getEventHandler () {
  61. return function (e: any) {
  62. // Cancel the event
  63. e.preventDefault()
  64. // Chrome requires returnValue to be set
  65. e.returnValue = ''
  66. }
  67. }
  68. export const $useForm = () => new UseForm().invoke()