@@ -59,12 +59,22 @@ export default function useModal () {
59
59
return
60
60
}
61
61
62
+ const currentHash = window . location . hash
63
+ if ( currentHash ) {
64
+ const hasModalWithHash = modalStack . current . some (
65
+ modal => modal . options ?. hash && `#${ modal . options . hash } ` === currentHash
66
+ )
67
+ if ( hasModalWithHash ) {
68
+ window . history . replaceState ( window . history . state , '' , window . location . pathname + window . location . search )
69
+ }
70
+ }
71
+
62
72
while ( modalStack . current . length ) {
63
73
getCurrentContent ( ) ?. options ?. onClose ?. ( )
64
74
modalStack . current . pop ( )
65
75
}
66
76
forceUpdate ( )
67
- } , [ onBack ] )
77
+ } , [ onBack , getCurrentContent ] )
68
78
69
79
const router = useRouter ( )
70
80
useEffect ( ( ) => {
@@ -80,6 +90,21 @@ export default function useModal () {
80
90
return ( ) => router . events . off ( 'routeChangeStart' , maybeOnClose )
81
91
} , [ router . events , onClose , getCurrentContent ] )
82
92
93
+ useEffect ( ( ) => {
94
+ const handleHashChange = ( ) => {
95
+ const currentContent = getCurrentContent ( )
96
+ if ( ! currentContent ?. options ?. hash ) return
97
+
98
+ const expectedHash = `#${ currentContent . options . hash } `
99
+ if ( window . location . hash !== expectedHash ) {
100
+ onClose ( )
101
+ }
102
+ }
103
+
104
+ window . addEventListener ( 'hashchange' , handleHashChange )
105
+ return ( ) => window . removeEventListener ( 'hashchange' , handleHashChange )
106
+ } , [ onClose , getCurrentContent ] )
107
+
83
108
const modal = useMemo ( ( ) => {
84
109
if ( modalStack . current . length === 0 ) {
85
110
return null
@@ -116,6 +141,12 @@ export default function useModal () {
116
141
const showModal = useCallback (
117
142
( getContent , options ) => {
118
143
document . activeElement ?. blur ( )
144
+ if ( options ?. hash ) {
145
+ const newHash = `#${ options . hash } `
146
+ if ( window . location . hash !== newHash ) {
147
+ window . history . pushState ( window . history . state , '' , newHash )
148
+ }
149
+ }
119
150
const ref = { node : getContent ( onClose , setOptions ) , options }
120
151
if ( options ?. replaceModal ) {
121
152
modalStack . current = [ ref ]
@@ -124,7 +155,7 @@ export default function useModal () {
124
155
}
125
156
forceUpdate ( )
126
157
} ,
127
- [ onClose ]
158
+ [ onClose , setOptions ]
128
159
)
129
160
130
161
return [ modal , showModal ]
0 commit comments