Refactor(Editor): Add a prompt to leave the page

Add a prompt to leave the page when content has been changed
This commit is contained in:
2024-04-22 18:14:43 +08:00
parent 5d28f7d8d7
commit 804005cae3
3 changed files with 69 additions and 26 deletions

View File

@@ -24,6 +24,10 @@ import LoadingMask from '@/components/common/LoadingMask'
import Card from '@/components/common/Card'
const Edit = () => {
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
currentLocation.pathname !== nextLocation.pathname && hasEdited
)
const navigate = useNavigate()
const { toolId } = useParams()
const [searchParams] = useSearchParams({
@@ -49,6 +53,19 @@ const Edit = () => {
const [categoryData, setCategoryData] = useState<ToolCategoryVo[]>()
const [loadingCategory, setLoadingCategory] = useState(false)
useBeforeUnload(
useCallback(
(event) => {
if (hasEdited) {
event.preventDefault()
event.returnValue = ''
}
},
[hasEdited]
),
{ capture: true }
)
const handleOnChangeFileContent = (content: string, fileName: string, files: IFiles) => {
setHasEdited(true)
@@ -484,6 +501,20 @@ const Edit = () => {
>
{editForm}
</AntdDrawer>
<AntdModal
open={blocker.state === 'blocked'}
title={'未保存'}
onOk={() => blocker.proceed?.()}
onCancel={() => blocker.reset?.()}
footer={(_, { OkBtn, CancelBtn }) => (
<>
<OkBtn />
<CancelBtn />
</>
)}
>
</AntdModal>
</>
)
}