1import { createRouter, createWebHistory } from 'vue-router'
2import PackageAnalysis from '@/views/PackageAnalysis.vue'
3import Demo from'@/views/Demo.vue'
4import About from '@/views/About.vue'
5import NotFound from '@/views/NotFound.vue'
6
7const routes = [
8  {
9    path: '/',
10    name: 'Analysis',
11    component: PackageAnalysis,
12    meta: {
13      title: 'Analyse OTA package - from AOSP'
14    }
15  },
16  {
17    path: '/demo',
18    name: 'Demo',
19    component: Demo
20  },
21  {
22    path: '/about',
23    name: 'About',
24    component: About
25  },
26  {
27    path: '/:catchAll(.*)',
28    name: 'Not Found',
29    component: NotFound
30  }
31]
32
33const router = createRouter({
34  history: createWebHistory(process.env.BASE_URL),
35  routes
36})
37
38// This callback runs before every route change, including on page load.
39router.beforeEach((to, from, next) => {
40  // This goes through the matched routes from last to first, finding the closest route with a title.
41  // e.g., if we have `/some/deep/nested/route` and `/some`, `/deep`, and `/nested` have titles,
42  // `/nested`'s will be chosen.
43  const nearestWithTitle = to.matched.slice().reverse().find(r => r.meta && r.meta.title);
44
45  // Find the nearest route element with meta tags.
46  const nearestWithMeta = to.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
47
48  const previousNearestWithMeta = from.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
49
50  // If a route with a title was found, set the document (page) title to that value.
51  if(nearestWithTitle) {
52    document.title = nearestWithTitle.meta.title;
53  } else if(previousNearestWithMeta) {
54    document.title = previousNearestWithMeta.meta.title;
55  }
56
57  // Remove any stale meta tags from the document using the key attribute we set below.
58  Array.from(document.querySelectorAll('[data-vue-router-controlled]')).map(el => el.parentNode.removeChild(el));
59
60  // Skip rendering meta tags if there are none.
61  if(!nearestWithMeta) return next();
62
63  // Turn the meta tag definitions into actual elements in the head.
64  nearestWithMeta.meta.metaTags.map(tagDef => {
65    const tag = document.createElement('meta');
66
67    Object.keys(tagDef).forEach(key => {
68      tag.setAttribute(key, tagDef[key]);
69    });
70
71    // We use this to track which meta tags we create so we don't interfere with other ones.
72    tag.setAttribute('data-vue-router-controlled', '');
73
74    return tag;
75  })
76  // Add the meta tags to the document head.
77    .forEach(tag => document.head.appendChild(tag));
78
79  next();
80});
81
82export default router
83