From c4dfa34212ca13a90a9c1f57326bfa768ff25d9e Mon Sep 17 00:00:00 2001 From: Alexandre Chopin Date: Fri, 10 Feb 2017 21:24:17 +0100 Subject: [PATCH] fix optional route with index and order --- lib/build.js | 61 +++++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/lib/build.js b/lib/build.js index 36b71f8aa7..71203675e6 100644 --- a/lib/build.js +++ b/lib/build.js @@ -261,42 +261,49 @@ function createRoutes (files, srcDir) { var res = 0 var _a = a.path.split('/') var _b = b.path.split('/') - var _max = _b.length - 1 - _a.forEach((s, i) => { - if (i <= _max) { - if (res === 0) { - var y = (s.indexOf('*') > -1) ? 2 : (s.indexOf(':') > -1 ? 1 : 0) - var z = (_b[i].indexOf('*') > -1) ? 2 : (_b[i].indexOf(':') > -1 ? 1 : 0) - res = y - z - } - } else { - res = (res === 0) ? -1 : res + for (var i = 0; i < _a.length; i++) { + if (res !== 0) { break } + var y = (_a[i].indexOf('*') > -1) ? 2 : (_a[i].indexOf(':') > -1 ? 1 : 0) + var z = (_b[i].indexOf('*') > -1) ? 2 : (_b[i].indexOf(':') > -1 ? 1 : 0) + res = y - z + if (i === _b.length - 1 && res === 0) { + res = 1 } - }) - return res === 0 ? ((_a.length === _b.length) ? _a[_max].length - _b[_max].length : _b.length - _a.length) : res + } + return res === 0 ? -1 : res }) }) return cleanChildrenRoutes(routes) } function cleanChildrenRoutes (routes, isChild = false) { - let hasIndex = false - let parents = [] + let start = -1 + let routesIndex = [] + routes.forEach((route) => { + if (/-index$/.test(route.name) || route.name === 'index') { + // Save indexOf 'index' key in name + let res = route.name.split('-') + let s = res.indexOf('index') + start = (start === -1 || s < start) ? s : start + routesIndex.push(res) + } + }) routes.forEach((route) => { route.path = (isChild) ? route.path.replace('/', '') : route.path - if ((isChild && /-index$/.test(route.name)) || (!isChild && route.name === 'index')) { - hasIndex = true - } - let names = route.path.split('/') - if (hasIndex && (isChild || (!isChild && names[1] && names[1].indexOf('?') > -1))) { - route.path = route.path.replace('?', '') - } - if (/-index$/.test(route.name)) { - parents.push(route.name) - } else { - if (hasIndex && parents.indexOf(route.name.split('-').slice(0, -1).join('-') + '-index') > -1) { - route.path = route.path.replace('?', '') - } + if (route.path.indexOf('?') > -1) { + let names = route.name.split('-') + let paths = route.path.split('/') + if (!isChild) { paths.shift() } // clean first / for parents + routesIndex.forEach((r) => { + let i = r.indexOf('index') - start // children names + if (i < paths.length) { + for (var a = 0; a <= i; a++) { + if (a === i) { paths[a] = paths[a].replace('?', '') } + if (a < i && names[a] !== r[a]) { break } + } + } + }) + route.path = (isChild ? '' : '/') + paths.join('/') } route.name = route.name.replace(/-index$/, '') if (route.children) {