11import { PermissionAction } from '@supabase/shared-types/out/constants'
2- import { useMemo , useState } from 'react'
2+ import { useEffect , useMemo , useState } from 'react'
33import ReactMarkdown from 'react-markdown'
44import { toast } from 'sonner'
55
@@ -38,6 +38,8 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
3838 const messageSlug = `MAILER_TEMPLATES_${ id } _CONTENT`
3939 const messageProperty = properties [ messageSlug ]
4040 const [ bodyValue , setBodyValue ] = useState ( ( authConfig && authConfig [ messageSlug ] ) ?? '' )
41+ const [ hasUnsavedChanges , setHasUnsavedChanges ] = useState ( false )
42+
4143 const onSubmit = ( values : any , { resetForm } : any ) => {
4244 const payload = { ...values }
4345
@@ -56,11 +58,27 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
5658 values : values ,
5759 initialValues : values ,
5860 } )
61+ setHasUnsavedChanges ( false ) // Reset the unsaved changes state
5962 } ,
6063 }
6164 )
6265 }
6366
67+ useEffect ( ( ) => {
68+ const handleBeforeUnload = ( e : BeforeUnloadEvent ) => {
69+ if ( hasUnsavedChanges ) {
70+ e . preventDefault ( )
71+ e . returnValue = '' // deprecated, but older browsers still require this
72+ }
73+ }
74+
75+ window . addEventListener ( 'beforeunload' , handleBeforeUnload )
76+
77+ return ( ) => {
78+ window . removeEventListener ( 'beforeunload' , handleBeforeUnload )
79+ }
80+ } , [ hasUnsavedChanges ] )
81+
6482 return (
6583 < Form id = { formId } className = "!border-t-0" initialValues = { INITIAL_VALUES } onSubmit = { onSubmit } >
6684 { ( { resetForm, values, initialValues } : any ) => {
@@ -135,7 +153,12 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
135153 language = "html"
136154 isReadOnly = { ! canUpdateConfig }
137155 className = "!mb-0 h-96 overflow-hidden rounded border"
138- onInputChange = { ( e : string | undefined ) => setBodyValue ( e ?? '' ) }
156+ onInputChange = { ( e : string | undefined ) => {
157+ setBodyValue ( e ?? '' )
158+ if ( bodyValue !== e ) {
159+ setHasUnsavedChanges ( true )
160+ }
161+ } }
139162 options = { { wordWrap : 'off' , contextmenu : false } }
140163 value = { bodyValue }
141164 />
0 commit comments