|
1
|
import { PropsWithChildren, useCallback, useMemo, useState } from "react" |
|
2
|
import { Path, useLocation, useNavigate } from "react-router-dom" |
|
3
|
import { RouteModalProviderContext } from "./route-modal-context" |
|
4
|
|
|
5
|
type RouteModalProviderProps = PropsWithChildren<{ |
|
6
|
prev: string | Partial<Path> | number |
|
7
|
}> |
|
8
|
|
|
9
|
export const RouteModalProvider = ({ |
|
10
|
prev, |
|
11
|
children, |
|
12
|
}: RouteModalProviderProps) => { |
|
13
|
const navigate = useNavigate() |
|
14
|
const location = useLocation() |
|
15
|
|
|
16
|
const [closeOnEscape, setCloseOnEscape] = useState(true) |
|
17
|
|
|
18
|
const handleSuccess = useCallback( |
|
19
|
(path?: string) => { |
|
20
|
const to = path || prev |
|
21
|
if (typeof to === "number") { |
|
22
|
// Replace current location with success state, then navigate back |
|
23
|
navigate(location.pathname + location.search, { |
|
24
|
replace: true, |
|
25
|
state: { ...location.state, isSubmitSuccessful: true }, |
|
26
|
}) |
|
27
|
setTimeout(() => { |
|
28
|
navigate(to) |
|
29
|
}, 0) |
|
30
|
} else { |
|
31
|
navigate(to, { replace: true, state: { isSubmitSuccessful: true } }) |
|
32
|
} |
|
33
|
}, |
|
34
|
[navigate, prev, location] |
|
35
|
) |
|
36
|
|
|
37
|
const value = useMemo( |
|
38
|
() => ({ |
|
39
|
handleSuccess, |
|
40
|
setCloseOnEscape, |
|
41
|
__internal: { closeOnEscape }, |
|
42
|
}), |
|
43
|
[handleSuccess, setCloseOnEscape, closeOnEscape] |
|
44
|
) |
|
45
|
|
|
46
|
return ( |
|
47
|
<RouteModalProviderContext.Provider value={value}> |
|
48
|
{children} |
|
49
|
</RouteModalProviderContext.Provider> |
|
50
|
) |
|
51
|
} |