Skip to content

Commit 9d59a68

Browse files
Michael.KryvoruchkoMichael.Kryvoruchko
Michael.Kryvoruchko
authored and
Michael.Kryvoruchko
committed
feat: add the possibility to close the dialog on navigation back
1 parent d1ee0be commit 9d59a68

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/components/GDialog.vue

+51-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script lang="ts">
2-
import { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue'
2+
import { computed, defineComponent, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref, watch } from 'vue'
33
44
import { IN_BROWSER } from '../util'
55
import { useStack } from '../composables/stack'
@@ -97,6 +97,15 @@ export default defineComponent({
9797
type: [String, Number],
9898
default: 'auto',
9999
},
100+
101+
/**
102+
* it true, the dialog will add hash to the url.
103+
* and will be closed on browser back button.
104+
*/
105+
closeOnBack: {
106+
type: Boolean,
107+
default: false,
108+
},
100109
},
101110
102111
emits: {
@@ -194,6 +203,47 @@ export default defineComponent({
194203
animateClick()
195204
}
196205
206+
// close on back button
207+
if (IN_BROWSER && props.closeOnBack) {
208+
const instace = getCurrentInstance()!
209+
210+
let currentDialogHash = `dialog-${instace.uid}`
211+
if (window.location.hash)
212+
currentDialogHash = `${window.location.hash.slice(1)}-${currentDialogHash}`
213+
214+
const popstateListener = () => {
215+
if (window.location.hash.includes(currentDialogHash) || !scopedModelValue.value)
216+
return
217+
218+
onClose()
219+
}
220+
221+
onMounted(() => {
222+
if (scopedModelValue.value)
223+
window.location.hash = currentDialogHash
224+
225+
window.addEventListener('popstate', popstateListener)
226+
})
227+
228+
onUnmounted(() => {
229+
window.removeEventListener('popstate', popstateListener)
230+
})
231+
232+
watch(scopedModelValue, (value) => {
233+
if (!value && window.location.hash.includes(currentDialogHash)) {
234+
window.history.back()
235+
}
236+
else if (value) {
237+
if (window.location.hash)
238+
currentDialogHash = `${window.location.hash.slice(1)}-${`dialog-${instace.uid}`}`
239+
else
240+
currentDialogHash = `dialog-${instace.uid}`
241+
242+
window.location.hash = `#${currentDialogHash}`
243+
}
244+
})
245+
}
246+
197247
// activator slot
198248
const activatorAttrs = {
199249
onClick() {

0 commit comments

Comments
 (0)