refactor(former): 🔄 restructure form components and stores
* Remove unused FormLayout and SuperForm stores. * Consolidate form logic into Former component. * Implement new Former layout and types. * Update stories for new Former component. * Clean up unused styles and types across the project.
This commit is contained in:
@@ -1,66 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useFormContext, useFormState } from 'react-hook-form'
|
||||
import { useDebouncedCallback } from '@mantine/hooks'
|
||||
import useSubscribe from '../hooks/use-subscribe'
|
||||
import { useSuperFormStore } from '../store/SuperForm.store'
|
||||
import { openConfirmModal } from '../utils/openConfirmModal'
|
||||
|
||||
const SuperFormPersist = ({ storageKey }: { storageKey?: string | null }) => {
|
||||
// Component store State
|
||||
const [persistKey, setPersistKey] = useState<string>('')
|
||||
const { isDirty, isReady, isSubmitted } = useFormState()
|
||||
|
||||
const { remote, request } = useSuperFormStore((state) => ({
|
||||
request: state.request,
|
||||
remote: state.remote,
|
||||
}))
|
||||
|
||||
// Component Hooks
|
||||
const { reset, setValue } = useFormContext()
|
||||
|
||||
const handleFormChange = useDebouncedCallback(({ values }) => {
|
||||
setPersistKey(() => {
|
||||
const key = `superform-persist-${storageKey?.length > 0 ? storageKey : `${remote?.tableName || 'local'}-${request}-${values[remote?.primaryKey] ?? ''}`}`
|
||||
|
||||
if (!isDirty) {
|
||||
return key
|
||||
}
|
||||
|
||||
window.localStorage.setItem(key, JSON.stringify(values))
|
||||
|
||||
return key
|
||||
})
|
||||
}, 250)
|
||||
|
||||
useSubscribe('', handleFormChange)
|
||||
|
||||
// Component use Effects
|
||||
useEffect(() => {
|
||||
if (isReady && persistKey) {
|
||||
const data = window.localStorage.getItem(persistKey)
|
||||
if (!data) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isSubmitted) {
|
||||
window.localStorage.removeItem(persistKey)
|
||||
return
|
||||
}
|
||||
|
||||
openConfirmModal(
|
||||
() => {
|
||||
reset(JSON.parse(data))
|
||||
setValue('_dirty', true, { shouldDirty: true })
|
||||
},
|
||||
() => {
|
||||
window.localStorage.removeItem(persistKey)
|
||||
},
|
||||
'Do you want to restore the previous data that was not submitted?'
|
||||
)
|
||||
}
|
||||
}, [isReady, isSubmitted, persistKey])
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export default SuperFormPersist
|
||||
Reference in New Issue
Block a user