Skip to content

Commit

Permalink
Use URLPattern
Browse files Browse the repository at this point in the history
Closed #73
  • Loading branch information
mantou132 committed Nov 23, 2023
1 parent df906fb commit 3700498
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions packages/gem/src/elements/base/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ interface NamePosition {
[index: string]: number;
}

// TODO: use `URLPattern`
// https://bugzilla.mozilla.org/show_bug.cgi?id=1731418
// https://github.com/WebKit/standards-positions/issues/61
class ParamsRegExp extends RegExp {
namePosition: NamePosition;
constructor(pattern: string) {
Expand All @@ -30,10 +27,26 @@ class ParamsRegExp extends RegExp {
}

type Params = Record<string, string>;
declare global {
interface Window {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1731418
// https://github.com/WebKit/standards-positions/issues/61
URLPattern: any;
}
}

// `/a/b/:c/:d` `/a/b/1/2`
// 匹配成功时返回 params
// `/a/b/:c/:d` `/a/b/1/2`
// pattern 以 / 结尾时能匹配 2 中路径
// `/a/b/:c/:d/` `/a/b/1/2`
// `/a/b/:c/:d/` `/a/b/1/2/`
export function matchPath(pattern: string, path: string) {
if (window.URLPattern) {
const urLPattern = new window.URLPattern({ pathname: pattern });
const matchResult = urLPattern.exec({ pathname: path }) || urLPattern.exec({ pathname: `${path}/` });
if (!matchResult) return null;
return matchResult.pathname.groups as Params;
}
const reg = new ParamsRegExp(pattern);
const matchResult = path.match(reg) || `${path}/`.match(reg);
if (!matchResult) return null;
Expand Down

0 comments on commit 3700498

Please sign in to comment.