Skip to content

Commit

Permalink
fix: sort wildcard and :params (#9672)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhigang1992 authored Jul 1, 2021
1 parent a70adfb commit 4135d09
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 20 deletions.
1 change: 1 addition & 0 deletions packages/core/src/__tests__/getStateFromPath.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2196,6 +2196,7 @@ it('tries to match wildcard patterns at the end', () => {
path: '/bar/:id/',
screens: {
404: '*',
UserProfile: ':userSlug',
Test: 'test',
},
},
Expand Down
44 changes: 24 additions & 20 deletions packages/core/src/getStateFromPath.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,27 +143,31 @@ export default function getStateFromPath<ParamList extends {}>(
const aParts = a.pattern.split('/');
const bParts = b.pattern.split('/');

const aWildcardIndex = aParts.indexOf('*');
const bWildcardIndex = bParts.indexOf('*');

// If only one of the patterns has a wildcard, move it down in the list
if (aWildcardIndex === -1 && bWildcardIndex !== -1) {
return -1;
}

if (aWildcardIndex !== -1 && bWildcardIndex === -1) {
return 1;
}

if (aWildcardIndex === bWildcardIndex) {
// If `b` has more `/`, it's more exhaustive
// So we move it up in the list
return bParts.length - aParts.length;
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
// if b is longer, b get higher priority
if (aParts[i] == null) {
return 1;
}
// if a is longer, a get higher priority
if (bParts[i] == null) {
return -1;
}
const aWildCard = aParts[i] === '*' || aParts[i].startsWith(':');
const bWildCard = bParts[i] === '*' || bParts[i].startsWith(':');
// if both are wildcard we compare next component
if (aWildCard && bWildCard) {
continue;
}
// if only a is wild card, b get higher priority
if (aWildCard) {
return 1;
}
// if only b is wild card, a get higher priority
if (bWildCard) {
return -1;
}
}

// If the wildcard appears later in the pattern (has higher index), it's more specific
// So we move it up in the list
return bWildcardIndex - aWildcardIndex;
return bParts.length - aParts.length;
});

// Check for duplicate patterns in the config
Expand Down

0 comments on commit 4135d09

Please sign in to comment.