| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456 |
- <!--
- Formulaire générique
- Assure la validation des données, les actions de base (enregistrement, annulation, ...), et la confirmation avant
- de quitter si des données ont été modifiées.
- @see https://vuetifyjs.com/en/components/forms/#usage
- -->
- <template>
- <LayoutContainer>
- <v-form
- ref="form"
- v-model="isValid"
- :readonly="readonly"
- @submit.prevent=""
- >
- <!-- Top action bar -->
- <v-container
- v-if="actionPosition === 'both' || actionPosition === 'top'"
- :fluid="true"
- class="container btnActions"
- >
- <v-row>
- <v-col cols="12" sm="12">
- <slot name="form.button" />
- <UiButtonSubmit
- v-if="!readonly"
- :actions="actions"
- :validation-pending="validationPending || !isValid"
- @submit="submit"
- />
- </v-col>
- </v-row>
- </v-container>
- <div v-else class="mt-6" />
- <!-- Content -->
- <slot v-bind="{ modelValue }" />
- <!-- Bottom action bar -->
- <v-container
- v-if="actionPosition === 'both' || actionPosition === 'bottom'"
- :fluid="true"
- class="container btnActions"
- >
- <v-row>
- <v-col cols="12" sm="12">
- <slot name="form.button" />
- <UiButtonSubmit
- :validation-pending="validationPending || !isValid"
- :actions="actions"
- @submit="submit"
- />
- </v-col>
- </v-row>
- </v-container>
- </v-form>
- <!-- Confirmation dialog -->
- <LazyLayoutDialog :show="isConfirmationDialogShowing" :max-width="1000">
- <template #dialogText>
- <v-card-title class="text-h5 theme-neutral">
- {{ $t('caution') }}
- </v-card-title>
- <v-card-text>
- <br >
- <p>{{ $t('quit_without_saving_warning') }}.</p>
- </v-card-text>
- </template>
- <template #dialogBtn>
- <div class="confirmation-dlg-actions">
- <v-btn class="theme-neutral" @click="closeConfirmationDialog">
- {{ $t('cancel') }}
- </v-btn>
- <v-btn class="theme-danger" @click="cancel">
- {{ $t('quit_with_no_saving') }}
- </v-btn>
- <v-btn class="theme-primary" @click="saveAndQuit">
- {{ $t('save_and_quit') }}
- </v-btn>
- </div>
- </template>
- </LazyLayoutDialog>
- </LayoutContainer>
- </template>
- <script setup lang="ts">
- import { computed, ref, watch } from 'vue'
- import type { ComputedRef, Ref, PropType } from 'vue'
- import type { RouteLocationNormalized, RouteLocationRaw } from 'vue-router'
- import * as _ from 'lodash-es'
- import { FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT } from '~/types/enum/enums'
- import { useFormStore } from '~/stores/form'
- import { useEntityManager } from '~/composables/data/useEntityManager'
- import type ApiModel from '~/models/ApiModel'
- import { usePageStore } from '~/stores/page'
- import type { AnyJson } from '~/types/data'
- import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
- const props = defineProps({
- /**
- * Instance de l'ApiModel
- */
- modelValue: {
- type: Object as () => ApiModel,
- required: true,
- },
- /**
- * TODO: compléter
- */
- onChanged: {
- type: Function,
- required: false,
- default: null,
- },
- goBackRoute: {
- type: Object as PropType<RouteLocationRaw>,
- required: false,
- default: null,
- },
- /**
- * Types de soumission disponibles (enregistrer / enregistrer et quitter)
- */
- submitActions: {
- type: Object,
- required: false,
- default: () => {
- const actions: AnyJson = {}
- actions[SUBMIT_TYPE.SAVE] = {}
- return actions
- },
- },
- /**
- * La validation est en cours
- */
- validationPending: {
- type: Boolean,
- required: false,
- default: false,
- },
- /**
- * Faut-il rafraichir le profil à la soumission du formulaire?
- */
- refreshProfile: {
- type: Boolean,
- required: false,
- default: false,
- },
- actionPosition: {
- type: String as PropType<'top' | 'bottom' | 'both'>,
- required: false,
- default: 'bottom',
- },
- })
- // ### Définitions
- const i18n = useI18n()
- const router = useRouter()
- const { em } = useEntityManager()
- const { refreshProfile } = useRefreshProfile()
- // Le formulaire est-il valide
- const isValid: Ref<boolean> = ref(true)
- // Erreurs de validation
- const errors: Ref<Array<string>> = ref([])
- // Référence au component v-form
- const form: Ref = ref(null)
- const formStore = useFormStore()
- // Le formulaire est-il en lecture seule
- const readonly: ComputedRef<boolean> = computed(() => {
- return formStore.readonly
- })
- /**
- * Si l'utilisateur veut quitter le formulaire sans enregistrer ses modifications,
- * on affiche la fenêtre de confirmation. En attendant, on garde en mémoire la route qu'il
- * voulait suivre au cas où il confirmerait.
- */
- const requestedLeavingRoute: Ref<RouteLocationNormalized | null> = ref(null)
- // La fenêtre de confirmation est-elle affichée
- const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
- return formStore.showConfirmToLeave
- })
- /**
- * Ferme la fenêtre de confirmation
- */
- const closeConfirmationDialog = () => {
- requestedLeavingRoute.value = null
- formStore.setShowConfirmToLeave(false)
- }
- const emit = defineEmits(['update:model-value'])
- // ### Actions du formulaire
- /**
- * Soumet le formulaire
- *
- * @param next
- */
- const submit = async (next: string | null = null) => {
- if (props.validationPending) {
- return
- }
- // Valide les données
- await validate()
- if (!isValid.value) {
- usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
- return
- }
- try {
- usePageStore().loading = true
- const updatedEntity = await em.persist(props.modelValue)
- emit('update:model-value', updatedEntity)
- if (props.refreshProfile) {
- await refreshProfile()
- }
- usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
- // On retire l'état 'dirty'
- setIsDirty(false)
- const actionArgs = next ? props.submitActions[next] : null
- if (next === SUBMIT_TYPE.SAVE) {
- onSaveAction(actionArgs, updatedEntity.id)
- } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
- onSaveAndQuitAction(actionArgs)
- }
- } catch (error: any) {
- if (
- error.response &&
- error.response.status === 422 &&
- error.response.data.violations
- ) {
- // TODO: à revoir
- const violations: Array<string> = []
- let fields: AnyJson = {}
- for (const violation of error.response.data.violations) {
- violations.push(i18n.t(violation.message) as string)
- fields = Object.assign(fields, {
- [violation.propertyPath]: violation.message,
- })
- }
- formStore.addViolation(fields)
- usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
- } else {
- throw error
- }
- } finally {
- usePageStore().loading = false
- }
- }
- /**
- * Enregistre et quitte
- */
- const saveAndQuit = async () => {
- await submit()
- cancel()
- }
- /**
- * Après l'action Sauvegarder
- *
- * Si on était en mode édition, on reste sur cette page (on ne fait rien).
- * Si on était en mode création, on bascule sur le mode édition
- *
- * @param route
- * @param id
- */
- function onSaveAction(route: Route, id: number) {
- if (formStore.formFunction === FORM_FUNCTION.CREATE) {
- route.path += id
- navigateTo(route)
- }
- }
- /**
- * Après l'action Sauvegarder et Quitter
- *
- * On redirige vers la route donnée
- *
- * @param route
- */
- function onSaveAndQuitAction(route: Route) {
- navigateTo(route)
- }
- /**
- * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
- */
- onBeforeRouteLeave(
- (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
- if (formStore.dirty === true) {
- requestedLeavingRoute.value = to
- formStore.setShowConfirmToLeave(true)
- return false
- }
- return true
- },
- )
- onMounted(() => {
- window.addEventListener('beforeunload', (event) => {
- if (formStore.dirty === true) {
- event.returnValue = i18n.t('quit_without_saving_warning')
- }
- })
- })
- /**
- * Quitte le formulaire sans enregistrer
- */
- const cancel = () => {
- setIsDirty(false)
- formStore.setShowConfirmToLeave(false)
- em.reset(props.modelValue)
- if (requestedLeavingRoute.value !== null) {
- navigateTo(requestedLeavingRoute.value)
- } else if (formStore.goAfterLeave !== null) {
- router.push(formStore.goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
- }
- }
- const actions = computed(() => {
- return _.keys(props.submitActions)
- })
- // #### Validation et store
- /**
- * Update store when form is changed (if valid)
- */
- const onFormChange = async () => {
- if (isValid.value) {
- em.save(props.modelValue)
- setIsDirty(true)
- if (props.onChanged) {
- // Execute the custom onChange method, if defined
- // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
- props.onChanged()
- }
- }
- }
- /**
- * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
- *
- * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
- */
- const validate = async function () {
- const validation = await form.value.validate()
- isValid.value = validation.valid
- errors.value = validation.errors
- }
- // #### Gestion de l'état dirty
- watch(props.modelValue, async (newEntity, oldEntity) => {
- setIsDirty(true)
- })
- /**
- * Handle events if the form is dirty to prevent submission
- * @param e
- */
- // TODO: voir si encore nécessaire avec le @submit.prevent
- const preventSubmit = (e: any) => {
- // Cancel the event
- e.preventDefault()
- // Chrome requires returnValue to be set
- e.returnValue = ''
- }
- /**
- * Applique ou retire l'état dirty (modifié) du formulaire
- */
- const setIsDirty = (dirty: boolean) => {
- formStore.setDirty(dirty)
- }
- defineExpose({ validate })
- </script>
- <style scoped>
- .btnActions {
- text-align: right;
- @media (max-width: 600px) {
- :deep(.v-col-12) {
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- width: 100%;
- .v-btn {
- margin: 12px 0 !important;
- max-width: 250px;
- }
- }
- }
- }
- .confirmation-dlg-actions {
- display: flex;
- flex-direction: row;
- }
- .confirmation-dlg-actions .v-btn {
- min-width: 255px;
- max-width: 255px;
- margin: 0 8px;
- font-size: 13px;
- font-weight: 600;
- }
- @media (max-width: 960px) {
- .confirmation-dlg-actions {
- width: 100%;
- flex-direction: column;
- align-items: center;
- }
- .confirmation-dlg-actions .v-btn {
- min-width: 80%;
- max-width: 80%;
- margin: 6px 0 !important;
- }
- }
- </style>
|