@hippy/vue-router
Version:
Official router for hippy-vue
87 lines (73 loc) • 2.1 kB
JavaScript
/*
* Tencent is pleased to support the open source community by making
* Hippy available.
*
* Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-param-reassign */
export function resolvePath(relative, base, append) {
const firstChar = relative.charAt(0);
if (firstChar === '/') {
return relative;
}
if (firstChar === '?' || firstChar === '#') {
return base + relative;
}
const stack = base.split('/');
// remove trailing segment if:
// - not appending
// - appending to trailing slash (last segment is empty)
if (!append || !stack[stack.length - 1]) {
stack.pop();
}
// resolve relative path
const segments = relative.replace(/^\//, '').split('/');
for (let i = 0; i < segments.length; i += 1) {
const segment = segments[i];
if (segment === '..') {
stack.pop();
} else if (segment !== '.') {
stack.push(segment);
}
}
// ensure leading slash
if (stack[0] !== '') {
stack.unshift('');
}
return stack.join('/');
}
export function parsePath(path) {
let hash = '';
let query = '';
const hashIndex = path.indexOf('#');
if (hashIndex >= 0) {
hash = path.slice(hashIndex);
path = path.slice(0, hashIndex);
}
const queryIndex = path.indexOf('?');
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
}
return {
path,
query,
hash,
};
}
export function cleanPath(path) {
return path.replace(/\/\//g, '/');
}