]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
refactor: remove unused code
authorEduardo San Martin Morote <posva13@gmail.com>
Thu, 30 Jan 2020 15:18:46 +0000 (16:18 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Thu, 30 Jan 2020 15:18:46 +0000 (16:18 +0100)
12 files changed:
__tests__/matcher/path-parser.spec.ts
__tests__/mount.ts
playground/App.vue
playground/router.ts
playground/views/Home.vue
playground/views/Nested.vue [new file with mode: 0644]
playground/views/User.vue
src/components/View.ts
src/index.ts
src/matcher/path-parser-ranker.ts
src/matcher/path-tokenizer.ts
src/router.ts

index aa27eed84271da0e42f5d7c93c5577495e2cec7d..82c625c81a0ff12a3a4279430fba7a1f3451f23c 100644 (file)
@@ -9,6 +9,14 @@ describe('Path parser', () => {
       ])
     })
 
+    // TODO: refactor trailing slash cases
+    it.skip('trailing slash', () => {
+      expect(tokenizePath('/foo/')).toEqual([
+        [{ type: TokenType.Static, value: 'foo' }],
+        [{ type: TokenType.Static, value: '' }],
+      ])
+    })
+
     it('empty', () => {
       expect(tokenizePath('')).toEqual([[]])
     })
@@ -363,10 +371,7 @@ describe('Path parser', () => {
 
     it('static single', () => {
       matchRegExp('^/?$', [[]], { strict: false })
-    })
-
-    it('empty path', () => {
-      matchRegExp('^$', [[]], { strict: true })
+      matchRegExp('^/$', [[]], { strict: true })
     })
 
     it('strict /', () => {
@@ -525,15 +530,19 @@ describe('Path parser', () => {
     })
 
     it('makes the difference between "" and "/" when strict', () => {
-      matchParams('', '/', null, { strict: true })
-      matchParams('/', '', null, { strict: true })
+      matchParams('/foo', '/foo/', null, { strict: true })
+      matchParams('/foo/', '/foo', null, { strict: true })
     })
 
-    it('allow a trailing slash', () => {
+    it('allows a trailing slash', () => {
       matchParams('/home', '/home/', {})
       matchParams('/a/b', '/a/b/', {})
     })
 
+    it('enforces a trailing slash', () => {
+      matchParams('/home/', '/home', null, { strict: true })
+    })
+
     it('allow a trailing slash in repeated params', () => {
       matchParams('/a/:id+', '/a/b/c/d/', { id: ['b', 'c', 'd'] })
       matchParams('/a/:id*', '/a/b/c/d/', { id: ['b', 'c', 'd'] })
index 3034a71140ae0102ba3bbd794128a9d686b97b39..0fc2d54be811ae3a415c62cc6c312cb67e59481c 100644 (file)
@@ -11,12 +11,14 @@ export function mount(
   },
   rootProps = {}
 ) {
+  // TODO: update with alpha-4
   const app = createApp()
   app.provide('router', router)
+  app.provide('route', router.currentRoute)
 
   const { template, components, ...ComponentWithoutTemplate } = Component
 
-  // @ts-ignore
+  // @ts-ignore TODO: remove?
   ComponentWithoutTemplate.components = {}
   for (const componentName in components) {
     app.component(componentName, components[componentName])
index 6a06ad29490efaaaaf8bc88241a43b27e4f07170..ae20154ba1f28c23ecf96247ff1f5e4af96dbbba 100644 (file)
         <a href="/documents/€">/documents/€ (force reload): not valid tho</a>
       </li>
       <li>
-        <router-link to="/">/</router-link>
+        <router-link to="/">Home</router-link>
+      </li>
+      <li>
+        <router-link to="/nested/nested/nested"
+          >/nested/nested/nested</router-link
+        >
       </li>
       <li>
         <router-link to="/long-0">/long-0</router-link>
         <router-link to="/with-data">/with-data</router-link>
       </li>
     </ul>
-    <transition
+    <!-- <transition
       name="fade"
       mode="out-in"
       @before-enter="flushWaiter"
       @before-leave="setupWaiter"
-    >
-      <router-view></router-view>
-    </transition>
+    > -->
+    <router-view></router-view>
+    <!-- </transition> -->
   </div>
 </template>
 
index a136bf819ddf9e0902d1563b62c3248b940d1978..ef8be6dea2ae2ad2ab9b5de93539c166d3dd81f2 100644 (file)
@@ -1,5 +1,6 @@
 import { createRouter, createHistory } from '../src'
 import Home from './views/Home.vue'
+import Nested from './views/Nested.vue'
 import User from './views/User.vue'
 import NotFound from './views/NotFound.vue'
 import component from './views/Generic.vue'
@@ -44,6 +45,18 @@ export const router = createRouter({
     { path: '/with-data', component: ComponentWithData, name: 'WithData' },
     { path: '/rep/:a*', component: component, name: 'repeat' },
     { path: '/:data(.*)', component: NotFound, name: 'NotFound' },
+    {
+      path: '/nested',
+      component: Nested,
+      name: 'Nested',
+      children: [
+        {
+          path: 'nested',
+          component: Nested,
+          children: [{ path: 'nested', component: Nested }],
+        },
+      ],
+    },
   ],
   async scrollBehavior(to, from, savedPosition) {
     await scrollWaiter.wait()
index 3e41c611baf081d2ff7125a935fb4d4f53493747..c59064b5af1ec340126f166979420b3d51b24c15 100644 (file)
@@ -1,11 +1,41 @@
 <template>
-  <div>Home</div>
+  <div>
+    <div>Home</div>
+    <p>My Data is: {{ someData }}</p>
+    toggle: {{ log(toggle) }}
+  </div>
 </template>
 
 <script>
-import { defineComponent } from 'vue'
+import { defineComponent, getCurrentInstance, inject, ref } from 'vue'
+// import { guardSymbol } from '../../src/components/View'
 
 export default defineComponent({
   name: 'Home',
+  data: () => ({
+    toggle: false,
+  }),
+
+  setup() {
+    const me = getCurrentInstance()
+    // const registerGuard = inject(guardSymbol)
+    // console.log('calling setup in Home')
+    // await registerGuard(me)
+    // emit('registerGuard', getCurrentInstance())
+
+    function log(value) {
+      console.log(value)
+      return value
+    }
+
+    return {
+      log,
+      someData: ref(0),
+    }
+  },
+
+  _beforeRouteEnter() {
+    this.toggle = true
+  },
 })
 </script>
diff --git a/playground/views/Nested.vue b/playground/views/Nested.vue
new file mode 100644 (file)
index 0000000..88a91dc
--- /dev/null
@@ -0,0 +1,26 @@
+<template>
+  <div>
+    <p>Nested level {{ level }}</p>
+    <router-view v-if="level < 6"></router-view>
+  </div>
+</template>
+
+<script>
+import { defineComponent, inject, provide } from 'vue'
+// import { guardSymbol } from '../../src/components/View'
+
+export default defineComponent({
+  name: 'Nested',
+  setup() {
+    const level = inject('level', 1)
+    provide('level', level + 1)
+    // const registerGuard = inject(guardSymbol)
+    // await registerGuard()
+    // console.log('done waiting')
+
+    return {
+      level,
+    }
+  },
+})
+</script>
index fef21a882d94bb8f96adc8ed35d9a258e5995014..bcf2264a66476823dfaea438515716f91bece5e2 100644 (file)
@@ -9,6 +9,7 @@ export default defineComponent({
   name: 'User',
   setup() {
     const route = inject('route')
+    console.log('calling setup in User')
     return { route }
   },
 })
index 00096c733e439ed995112ab87796cfbadc6c5829..80cb255b6b023669ddc0f6fbc2b31378453e74fa 100644 (file)
@@ -18,20 +18,21 @@ const View = defineComponent({
   },
 
   setup(props, { attrs }) {
-    const router = inject('router')
+    const route = inject('route')
     const depth: number = inject('routerViewDepth', 0)
     provide('routerViewDepth', depth + 1)
 
-    const ViewComponent = computed<Component | void>(() => {
-      const matched = router.currentRoute.value.matched[depth]
+    const ViewComponent = computed<Component | undefined>(() => {
+      const matched = route.value.matched[depth]
 
-      if (!matched) return null
-
-      return matched.components[props.name]
+      return matched && matched.components[props.name]
     })
 
-    return () =>
-      ViewComponent.value ? h(ViewComponent.value as any, attrs) : []
+    return () => {
+      return ViewComponent.value
+        ? h(ViewComponent.value as any, { ...attrs })
+        : null
+    }
   },
 })
 
index e0968148c3531cf224b15eee32528d129ac8c0d8..f6cf130d5b78fa2cc901e7d3d2802bab013d3e38 100644 (file)
@@ -1,5 +1,5 @@
 import { createRouter, Router } from './router'
-import { App } from '@vue/runtime-core'
+import { App, Ref } from '@vue/runtime-core'
 import createHistory from './history/html5'
 import createMemoryHistory from './history/memory'
 import createHashHistory from './history/hash'
@@ -12,8 +12,7 @@ import {
 
 declare module '@vue/runtime-core' {
   function inject(name: 'router'): Router
-  function inject(name: 'route'): RouteLocationNormalized
-  function inject(name: 'routerViewDepth'): number
+  function inject(name: 'route'): Ref<RouteLocationNormalized>
 }
 
 // @ts-ignore: we are not importing it so it complains
@@ -38,8 +37,6 @@ export function RouterPlugin(app: App, router: Router) {
   app.mixin({
     beforeCreate() {
       if (!started) {
-        router.setActiveApp(this)
-
         // TODO: this initial navigation is only necessary on client, on server it doesn't make sense
         // because it will create an extra unecessary navigation and could lead to problems
         router.push(router.history.location).catch(err => {
index be56fd8fd4356f5edec4a72b81090743ab39caf1..138939fc4e679b6bd085a7b1b6121deca9d7e47f 100644 (file)
@@ -125,6 +125,8 @@ export function tokensToParser(
     // the root segment needs special treatment
     const segmentScores: number[] = segment.length ? [] : [PathScore.Root]
 
+    // allow trailing slash
+    if (options.strict && !segment.length) pattern += '/'
     for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
       const token = segment[tokenIndex]
       // resets the score if we are inside a sub segment /:a-other-:b
index 9c7b4c2c04831c8f278d7421e92157e19f579aa3..7dd85319152d8fd2b79681285e2f9cf7272ee7ae 100644 (file)
@@ -123,9 +123,9 @@ export function tokenizePath(path: string): Array<Token[]> {
         } else if (char === ':') {
           consumeBuffer()
           state = TokenizerState.Param
-        } else if (char === '{') {
+          // } else if (char === '{') {
           // TODO: handle group (or drop it)
-          addCharToBuffer()
+          // addCharToBuffer()
         } else {
           addCharToBuffer()
         }
index e89c5ba67b846680da5e790af6c37a05d1ba8d3a..5a030b10e7480a3c8c0fb100682adb1160851589 100644 (file)
@@ -33,6 +33,7 @@ import { extractComponentsGuards, guardToPromiseFn } from './utils'
 import { encodeParam } from './utils/encoding'
 import { decode } from './utils/encoding'
 import { ref, Ref, markNonReactive } from '@vue/reactivity'
+import { nextTick } from '@vue/runtime-core'
 
 type ErrorHandler = (error: any) => any
 // resolve, reject arguments of Promise constructor
@@ -62,9 +63,6 @@ export interface Router {
   push(to: RouteLocation): Promise<RouteLocationNormalized>
   replace(to: RouteLocation): Promise<RouteLocationNormalized>
 
-  // TODO: find a way to remove it
-  setActiveApp(vm: TODO): void
-
   beforeEach(guard: NavigationGuard): ListenerRemover
   afterEach(guard: PostNavigationGuard): ListenerRemover
 
@@ -91,7 +89,6 @@ export function createRouter({
   let onReadyCbs: OnReadyCallback[] = []
   // TODO: should these be triggered before or after route.push().catch()
   let errorHandlers: ErrorHandler[] = []
-  let app: TODO
   let ready: boolean = false
 
   function resolve(
@@ -492,16 +489,12 @@ export function createRouter({
   ) {
     if (!scrollBehavior) return
 
-    await app.$nextTick()
+    await nextTick()
     const position = await scrollBehavior(to, from, scrollPosition || null)
     console.log('scrolling to', position)
     scrollToPosition(position)
   }
 
-  function setActiveApp(vm: TODO) {
-    app = vm
-  }
-
   const router: Router = {
     currentRoute,
     push,
@@ -514,7 +507,6 @@ export function createRouter({
     isReady,
 
     history,
-    setActiveApp,
   }
 
   return router