Skip to content

WIP: Optimized matcher #3707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions flow/declarations.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ declare type RouteRecord = {
beforeEnter: ?NavigationGuard;
meta: any;
props: boolean | Object | Function | Dictionary<boolean | Object | Function>;
pathToRegexpOptions: PathToRegexpOptions;
}

declare type Location = {
Expand Down
92 changes: 86 additions & 6 deletions src/create-matcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,18 @@ export function createMatcher (
): Matcher {
const { pathList, pathMap, nameMap } = createRouteMap(routes)

let _optimizedMatcher = optimizedMatcher(pathList, pathMap)

function addRoutes (routes) {
createRouteMap(routes, pathList, pathMap, nameMap)
_optimizedMatcher = optimizedMatcher(pathList, pathMap)
}

function addRoute (parentOrRoute, route) {
const parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined
// $flow-disable-line
createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent)
_optimizedMatcher = optimizedMatcher(pathList, pathMap)

// add aliases of parent
if (parent && parent.alias.length) {
Expand Down Expand Up @@ -82,12 +86,9 @@ export function createMatcher (
return _createRoute(record, location, redirectedFrom)
} else if (location.path) {
location.params = {}
for (let i = 0; i < pathList.length; i++) {
const path = pathList[i]
const record = pathMap[path]
if (matchRoute(record.regex, location.path, location.params)) {
return _createRoute(record, location, redirectedFrom)
}
const record = _optimizedMatcher(location.path, location.params)
if (record) {
return _createRoute(record, location, redirectedFrom)
}
}
// no match
Expand Down Expand Up @@ -224,3 +225,82 @@ function matchRoute (
function resolveRecordPath (path: string, record: RouteRecord): string {
return resolvePath(path, record.parent ? record.parent.path : '/', true)
}

function isStatic (route) {
return (
// Custom regex options are dynamic.
Object.keys(route.pathToRegexpOptions).length === 0 &&
// Dynamic paths have /:placeholder or anonymous placeholder /(.+) or wildcard *.
!/[:(*]/.exec(route.path)
)
}

function firstLevelStatic (path) {
// firstLevel = ['/p/', '/p', '/' index: 0, input: '/p/b/c', groups: undefined]
const firstLevel = /^(\/[^:(*/]+)(\/|$)/.exec(path)
return firstLevel && firstLevel[1]
}

function optimizedMatcher (
pathList: Array<string>,
pathMap: Dictionary<RouteRecord>
) {
// Lookup table
// e.g. Route /p/b is mapped as {"/p/b": route}
const staticMap = {}
// Buckets with the first level static path.
// e.g. Route /p/b/:id is mapped as {"/p": [route]}
const firstLevelStaticMap = {}
// Array of everything else.
const dynamic = []

pathList.forEach((path, index) => {
const route = pathMap[path]
const normalizedPath = route.regex.ignoreCase ? path.toLowerCase() : path
if (isStatic(route)) {
staticMap[normalizedPath] = { index, route }
} else {
const firstLevel = firstLevelStatic(path.toLowerCase())
if (firstLevel) {
if (!firstLevelStaticMap[firstLevel]) {
firstLevelStaticMap[firstLevel] = []
}
firstLevelStaticMap[firstLevel].push({ index, route })
} else {
dynamic.push({ index, route })
}
}
})

function match (path, params) {
const cleanPath = path.replace(/\/$/, '').toLowerCase()
let record = staticMap[cleanPath]

const firstLevel = firstLevelStatic(path)
const firstLevelRoutes = firstLevelStaticMap[firstLevel] || []

for (let i = 0; i < firstLevelRoutes.length; i++) {
const { index, route } = firstLevelRoutes[i]
if (record && index >= record.index) {
break
}
if (matchRoute(route.regex, path, params)) {
record = firstLevelRoutes[i]
break
}
}

for (let j = 0; j < dynamic.length; j++) {
const { index, route } = dynamic[j]
if (record && index >= record.index) {
break
}
if (matchRoute(route.regex, path, params)) {
record = dynamic[j]
}
}
return record && record.route
}

return match
}
1 change: 1 addition & 0 deletions src/create-route-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ function addRouteRecord (
const record: RouteRecord = {
path: normalizedPath,
regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
pathToRegexpOptions,
components: route.components || { default: route.component },
alias: route.alias
? typeof route.alias === 'string'
Expand Down
159 changes: 159 additions & 0 deletions test/unit/specs/create-matcher.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,163 @@ describe('Creating Matcher', function () {
expect(pathForErrorRoute).toEqual('/error/')
expect(pathForNotFoundRoute).toEqual('/')
})

it('respect ordering', function () {
const matcher = createMatcher([
{
path: '/p/staticbefore',
name: 'staticbefore',
component: { name: 'staticbefore' }
},
{
path: '/p/:id',
name: 'dynamic',
component: { name: 'dynamic' }
},
{
path: '/p/staticafter',
name: 'staticafter',
component: { name: 'staticafter' }
}
])
expect(matcher.match('/p/staticbefore').name).toBe('staticbefore')
expect(matcher.match('/p/staticafter').name).toBe('dynamic')
})

it('respect ordering for full dynamic', function () {
const matcher = createMatcher([
{
path: '/before/static',
name: 'staticbefore',
component: { name: 'staticbefore' }
},
{
path: '/:foo/static',
name: 'dynamic',
component: { name: 'dynamic' }
},
{
path: '/after/static',
name: 'staticafter',
component: { name: 'staticafter' }
}
])
expect(matcher.match('/before/static').name).toBe('staticbefore')
expect(matcher.match('/after/static').name).toBe('dynamic')
})

it('respect ordering between full dynamic and first level static', function () {
const matcher = createMatcher([
{
path: '/before/:foo',
name: 'staticbefore',
component: { name: 'staticbefore' }
},
{
path: '/:foo/static',
name: 'dynamic',
component: { name: 'dynamic' }
},
{
path: '/after/:foo',
name: 'staticafter',
component: { name: 'staticafter' }
}
])
expect(matcher.match('/before/static').name).toBe('staticbefore')
expect(matcher.match('/after/static').name).toBe('dynamic')
})

it('static can use sensitive flag', function () {
const matcher = createMatcher([
{
path: '/p/sensitive',
name: 'sensitive',
pathToRegexpOptions: {
sensitive: true
},
component: { name: 'sensitive' }
},
{
path: '/p/insensitive',
name: 'insensitive',
component: { name: 'insensitive' }
},
{
path: '*', name: 'not-found', component: { name: 'not-found ' }
}
])

expect(matcher.match('/p/SENSITIVE').name).toBe('not-found')
expect(matcher.match('/p/INSENSITIVE').name).toBe('insensitive')
})

it('static can use strict flag', function () {
const matcher = createMatcher([
{
path: '/p/strict',
name: 'strict',
pathToRegexpOptions: {
strict: true
},
component: { name: 'strict' }
},
{
path: '/p/unstrict',
name: 'unstrict',
component: { name: 'unstrict' }
},
{
path: '*', name: 'not-found', component: { name: 'not-found ' }
}
])

expect(matcher.match('/p/strict/').name).toBe('not-found')
expect(matcher.match('/p/unstrict/').name).toBe('unstrict')
})

it('static can use end flag', function () {
const matcher = createMatcher([
{
path: '/p/end',
name: 'end',
component: { name: 'end' }
},
{
path: '/p/not-end',
name: 'not-end',
pathToRegexpOptions: {
end: false
},
component: { name: 'not-end' }
},
{
path: '*', name: 'not-found', component: { name: 'not-found ' }
}
])

expect(matcher.match('/p/end/foo').name).toBe('not-found')
expect(matcher.match('/p/not-end/foo').name).toBe('not-end')
})

it('first level dynamic must work', function () {
const matcher = createMatcher([
{
path: '/:foo/b',
name: 'b',
component: { name: 'b' }
},
{
path: '/p/c',
name: 'c',
component: { name: 'c' }
},
{
path: '*', name: 'not-found', component: { name: 'not-found ' }
}
])

expect(matcher.match('/p/b').name).toBe('b')
expect(matcher.match('/p/c').name).toBe('c')
})
})
4 changes: 4 additions & 0 deletions test/unit/specs/error-handling.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { NavigationFailureType } from '../../../src/util/errors'
Vue.use(VueRouter)

describe('error handling', () => {
beforeEach(function () {
process.env.NODE_ENV = 'development'
})

it('onReady errors', done => {
const router = new VueRouter()
const err = new Error('foo')
Expand Down
1 change: 1 addition & 0 deletions types/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export type RouteConfig = RouteConfigSingleView | RouteConfigMultipleViews
export interface RouteRecord {
path: string
regex: RegExp
pathToRegexpOptions: PathToRegexpOptions
components: Dictionary<Component>
instances: Dictionary<Vue>
name?: string
Expand Down