-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathrouter.ts
49 lines (43 loc) · 1.11 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* External dependencies
*/
import { match } from 'path-to-regexp';
/**
* Internal dependencies
*/
import type { Screen, MatchParams } from '../types';
function matchPath( path: string, pattern: string ) {
const matchingFunction = match< MatchParams >( pattern, {
decode: decodeURIComponent,
} );
return matchingFunction( path );
}
export function patternMatch( path: string, screens: Screen[] ) {
for ( const screen of screens ) {
const matched = matchPath( path, screen.path );
if ( matched ) {
return { params: matched.params, id: screen.id };
}
}
return undefined;
}
export function findParent( path: string, screens: Screen[] ) {
if ( ! path.startsWith( '/' ) ) {
return undefined;
}
const pathParts = path.split( '/' );
let parentPath;
while ( pathParts.length > 1 && parentPath === undefined ) {
pathParts.pop();
const potentialParentPath =
pathParts.join( '/' ) === '' ? '/' : pathParts.join( '/' );
if (
screens.find( ( screen ) => {
return matchPath( potentialParentPath, screen.path ) !== false;
} )
) {
parentPath = potentialParentPath;
}
}
return parentPath;
}