fix(router): inula-router路由匹配规则兼容react-router;HashHistory hash格式不合法时重定向至合法URL

This commit is contained in:
huangxuan 2024-04-02 10:52:22 +08:00
parent ebfe1eceb9
commit 78f4bce57c
No known key found for this signature in database
GPG Key ID: E79F50C67022565D
3 changed files with 50 additions and 37 deletions

View File

@ -57,6 +57,13 @@ export function createHashHistory<S = DefaultStateType>(option: HashHistoryOptio
const pathDecoder = addHeadSlash; const pathDecoder = addHeadSlash;
const pathEncoder = hashType === 'slash' ? addHeadSlash : stripHeadSlash; const pathEncoder = hashType === 'slash' ? addHeadSlash : stripHeadSlash;
const startLocation = getHashContent(window.location.href);
const encodeLocation = pathEncoder(startLocation);
// 初始化hash格式不合法时会重定向
if (startLocation !== encodeLocation) {
window.location.replace(stripHash(window.location.href) + '#' + encodeLocation);
}
function getLocation() { function getLocation() {
let hashPath = pathDecoder(getHashContent(window.location.hash)); let hashPath = pathDecoder(getHashContent(window.location.hash));
if (basename) { if (basename) {

View File

@ -121,7 +121,13 @@ describe('parser test', () => {
it('url without end slash match wildcard', function () { it('url without end slash match wildcard', function () {
const parser = createPathParser('/about/', { strictMode: false }); const parser = createPathParser('/about/', { strictMode: false });
const matched = parser.parse('/about'); const matched = parser.parse('/about');
expect(matched).toBeNull(); expect(matched).toStrictEqual({
path: '/about/',
url: '/about',
score: [10],
isExact: true,
param: {},
});
}); });
it('url without end slash match wildcard (strictMode)', function () { it('url without end slash match wildcard (strictMode)', function () {
@ -259,7 +265,7 @@ describe('parser test', () => {
}); });
it('dynamic param with complex regexp pattern', () => { it('dynamic param with complex regexp pattern', () => {
const parser = createPathParser('/detail/:action([\\da-z]+)', { exact: true }); const parser = createPathParser('/detail/:action([\\da-z]+)', { exact: true, caseSensitive: true });
const res = parser.parse('/detail/a123'); const res = parser.parse('/detail/a123');
expect(res).toEqual({ expect(res).toEqual({
isExact: true, isExact: true,

View File

@ -97,12 +97,14 @@ export function createPathParser<P = unknown>(pathname: string, option: ParserOp
const token = tokens[tokenIdx]; const token = tokens[tokenIdx];
const nextToken = tokens[tokenIdx + 1]; const nextToken = tokens[tokenIdx + 1];
switch (token.type) { switch (token.type) {
case TokenType.Delimiter: case TokenType.Delimiter: {
{ // 该分隔符后有可选参数则该分割符在匹配时是可选的
const hasOptional = lookToNextDelimiter(tokenIdx + 1); const hasOptional = lookToNextDelimiter(tokenIdx + 1);
pattern += `/${hasOptional ? '?' : ''}`; // 该分割符为最后一个且strictMode===false时该分隔符在匹配时是可选的
} const isSlashOptional = nextToken === undefined && !strictMode;
pattern += `/${hasOptional || isSlashOptional ? '?' : ''}`;
break; break;
}
case TokenType.Static: case TokenType.Static:
pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); pattern += token.value.replace(REGEX_CHARS_RE, '\\$&');
if (nextToken && nextToken.type === TokenType.Pattern) { if (nextToken && nextToken.type === TokenType.Pattern) {
@ -112,32 +114,31 @@ export function createPathParser<P = unknown>(pathname: string, option: ParserOp
} }
scores.push(MatchScore.static); scores.push(MatchScore.static);
break; break;
case TokenType.Param: case TokenType.Param: {
{ // 动态参数支持形如/:param、/:param*、/:param?、/:param(\\d+)的形式
// 动态参数支持形如/:param、/:param*、/:param?、/:param(\\d+)的形式 let paramRegexp = '';
let paramRegexp = ''; if (nextToken) {
if (nextToken) { switch (nextToken.type) {
switch (nextToken.type) { case TokenType.LBracket:
case TokenType.LBracket: // 跳过当前Token和左括号
// 跳过当前Token和左括号 tokenIdx += 2;
tokenIdx += 2; while (tokens[tokenIdx].type !== TokenType.RBracket) {
while (tokens[tokenIdx].type !== TokenType.RBracket) { paramRegexp += tokens[tokenIdx].value;
paramRegexp += tokens[tokenIdx].value;
tokenIdx++;
}
paramRegexp = `(${paramRegexp})`;
break;
case TokenType.Pattern:
tokenIdx++; tokenIdx++;
paramRegexp += `(${nextToken.value === '*' ? '.*' : BASE_PARAM_PATTERN})${nextToken.value}`; }
break; paramRegexp = `(${paramRegexp})`;
} break;
case TokenType.Pattern:
tokenIdx++;
paramRegexp += `(${nextToken.value === '*' ? '.*' : BASE_PARAM_PATTERN})${nextToken.value}`;
break;
} }
pattern += paramRegexp ? `(?:${paramRegexp})` : `(${BASE_PARAM_PATTERN})`;
keys.push(token.value);
scores.push(MatchScore.param);
} }
pattern += paramRegexp ? `(?:${paramRegexp})` : `(${BASE_PARAM_PATTERN})`;
keys.push(token.value);
scores.push(MatchScore.param);
break; break;
}
case TokenType.WildCard: case TokenType.WildCard:
keys.push(token.value); keys.push(token.value);
pattern += `((?:${BASE_PARAM_PATTERN})${onlyHasWildCard ? '?' : ''}(?:/(?:${BASE_PARAM_PATTERN}))*)`; pattern += `((?:${BASE_PARAM_PATTERN})${onlyHasWildCard ? '?' : ''}(?:/(?:${BASE_PARAM_PATTERN}))*)`;
@ -215,16 +216,15 @@ export function createPathParser<P = unknown>(pathname: string, option: ParserOp
} }
path += params[token.value]; path += params[token.value];
break; break;
case TokenType.WildCard: case TokenType.WildCard: {
{ const wildCard = params['*'];
const wildCard = params['*']; if (wildCard instanceof Array) {
if (wildCard instanceof Array) { path += wildCard.join('/');
path += wildCard.join('/'); } else {
} else { path += wildCard;
path += wildCard;
}
} }
break; break;
}
case TokenType.Delimiter: case TokenType.Delimiter:
path += token.value; path += token.value;
break; break;