|
| 1 | +/* @flow */ |
| 2 | +import { cleanPath } from './util/path' |
| 3 | +import { assert } from './util/warn' |
| 4 | + |
| 5 | +export function removeRouteMap ( |
| 6 | + location: string, |
| 7 | + oldPathList?: Array<string>, |
| 8 | + oldPathMap?: Dictionary<RouteRecord>, |
| 9 | + oldNameMap?: Dictionary<RouteRecord> |
| 10 | +): Dictionary<RouteRecord> { |
| 11 | + if (process.env.NODE_ENV !== 'production') { |
| 12 | + assert(oldPathList && oldPathMap, `route definition is empty`) |
| 13 | + } |
| 14 | + |
| 15 | + // the path list is used to control path matching priority |
| 16 | + const pathList: Array<string> = oldPathList || [] |
| 17 | + // $flow-disable-line |
| 18 | + const pathMap: Dictionary<RouteRecord> = oldPathMap || Object.create(null) |
| 19 | + // $flow-disable-line |
| 20 | + const nameMap: Dictionary<RouteRecord> = oldNameMap || Object.create(null) |
| 21 | + |
| 22 | + const normalizedPath = normalizePath(location) |
| 23 | + |
| 24 | + // remove routes which path and parent match normalizedPath |
| 25 | + // pending paths to remove |
| 26 | + const pathToRemove: Array<string> = [normalizedPath] |
| 27 | + |
| 28 | + const removedRoutes = {} |
| 29 | + |
| 30 | + while (pathToRemove.length) { |
| 31 | + const target = pathToRemove.pop() |
| 32 | + objIterator(pathMap, (path, route) => { |
| 33 | + const { name, parent } = route |
| 34 | + |
| 35 | + // sub items |
| 36 | + if (parent && parent.path === target && pathToRemove.indexOf(path) === -1) { |
| 37 | + pathToRemove.push(path) |
| 38 | + } |
| 39 | + |
| 40 | + if (path !== target) { |
| 41 | + // $flow-disable-line |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + removedRoutes[path] = route |
| 46 | + |
| 47 | + // remove from pathList |
| 48 | + const idx = pathList.indexOf(path) |
| 49 | + if (idx !== -1) { |
| 50 | + pathList.splice(idx, 1) |
| 51 | + } |
| 52 | + |
| 53 | + // remove from pathMap |
| 54 | + delete pathMap[path] |
| 55 | + |
| 56 | + // remove from nameMap |
| 57 | + if (nameMap && name) { |
| 58 | + delete pathMap[name] |
| 59 | + } |
| 60 | + }) |
| 61 | + } |
| 62 | + |
| 63 | + if (process.env.NODE_ENV !== 'production') { |
| 64 | + assert(Object.keys(removedRoutes).length, `route path not found: ${location}`) |
| 65 | + } |
| 66 | + |
| 67 | + return removedRoutes |
| 68 | +} |
| 69 | + |
| 70 | +function objIterator (obj, handler) { |
| 71 | + for (const key in obj) { |
| 72 | + handler(key, obj[key]) |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +function normalizePath ( |
| 77 | + path: string, |
| 78 | + parent?: RouteRecord, |
| 79 | + strict?: boolean |
| 80 | +): string { |
| 81 | + if (!strict) path = path.replace(/\/$/, '') |
| 82 | + if (path[0] === '/') return path |
| 83 | + if (parent == null) return path |
| 84 | + return cleanPath(`${parent.path}/${path}`) |
| 85 | +} |
0 commit comments