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 Dec 5, 2023
1 parent d2e02a0 commit 2952a15
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
4 changes: 2 additions & 2 deletions packages/gem-examples/src/multi-page/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const routes = [
},
{
title: 'Page B Title',
pattern: '/B',
pattern: '/b',
content: html` <app-page-b>B: </app-page-b> `,
},
{
Expand Down Expand Up @@ -57,7 +57,7 @@ class App extends GemElement {
<header><gem-title prefix=${GemTitleElement.defaultPrefix}>AppName</gem-title></header>
<nav>
<gem-link path="/">Home</gem-link>
<gem-link path="/A">PageA</gem-link>
<gem-link path="/a">PageA</gem-link>
<gem-link path="/b">PageB</gem-link>
<gem-link path="/c/e" pattern="/c/*">PageC</gem-link>
</nav>
Expand Down
22 changes: 18 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,27 @@ 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`
// URLPattern 大小写敏感
// 匹配成功时返回 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 2952a15

Please sign in to comment.