walker.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { type App, inject, ref } from 'vue'
  3. import type { RouteLocationRaw, Router } from 'vue-router'
  4. export class Walker {
  5. private previousRoute = ref<string | null>(null)
  6. static KEY_INJECT = Symbol('walker')
  7. constructor(private router: Router) {
  8. this.previousRoute.value = Walker.getHistoryBackRoute()
  9. router.afterEach(() => {
  10. this.previousRoute.value = Walker.getHistoryBackRoute()
  11. })
  12. }
  13. private static getHistoryBackRoute(): string | null {
  14. const { state } = window.history
  15. if (state && typeof state.back === 'string') {
  16. return state.back
  17. }
  18. return null
  19. }
  20. public getBackUrl(backupRoute: RouteLocationRaw) {
  21. return this.previousRoute.value || backupRoute
  22. }
  23. public get hasBackUrl() {
  24. return this.previousRoute.value !== null
  25. }
  26. public async back(path: RouteLocationRaw, ignore: string[] = []) {
  27. const previous = this.previousRoute.value
  28. if (previous && !ignore.find((entry) => previous.includes(entry))) {
  29. return this.router.back()
  30. }
  31. return this.router.push(path)
  32. }
  33. }
  34. declare module '@vue/runtime-core' {
  35. export interface ComponentCustomProperties {
  36. $walker: Walker
  37. }
  38. }
  39. export const useWalker = (): Walker => {
  40. return inject(Walker.KEY_INJECT) as Walker
  41. }
  42. export const initializeWalker = (app: App, router: Router) => {
  43. const walker = new Walker(router)
  44. app.provide(Walker.KEY_INJECT, walker)
  45. app.config.globalProperties.$walker = walker
  46. }