|
| 1 | +import { ref, onMounted, onUnmounted, Ref } from '@src/api' |
| 2 | + |
| 3 | +// The history methods 'pushState' and 'replaceState' by default do not fire an event |
| 4 | +// unless it is coming from user interaction with the browser navigation bar, |
| 5 | +// so we are adding a patch to make them detectable |
| 6 | +let isPatched = false |
| 7 | +const patchHistoryMethodsOnce = () => { |
| 8 | + if (isPatched) return |
| 9 | + const methods = ['pushState', 'replaceState'] |
| 10 | + methods.forEach(method => { |
| 11 | + const original = (history as any)[method] |
| 12 | + ;(history as any)[method] = function(state: any) { |
| 13 | + // eslint-disable-next-line prefer-rest-params |
| 14 | + const result = original.apply(this, arguments) |
| 15 | + const event = new Event(method.toLowerCase()) |
| 16 | + ;(event as any).state = state |
| 17 | + window.dispatchEvent(event) |
| 18 | + return result |
| 19 | + } |
| 20 | + }) |
| 21 | + |
| 22 | + isPatched = true |
| 23 | +} |
| 24 | + |
| 25 | +export function useLocation(runOnMount = true) { |
| 26 | + const buildState = (trigger: string) => { |
| 27 | + const { state, length } = history |
| 28 | + |
| 29 | + const { |
| 30 | + hash, |
| 31 | + host, |
| 32 | + hostname, |
| 33 | + href, |
| 34 | + origin, |
| 35 | + pathname, |
| 36 | + port, |
| 37 | + protocol, |
| 38 | + search |
| 39 | + } = location |
| 40 | + |
| 41 | + return { |
| 42 | + trigger, |
| 43 | + state, |
| 44 | + length, |
| 45 | + hash, |
| 46 | + host, |
| 47 | + hostname, |
| 48 | + href, |
| 49 | + origin, |
| 50 | + pathname, |
| 51 | + port, |
| 52 | + protocol, |
| 53 | + search |
| 54 | + } |
| 55 | + } |
| 56 | + const isTracking = ref(false) |
| 57 | + const locationState = ref(buildState('load')) |
| 58 | + |
| 59 | + const popState = () => (locationState.value = buildState('popstate')) |
| 60 | + const pushState = () => (locationState.value = buildState('pushstate')) |
| 61 | + const replaceState = () => (locationState.value = buildState('replacestate')) |
| 62 | + |
| 63 | + const start = () => { |
| 64 | + patchHistoryMethodsOnce() |
| 65 | + |
| 66 | + if (isTracking.value) return |
| 67 | + isTracking.value = true |
| 68 | + window.addEventListener('popstate', popState) |
| 69 | + window.addEventListener('pushstate', pushState) |
| 70 | + window.addEventListener('replacestate', replaceState) |
| 71 | + } |
| 72 | + |
| 73 | + const stop = () => { |
| 74 | + if (!isTracking.value) return |
| 75 | + isTracking.value = false |
| 76 | + window.removeEventListener('popstate', popState) |
| 77 | + window.removeEventListener('pushstate', pushState) |
| 78 | + window.removeEventListener('replacestate', replaceState) |
| 79 | + } |
| 80 | + |
| 81 | + onMounted(() => runOnMount && start()) |
| 82 | + onUnmounted(stop) |
| 83 | + |
| 84 | + return { locationState, isTracking, start, stop } |
| 85 | +} |
0 commit comments