import { AnyJson, AnyStore } from '~/types/interfaces' /** * @category Use/form * @class UseDirtyForm * Use Classe pour gérer l'apparition de message si le formulaire est dirty */ export class UseDirtyForm { private store: AnyStore private readonly handler: any constructor (handler: any, store: AnyStore) { this.store = store this.handler = handler } /** * Composition function */ public invoke (): AnyJson { return { markFormAsDirty: () => this.markAsDirty(), markFormAsNotDirty: () => this.markAsNotDirty() } } /** * définit le formulaire comme Dirty (modifié) */ private markAsDirty () { this.store.commit('form/setDirty', true) this.addEventListener() } /** * Définit le formulaire comme non dirty (non modifié) */ private markAsNotDirty () { this.store.commit('form/setDirty', false) this.clearEventListener() } /** * Ajoute un Event avant le départ de la page */ private addEventListener () { if (process.browser) { window.addEventListener('beforeunload', this.handler) } } /** * Supprime l'Event avant le départ de la page */ private clearEventListener () { if (process.browser) { window.removeEventListener('beforeunload', this.handler) } } } function getEventHandler () { return function (e: any) { // Cancel the event e.preventDefault() // Chrome requires returnValue to be set e.returnValue = '' } } const handler = getEventHandler() export const $useDirtyForm = (store: AnyStore) => new UseDirtyForm(handler, store).invoke()