Add unsaved changes warning modal in Form Builder

- Implemented a modal to warn users about unsaved changes when navigating away from the form builder.
- Added computed properties and methods to manage unsaved changes state and navigation confirmation.
- Updated the form management page to include unsaved changes handling when creating new forms.
- Enhanced the form store to track unsaved changes status, ensuring better user experience and data integrity.
This commit is contained in:
Md Afiq Iskandar 2025-04-15 10:21:18 +08:00
parent 63a7d0f870
commit 103663b66b
3 changed files with 300 additions and 90 deletions

View File

@ -22,7 +22,7 @@
type="text" type="text"
name="formName" name="formName"
placeholder="Form Name" placeholder="Form Name"
v-model="formStore.formName" v-model="formName"
validation="required" validation="required"
validation-visibility="live" validation-visibility="live"
:validation-messages="{ required: 'Please enter a form name' }" :validation-messages="{ required: 'Please enter a form name' }"
@ -151,6 +151,29 @@
</div> </div>
<template #footer> </template> <template #footer> </template>
</RsModal> </RsModal>
<!-- Unsaved Changes Modal -->
<RsModal v-model="showUnsavedChangesModal" title="Unsaved Changes" size="md" position="center">
<div class="p-4">
<div class="flex items-center mb-4">
<Icon name="material-symbols:warning-outline" class="text-yellow-500 w-8 h-8 mr-3" />
<div>
<h3 class="font-medium text-lg">You have unsaved changes</h3>
<p class="text-gray-600">Are you sure you want to leave? Your changes will be lost.</p>
</div>
</div>
</div>
<template #footer>
<div class="flex justify-end gap-2">
<RsButton @click="cancelNavigation" variant="tertiary">
Stay
</RsButton>
<RsButton @click="confirmNavigation" variant="danger">
Leave
</RsButton>
</div>
</template>
</RsModal>
</div> </div>
</template> </template>
@ -169,12 +192,80 @@ const router = useRouter();
const formStore = useFormBuilderStore(); const formStore = useFormBuilderStore();
const toast = useToast(); const toast = useToast();
const showPreview = ref(false);
const showUnsavedChangesModal = ref(false);
const pendingNavigation = ref(null);
const navigationTarget = ref(null);
const navigationConfirmed = ref(false);
// Computed property for form name with getter and setter
const formName = computed({
get: () => formStore.formName,
set: (value) => {
if (value !== formStore.formName) {
formStore.setFormName(value);
}
}
});
// Initialize the form builder // Initialize the form builder
onMounted(() => { onMounted(() => {
formStore.loadSavedForms(); formStore.loadSavedForms();
// Add the beforeunload event listener
window.addEventListener('beforeunload', handleBeforeUnload);
}); });
const showPreview = ref(false); onUnmounted(() => {
// Remove the beforeunload event listener
window.removeEventListener('beforeunload', handleBeforeUnload);
});
// Show warning if there are unsaved changes
const handleBeforeUnload = (event) => {
if (formStore.hasUnsavedChanges) {
event.preventDefault();
event.returnValue = '';
return '';
}
};
// Navigation guards
// Add navigation guard
onBeforeRouteLeave((to, from, next) => {
// If navigation was already confirmed or there are no unsaved changes, proceed
if (navigationConfirmed.value || !formStore.hasUnsavedChanges) {
next();
return;
}
// Otherwise show the confirmation modal
showUnsavedChangesModal.value = true;
pendingNavigation.value = () => {
navigationConfirmed.value = true;
next();
};
next(false);
});
// Navigation handlers
const cancelNavigation = () => {
showUnsavedChangesModal.value = false;
pendingNavigation.value = null;
navigationTarget.value = null;
navigationConfirmed.value = false;
};
const confirmNavigation = () => {
showUnsavedChangesModal.value = false;
if (pendingNavigation.value) {
pendingNavigation.value();
} else if (navigationTarget.value) {
navigationConfirmed.value = true; // Mark as confirmed before navigating
router.push(navigationTarget.value);
}
};
// Handler methods // Handler methods
const handleAddComponent = (component) => { const handleAddComponent = (component) => {
@ -242,11 +333,19 @@ const handlePreviewSubmit = (formData) => {
}; };
const navigateToManage = () => { const navigateToManage = () => {
router.push("/form-builder/manage"); // If already confirmed or no unsaved changes, navigate directly
if (navigationConfirmed.value || !formStore.hasUnsavedChanges) {
router.push("/form-builder/manage");
return;
}
// Otherwise show confirmation modal
showUnsavedChangesModal.value = true;
navigationTarget.value = "/form-builder/manage";
}; };
const handleOptimizeLayout = () => { const handleOptimizeLayout = () => {
// Implementation of handleOptimizeLayout method formStore.optimizeGridLayout();
}; };
</script> </script>

View File

@ -1,85 +1,154 @@
<template> <template>
<div class="flex flex-col h-screen bg-gray-50"> <div>
<!-- Header --> <div class="flex flex-col h-screen bg-gray-50">
<header class="bg-gray-800 p-2 flex flex-wrap items-center justify-between text-white"> <!-- Header -->
<div class="flex items-center mb-2 sm:mb-0 gap-4"> <header
<Icon class="bg-gray-800 p-2 flex flex-wrap items-center justify-between text-white"
@click="navigateTo('/', { external: true })" >
name="ph:arrow-circle-left-duotone" <div class="flex items-center mb-2 sm:mb-0 gap-4">
class="cursor-pointer w-6 h-6" <Icon
/> @click="navigateTo('/', { external: true })"
<img src="@/assets/img/logo/logo-word-white.svg" alt="Corrad Logo" class="h-8 block mr-2" /> name="ph:arrow-circle-left-duotone"
</div> class="cursor-pointer w-6 h-6"
<div class="flex flex-wrap items-center space-x-2"> />
<RsButton @click="navigateToBuilder" variant="primary" class="mr-2"> <img
<Icon name="material-symbols:add" class="mr-2" /> src="@/assets/img/logo/logo-word-white.svg"
Create New Form alt="Corrad Logo"
</RsButton> class="h-8 block mr-2"
<h1 class="text-lg font-semibold">Manage Forms</h1> />
</div> </div>
</header> <div class="flex flex-wrap items-center space-x-2">
<RsButton @click="navigateToBuilder" variant="primary" class="mr-2">
<Icon name="material-symbols:add" class="mr-2" />
Create New Form
</RsButton>
<h1 class="text-lg font-semibold">Manage Forms</h1>
</div>
</header>
<!-- Main content --> <!-- Main content -->
<div class="flex-1 overflow-auto p-6"> <div class="flex-1 overflow-auto p-6">
<div class="container mx-auto"> <div class="container mx-auto">
<!-- Search bar --> <!-- Search bar -->
<div class="bg-white p-4 rounded-lg shadow-sm mb-6"> <div class="bg-white p-4 rounded-lg shadow-sm mb-6">
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4"> <div
<h2 class="text-xl font-medium">Saved Forms</h2> class="flex flex-col md:flex-row md:items-center md:justify-between gap-4"
<div class="relative w-full md:w-64"> >
<input <h2 class="text-xl font-medium">Saved Forms</h2>
type="text" <div class="relative w-full md:w-64">
v-model="searchQuery" <input
placeholder="Search forms..." type="text"
class="w-full px-3 py-2 pl-9 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" v-model="searchQuery"
/> placeholder="Search forms..."
<Icon name="material-symbols:search" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" /> class="w-full px-3 py-2 pl-9 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<Icon
name="material-symbols:search"
class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400"
/>
</div>
</div> </div>
</div> </div>
</div>
<!-- Forms list -->
<!-- Forms list --> <div class="bg-white rounded-lg shadow-sm">
<div class="bg-white rounded-lg shadow-sm"> <div
<div v-if="formStore.savedForms.length === 0" class="text-center py-16 text-gray-500"> v-if="formStore.savedForms.length === 0"
<Icon name="material-symbols:file-copy-outline" class="w-16 h-16 mx-auto mb-4" /> class="text-center py-16 text-gray-500"
<p class="text-lg font-medium">No forms found</p>
<p class="text-sm mb-4">Start by creating a new form</p>
<RsButton @click="navigateToBuilder" variant="primary">Create Form</RsButton>
</div>
<div v-else>
<RsTable
:field="['Form Name', 'Created', 'Actions']"
:data="filteredForms"
:options="{ striped: true, hover: true }"
:optionsAdvanced="{ sortable: true, responsive: true }"
> >
<template #cell-2="{ row, index }"> <Icon
<div class="flex space-x-2 justify-end"> name="material-symbols:file-copy-outline"
<RsButton @click="editForm(row.id)" size="sm" variant="tertiary"> class="w-16 h-16 mx-auto mb-4"
<template #prepend> />
<Icon name="material-symbols:edit-outline" class="w-4 h-4" /> <p class="text-lg font-medium">No forms found</p>
</template> <p class="text-sm mb-4">Start by creating a new form</p>
Edit <RsButton @click="navigateToBuilder" variant="primary"
</RsButton> >Create Form</RsButton
<RsButton @click="deleteForm(row.id)" size="sm" variant="tertiary" class="text-red-500"> >
<template #prepend> </div>
<Icon name="material-symbols:delete-outline" class="w-4 h-4" />
</template> <div v-else>
Delete <RsTable
</RsButton> :field="['Form Name', 'Created', 'Actions']"
</div> :data="filteredForms"
</template> :options="{ striped: true, hover: true }"
</RsTable> :optionsAdvanced="{ sortable: true, responsive: true }"
>
<template #cell-2="{ row, index }">
<div class="flex space-x-2 justify-end">
<RsButton
@click="editForm(row.id)"
size="sm"
variant="tertiary"
>
<template #prepend>
<Icon
name="material-symbols:edit-outline"
class="w-4 h-4"
/>
</template>
Edit
</RsButton>
<RsButton
@click="deleteForm(row.id)"
size="sm"
variant="tertiary"
class="text-red-500"
>
<template #prepend>
<Icon
name="material-symbols:delete-outline"
class="w-4 h-4"
/>
</template>
Delete
</RsButton>
</div>
</template>
</RsTable>
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- Unsaved Changes Modal -->
<RsModal
v-model="showUnsavedChangesModal"
title="Unsaved Changes"
size="md"
>
<div class="p-4">
<div class="flex items-center mb-4">
<Icon
name="material-symbols:warning-outline"
class="text-yellow-500 w-8 h-8 mr-3"
/>
<div>
<h3 class="font-medium text-lg">You have unsaved changes</h3>
<p class="text-gray-600">
Are you sure you want to create a new form? Your unsaved changes
will be lost.
</p>
</div>
</div>
</div>
<template #footer>
<div class="flex justify-end gap-2">
<RsButton @click="cancelNavigation" variant="tertiary">
Cancel
</RsButton>
<RsButton @click="confirmNavigation" variant="danger">
Create New Form
</RsButton>
</div>
</template>
</RsModal>
</div> </div>
</template> </template>
<script setup> <script setup>
import { useFormBuilderStore } from '~/stores/formBuilder'; import { useFormBuilderStore } from "~/stores/formBuilder";
definePageMeta({ definePageMeta({
title: "Manage Forms", title: "Manage Forms",
@ -92,7 +161,8 @@ definePageMeta({
const router = useRouter(); const router = useRouter();
const formStore = useFormBuilderStore(); const formStore = useFormBuilderStore();
const toast = useToast(); const toast = useToast();
const searchQuery = ref(''); const searchQuery = ref("");
const showUnsavedChangesModal = ref(false);
// Initialize and load forms // Initialize and load forms
onMounted(() => { onMounted(() => {
@ -102,45 +172,60 @@ onMounted(() => {
// Format date for display // Format date for display
const formatDate = (dateString) => { const formatDate = (dateString) => {
const date = new Date(dateString); const date = new Date(dateString);
return date.toLocaleDateString('en-US', { return date.toLocaleDateString("en-US", {
year: 'numeric', year: "numeric",
month: 'short', month: "short",
day: 'numeric' day: "numeric",
}); });
}; };
// Filtered and formatted forms for table display // Filtered and formatted forms for table display
const filteredForms = computed(() => { const filteredForms = computed(() => {
return formStore.savedForms return formStore.savedForms
.filter(form => { .filter((form) => {
if (!searchQuery.value) return true; if (!searchQuery.value) return true;
return form.name.toLowerCase().includes(searchQuery.value.toLowerCase()); return form.name.toLowerCase().includes(searchQuery.value.toLowerCase());
}) })
.map(form => ({ .map((form) => ({
id: form.id, id: form.id,
'Form Name': form.name, "Form Name": form.name,
'Created': formatDate(form.createdAt) Created: formatDate(form.createdAt),
})); }));
}); });
// Navigation and action handlers // Navigation and action handlers
const navigateToBuilder = () => { const navigateToBuilder = () => {
router.push('/form-builder'); if (formStore.hasUnsavedChanges) {
showUnsavedChangesModal.value = true;
} else {
formStore.clearForm();
router.push("/form-builder");
}
};
const cancelNavigation = () => {
showUnsavedChangesModal.value = false;
};
const confirmNavigation = () => {
showUnsavedChangesModal.value = false;
formStore.clearForm();
router.push("/form-builder");
}; };
const editForm = (formId) => { const editForm = (formId) => {
formStore.loadForm(formId); formStore.loadForm(formId);
router.push('/form-builder'); router.push("/form-builder");
}; };
const deleteForm = (formId) => { const deleteForm = (formId) => {
if (confirm('Are you sure you want to delete this form?')) { if (confirm("Are you sure you want to delete this form?")) {
const index = formStore.savedForms.findIndex(f => f.id === formId); const index = formStore.savedForms.findIndex((f) => f.id === formId);
if (index !== -1) { if (index !== -1) {
formStore.savedForms.splice(index, 1); formStore.savedForms.splice(index, 1);
localStorage.setItem('savedForms', JSON.stringify(formStore.savedForms)); localStorage.setItem("savedForms", JSON.stringify(formStore.savedForms));
toast.success('Form deleted successfully'); toast.success("Form deleted successfully");
} }
} }
}; };
</script> </script>

View File

@ -8,7 +8,8 @@ export const useFormBuilderStore = defineStore('formBuilder', {
formName: 'New Form', formName: 'New Form',
formDescription: '', formDescription: '',
isDraggingOver: false, isDraggingOver: false,
savedForms: [] savedForms: [],
hasUnsavedChanges: false
}), }),
getters: { getters: {
@ -51,6 +52,7 @@ export const useFormBuilderStore = defineStore('formBuilder', {
this.formComponents.push(newComponent); this.formComponents.push(newComponent);
this.selectComponent(newComponent.id); this.selectComponent(newComponent.id);
this.hasUnsavedChanges = true;
}, },
// Find optimal placement for a new component in the grid // Find optimal placement for a new component in the grid
@ -142,6 +144,7 @@ export const useFormBuilderStore = defineStore('formBuilder', {
const index = this.formComponents.findIndex(c => c.id === updatedComponent.id); const index = this.formComponents.findIndex(c => c.id === updatedComponent.id);
if (index !== -1) { if (index !== -1) {
this.formComponents[index] = JSON.parse(JSON.stringify(updatedComponent)); this.formComponents[index] = JSON.parse(JSON.stringify(updatedComponent));
this.hasUnsavedChanges = true;
} }
}, },
@ -152,6 +155,7 @@ export const useFormBuilderStore = defineStore('formBuilder', {
// Optimize layout after reordering // Optimize layout after reordering
this.optimizeGridLayout(); this.optimizeGridLayout();
this.hasUnsavedChanges = true;
} }
}, },
@ -172,6 +176,7 @@ export const useFormBuilderStore = defineStore('formBuilder', {
// Optimize layout after deletion // Optimize layout after deletion
this.optimizeGridLayout(); this.optimizeGridLayout();
this.hasUnsavedChanges = true;
} }
}, },
@ -193,6 +198,8 @@ export const useFormBuilderStore = defineStore('formBuilder', {
// Save to localStorage for persistence // Save to localStorage for persistence
localStorage.setItem('savedForms', JSON.stringify(this.savedForms)); localStorage.setItem('savedForms', JSON.stringify(this.savedForms));
this.hasUnsavedChanges = false;
return formData; return formData;
}, },
@ -211,11 +218,30 @@ export const useFormBuilderStore = defineStore('formBuilder', {
} }
}, },
setFormName(name) {
if (this.formName !== name) {
this.formName = name;
this.hasUnsavedChanges = true;
}
},
setFormDescription(description) {
if (this.formDescription !== description) {
this.formDescription = description;
this.hasUnsavedChanges = true;
}
},
resetUnsavedChanges() {
this.hasUnsavedChanges = false;
},
clearForm() { clearForm() {
this.formComponents = []; this.formComponents = [];
this.selectedComponentId = null; this.selectedComponentId = null;
this.formName = 'New Form'; this.formName = 'New Form';
this.formDescription = ''; this.formDescription = '';
this.hasUnsavedChanges = false;
}, },
loadSavedForms() { loadSavedForms() {