@wcstack/router 4.9.0 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +65 -5
- package/README.md +66 -5
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.esm.js +190 -9
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -200,6 +200,11 @@ output-only メンバーはバインド attach 時に**読まれ**、以後は
|
|
|
200
200
|
- ページネーション・タブ(戻るボタンで戻りたい)→ `navigateUrl = "?page=2"`
|
|
201
201
|
- 検索ボックス・絞り込み(履歴を打鍵ごとに汚したくない)→ `replaceUrl = "?q=" + …`(高頻度入力には `<wcs-debounce>` を挟む)
|
|
202
202
|
|
|
203
|
+
クエリを URL に持つ検索ページが、何も言わずに間違えることが 2 つある:
|
|
204
|
+
|
|
205
|
+
- **URL が追いつくまでの、読者が打っている文字。** 検索ボックスを URL のクエリ(`searchParams.q`)に束ね、ボックスと `replaceUrl` の間に `<wcs-debounce>` を挟むと、URL は — したがってボックスも — 打鍵より遅れる: 落ち着いた値が URL を書き、router が少し後で commit する。その間、ボックスには古いクエリが書き戻され、打っている指の下で文字が消える。打っている間は打っているものを見せる: ボックス自身の `draft` と `typing` フラグを持ち、フラグは `input` で立て、debounce が落ち着き、その値が URL に入ったら下ろす。URL のクエリを見せるのはフラグが下りているときだけにする(戻る / 進むでもボックスが埋まる)。そして URL は、打たれた値が落ち着いたときにだけ書く: debounce は最初に受けた値でも 1 度落ち着くので、ディープリンク(`/search?q=a&page=2`)ではそれが URL にクエリを書き戻す — `?q=` や、`page` の無い `?q=a` を。
|
|
206
|
+
- **件数の読み上げ。** 文(「12 冊見つかりました」)はリクエストの応答から書く — `<wcs-fetch>` の応答のイベント、`eventToken.value: results` と `$on: { results(state, event) { … } }`([`value` がどの応答か](../fetch/README.ja.md#出力ステートバインド可能な非同期状態))。getter で `value` と今のクエリから組み立てない: 新しいクエリの要求が進んでいる間も `value` は前の応答のままなので、読み上げの領域は、まず新しい条件と前の件数を言った。領域はルートの内容の外に置く([アクセシビリティ契約](#アクセシビリティ契約))。
|
|
207
|
+
|
|
203
208
|
**マルチ Router**: `params` / `routeName` は各 Router 自身のマッチを反映するが、ページの URL にクエリは 1 つしかない — どの Router 経由で書いてもページ全体のクエリが置き換わる。一方**読み取り面は per-Router**: Router は自分の `basename` 配下のナビゲーションを処理したときだけ `searchParams` を commit するので、その値は「その Router が最後に処理したナビゲーション時点のクエリ」である。
|
|
204
209
|
|
|
205
210
|
#### ナビゲーションターゲットのクエリ文字列
|
|
@@ -279,7 +284,7 @@ interface IGuardContext { // 進入先マッチの frozen スナップ
|
|
|
279
284
|
- 判定関数が `false` を返すとナビゲーションがキャンセルされ、`guard` 属性のパスへ遷移。空でない文字列を返すとそのパスへ遷移(例: `` return `/login?next=${encodeURIComponent(toPath)}` ``)。`toPath` にクエリは含まれない。リダイレクト先に要るなら第 3 引数の `searchParams` から組み直す(`new URLSearchParams(searchParams)`)
|
|
280
285
|
- リダイレクトは、キャンセルしたナビゲーションの履歴エントリを**置き換える**。だから「戻る」で守られた URL へ戻る(そしてすぐまたリダイレクトされる)ことはない。リダイレクトはガードの本来の使い方なので、コンソールには何も出さない。ガード同士が送り合うリダイレクトは、続けて 10 回で止め、最後の 1 回を名指すエラーを出す。リダイレクトされたナビゲーションの `navigate()` / `replace()` は `AbortError` で reject する
|
|
281
286
|
- モジュールは**一度だけ**評価され、関数はナビゲーションのたびに呼ばれる。変わるもの(セッション)は、モジュールの先頭ではなく関数の中で読む
|
|
282
|
-
- ガードから `<wcs-state>` の状態は見えない。ページの読み込みでは、最初のルートのガードが `@wcstack/state` の読み込みより先に走ることもある。セッションは、それを保存している場所 — `<wcs-storage>` が保存する `localStorage`
|
|
287
|
+
- ガードから `<wcs-state>` の状態は見えない。ページの読み込みでは、最初のルートのガードが `@wcstack/state` の読み込みより先に走ることもある。セッションは、それを保存している場所 — `<wcs-storage>` が保存する `localStorage` のキー — から直接読む。どのタブでも最新の値になる。`<wcs-storage>` はオブジェクトと配列を JSON で、文字列はそのまま保存する([JSON 自動シリアライズ](../storage/README.ja.md#json-自動シリアライズ)): 保存したセッションのオブジェクトは `JSON.parse(localStorage.getItem(key))` で読めるが、保存したトークンの文字列ではそれが例外を投げる — 文字列は `getItem` だけで読む
|
|
283
288
|
- 判定関数は `Promise` を返すことも可能(非同期チェック対応)— 解決するまでルートは commit されない
|
|
284
289
|
- 第 3 引数に進入先マッチ(`params` / `typedParams` / `searchParams` / `routeName`)が渡る。`toPath` / `fromPath` は basename スライス後のパス
|
|
285
290
|
- 中に置いた `<wcs-route>` を守る。その中のどこに置いてもよい — 入れ子のルートの前でも後でも、要素の中でも。親のガードは、子のルートへのナビゲーションでも走る
|
|
@@ -457,16 +462,16 @@ console.log(router.typedParams.userId); // 123 (number)
|
|
|
457
462
|
| `to` | 遷移先の絶対ルートパスもしくはURL。`/`で始まる場合はルートパス(basename は pathname にのみ付与され、`?クエリ` / `#ハッシュ` はそのまま温存される)。`?` で始まる場合は**クエリのみリンク**:href は「現在 pathname + 指定クエリ」で組み立てられ、ロケーション変更に追従する。それ以外は外部URLとして扱われる。`to` が空の間(`attr.to:` で束ね、まだ書かれていない — router を state より先に読むページ)は、`<a>` に `href` が無く、active にもならない。`to` が来たらそれを書く |
|
|
458
463
|
| `match` | `exact`(既定)か `prefix`。`prefix` なら下のパスでも active になる(サイドナビの「商品」が `/products/3` でも)。そのときの `aria-current` は `"true"`(そのパス自身では `"page"`)。下のパスへのリンクにも印が付く: `/products/new` では `prefix` の「商品」と「新しい商品」の両方が active で、`aria-current` は `"true"` と `"page"`。印を 1 つに見せるなら `[aria-current="page"]` でスタイルを書く |
|
|
459
464
|
|
|
460
|
-
**アクティブ状態**: 生成された `<a>` はパスが現在のロケーションと一致する場合に `active` クラスと、同じ事実の ARIA 表現である `aria-current="page"`
|
|
465
|
+
**アクティブ状態**: 生成された `<a>` はパスが現在のロケーションと一致する場合に `active` クラスと、同じ事実の ARIA 表現である `aria-current="page"` を受け取る(スクリーンリーダーがナビゲーション内の現在地を読み上げられる)。クエリの無い `to` は **pathname だけ**で比べ、ページのクエリは影響しない(`to="/products"` は `/products?page=2` でも active のまま)。4.10 から、クエリのある `to` は、今の URL のクエリが `to` のクエリのパラメータをすべて同じ値で持つときだけ active になる: `to="?q=a&page=2"`(「次のページ」)は `/search?q=a` では現在のページではなく、`/search?q=a&page=2` では現在のページ — リンクが名指さないパラメータは構わないので、`/search?q=a&page=2&sort=new` でも。重複するキー(`?tag=a&tag=b`)は同じ値の組(順序は問わない)が要り、値はデコードして比べる(`+` と `%20` は同じ)。`match="prefix"` はパスの規則をそのままに、同じクエリの規則を足す。4.9 まではどちら側のクエリも見なかったので、ページのページ送りのリンクがすべて「現在のページ」になり、スクリーンリーダーは「次のページ、現在のページ」と読んだ。ナビゲーションイベント(`currententrychange`, `wcs:navigate`, `popstate`)で更新される — クエリだけのナビゲーションでも。
|
|
461
466
|
|
|
462
467
|
```css
|
|
463
468
|
/* アクティブなリンクのスタイル */
|
|
464
469
|
a.active { font-weight: bold; color: blue; }
|
|
465
470
|
```
|
|
466
471
|
|
|
467
|
-
**属性の転送**: `<a>` の生成時に、すべての `aria-*` 属性と固定 7 名(`title` / `rel` / `target` / `download` / `hreflang` / `lang` / `dir`)をホストから anchor へコピーする(`lang` / `dir` はスクリーンリーダーの読み上げ言語・方向に直結する)。`to` / `style` / `class` は決して転送しない(ホストは `display:none` であり、`class` は `active` 契約を持つ)。接続後に追従するのは固定 7
|
|
472
|
+
**属性の転送**: `<a>` の生成時に、すべての `aria-*` 属性と固定 7 名(`title` / `rel` / `target` / `download` / `hreflang` / `lang` / `dir`)をホストから anchor へコピーする(`lang` / `dir` はスクリーンリーダーの読み上げ言語・方向に直結する)。`to` / `style` / `class` は決して転送しない(ホストは `display:none` であり、`class` は `active` 契約を持つ)。接続後に追従するのは固定 7 名のみで、**`aria-*` の値は anchor を作るときに 1 度だけコピーされ**、その後の変更は anchor に届かない。`data-wcs` のバインド(`<wcs-link data-wcs="attr.aria-label: ...">`)では、値をいつ書くかで決まる: `for:` の行や `if:` の枝の中の `<wcs-link>` は接続より前に束ねられるので、最初の値は anchor を作るときにホストにあってコピーされる — ただしその値の後の変更は届かない。ページのマークアップの `<wcs-link>` は、state が束ねる前に anchor を持つことがあり、そのとき値は届かない。変わらない `aria-*` は静的属性で書き、変わるリンクの名前は中身で与える: ホストの子は anchor へ移されるので、`<wcs-link>` の中の束ねた `<span data-wcs="textContent: …">` は更新され続ける。
|
|
468
473
|
|
|
469
|
-
**素の `<a>` について**: Navigation API のあるブラウザでは、basename 配下の素の `<a href="/about">` も SPA 遷移になる(router が intercept する)。フォールバックブラウザでは成立しない(SPA 経路は `<wcs-link>` の click ハンドラのみ)ため、推奨は `<wcs-link>` のまま。
|
|
474
|
+
**素の `<a>` について**: Navigation API のあるブラウザでは、basename 配下の素の `<a href="/about">` も SPA 遷移になる(router が intercept する)。フォールバックブラウザでは成立しない(SPA 経路は `<wcs-link>` の click ハンドラのみ)ため、推奨は `<wcs-link>` のまま。4.10 から、素の `<a href="#main">`(フラグメントだけ)はルートの遷移にならず、どちらの経路でも今のページの中で移る — [ページ内リンク](#ページ内リンクスキップリンク)を参照。
|
|
470
475
|
|
|
471
476
|
**読み直しについて**: 4.7 から、ページが求める読み直し — `location.reload()`・`history.go(0)`・`navigation.reload()` — は文書を読み直す。`leaveConfirm` があればブラウザ自身の確認が出る。4.6 までは router が同じ文書の中のルートの遷移として受けたので、「更新があります — 再読み込み」のボタンも Service Worker の更新も効かなかった。basename 配下のほかのナビゲーションは、`location.replace(location.href)` も含めて SPA の遷移のまま。
|
|
472
477
|
|
|
@@ -575,6 +580,52 @@ router は、プラットフォームが既に正しく行うことについて
|
|
|
575
580
|
|
|
576
581
|
設計の記録は [docs/a11y-design.md](https://github.com/wcstack/wcstack/blob/main/docs/a11y-design.md) §3 を参照。
|
|
577
582
|
|
|
583
|
+
### ページ内リンク(スキップリンク)
|
|
584
|
+
|
|
585
|
+
4.10 から、書いたままの `href` がフラグメントだけのリンク — スキップリンクの `<a href="#main">` と、ページ先頭への `href="#"` — は今のページの中で移り、ルートの遷移にはならない:
|
|
586
|
+
|
|
587
|
+
```html
|
|
588
|
+
<head><base href="/"></head>
|
|
589
|
+
<body>
|
|
590
|
+
<a class="skip-link" href="#main">本文へ移動</a>
|
|
591
|
+
<wcs-router>
|
|
592
|
+
<template>
|
|
593
|
+
<wcs-route path="/search"><main id="main">…</main></wcs-route>
|
|
594
|
+
…
|
|
595
|
+
</template>
|
|
596
|
+
</wcs-router>
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
- URL は今のパスとクエリ+そのハッシュ(`/search?q=a#main`)になり、どのフラグメントのリンクとも同じく履歴が 1 つ増える(同じフラグメントをもう一度押すと置き換える)。ブラウザが行き先 — その `id` を持つ要素、または `<a name>` — へスクロールし、router がそこへフォーカスを移す。自分でフォーカスを受けない要素には、`focus="heading"` と同じく `tabindex="-1"` を足す。`#` と `#top` は先頭へスクロールし、フォーカスは動かさない。
|
|
600
|
+
- ルートは何も変わらない: guard は走らず、描き直しも無く、`leaveConfirm` も聞かない。2 つの履歴の間の戻る / 進むもフラグメントのナビゲーションで、ルートはそのまま、スクロール位置はブラウザが戻す。
|
|
601
|
+
- 理由: SPA なら必ずある `<base href="/">` の下では、`#main` は `/#main` へ解決される。だから 4.9 までは、`/search?q=a` のスキップリンクで読者はホームのルートへ移った(`<base href="/ja/">` の下では `/ja/` へ)。
|
|
602
|
+
- どちらの経路でも動く。Navigation API があれば、router は `navigate` イベントからリンクを読む(`sourceElement`。今の Chromium・Firefox・Safari は持つ)。無いとき、またはイベントに `sourceElement` が無いときは `window` で click を聞く — ページ自身のリスナーより後なので、ページが取り消したクリックには触らない。
|
|
603
|
+
- 変わらないもの: 修飾キー(Ctrl / ⌘ / Shift / Alt)付きや中ボタンのクリック、`_self` 以外の `target` や `download` を持つリンク、別のページのフラグメントへのリンク(`/faq#x`・`?q=b#x`)、どの router の `basename` の下でもないページ。
|
|
604
|
+
|
|
605
|
+
### router がページに任せること
|
|
606
|
+
|
|
607
|
+
- **ナビゲーションの後に聞かせたい知らせは、ルートの内容に置かない。** ルートの内容は文と一緒に挿入されるので、その中の `role="status"` / `aria-live` の領域は知らせを持ったまま現れる。スクリーンリーダーが読み上げるのは、すでに知っている領域の変化なので、その知らせは決して読まれない。`<wcs-view-transition>` があると、ルートを置いた後に応答で埋めた領域でさえ、文と一緒に挿入されうる(差し替えが遷移の中で走る)。領域はページに 1 つ、router とその `<wcs-outlet>` の外に置く。ナビゲーションの commit で空にし(router の `path` への `$watch`)、新しいページの文はその後、ページが言うことを持ったときに書く。ページのタイトルなら `announce="title"` が router 自身の領域でそうする。
|
|
608
|
+
|
|
609
|
+
```html
|
|
610
|
+
<wcs-router data-wcs="path: route"><template>…</template></wcs-router>
|
|
611
|
+
<wcs-outlet></wcs-outlet>
|
|
612
|
+
<p class="visually-hidden" role="status" data-wcs="textContent: status"></p>
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
```js
|
|
616
|
+
$eventTokens: ["results"],
|
|
617
|
+
$watch: {
|
|
618
|
+
route() { this.status = ""; }, // ナビゲーションで空にし…
|
|
619
|
+
},
|
|
620
|
+
$on: {
|
|
621
|
+
results(state, event) { // …新しいページは言うことを持ったときに書く
|
|
622
|
+
state.status = `${event.detail.value.length} 冊見つかりました`;
|
|
623
|
+
},
|
|
624
|
+
},
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
- **ダイアログを閉じた後のフォーカス。** モーダルの `<dialog>` は、閉じると開いた要素へフォーカスを返す。その要素がもう無いとき — ダイアログが、開いたボタンのあった行を消した — フォーカスは `<body>` へ落ち、キーボードやスクリーンリーダーの読者はページの先頭からやり直すことになる。そういう削除の後は自分で移す — リストかその見出しへ: `<h2 tabindex="-1" data-wcs="command.focus: $command.focusList">` と、行が消えた後の `this.$command.focusList.emit()`(ネイティブ要素の `command.` のメソッドは `native-commands` アドオンにあり、full のエントリに入っている)。
|
|
628
|
+
|
|
578
629
|
## パス仕様案(Router / Route / Link 共通)
|
|
579
630
|
|
|
580
631
|
### 用語
|
|
@@ -635,11 +686,20 @@ basename が `/ja` なら `/en/orders` へのリンクは `_isOwnPath` を外れ
|
|
|
635
686
|
辞退し、ブラウザが本物のナビゲーションを行う。「ただのリンクで切り替わる」のは basename の
|
|
636
687
|
**おかげ**である。
|
|
637
688
|
|
|
689
|
+
この切り替えはページを離れるので、`leaveConfirm` があれば先に聞く — そしてページには、
|
|
690
|
+
読者が受け入れたかが分からない: click のリスナーは質問より先に走り、断られた切り替えは
|
|
691
|
+
前の言語のままページに留まる。選んだ言語は、クリックではなく次のページで記録する:
|
|
692
|
+
クリックでは `sessionStorage` に印を付け、次のページの head スクリプトが、URL がその言語を
|
|
693
|
+
持つときに(`localStorage` へ)確定し、そうでなければ印を捨てる。
|
|
694
|
+
|
|
638
695
|
副産物が 2 つある。
|
|
639
696
|
|
|
640
697
|
* **ルートパターンからロケールが消える** —— `path="/"`・`path="/about"`。アプリ内リンクも
|
|
641
698
|
ロケールを持たない(`<wcs-link to="/about">` が basename を前置する)
|
|
642
|
-
* **ページ上の URL をすべて絶対にする**こと。`<base>` が相対 URL
|
|
699
|
+
* **ページ上の URL をすべて絶対にする**こと。`<base>` が相対 URL の基準を変えるため。
|
|
700
|
+
4.10 から、フラグメントだけのリンク(`href="#main"`)は例外で、router が
|
|
701
|
+
今のページに留める([ページ内リンク](#ページ内リンクスキップリンク))。インライン SVG の
|
|
702
|
+
フラグメント参照(`url(#gradient)`・`clip-path`)はリンクではないので、base 基準のまま
|
|
643
703
|
|
|
644
704
|
ロケールを持たない URL や未対応のロケールの修復も、同じ head スクリプトで `location.replace`
|
|
645
705
|
する。ルートガードには置けない —— guard の redirect 先は静的な `guard="…"` 属性なので、
|
package/README.md
CHANGED
|
@@ -200,6 +200,11 @@ The exposed objects are **frozen snapshots** owned by the router: a new object p
|
|
|
200
200
|
- Pagination, tabs — the back button should step through them: `navigateUrl = "?page=2"`.
|
|
201
201
|
- Search boxes, filters — the history should not record every keystroke: `replaceUrl = "?q=" + …`, with `<wcs-debounce>` in front of high-frequency input.
|
|
202
202
|
|
|
203
|
+
Two things a search page with its query in the URL gets wrong without a word:
|
|
204
|
+
|
|
205
|
+
- **What the reader is typing, while the URL catches up.** With the box bound to the URL's query (`searchParams.q`) and `<wcs-debounce>` between the box and `replaceUrl`, the URL — and so the box — lags the keys: a settle writes the URL, the router commits it a moment later, and in between the box is written back with the older query, under the reader's fingers. Show what is typed while it is being typed: keep the box's own `draft` and a `typing` flag, set on `input` and cleared when the debounce has settled and the URL has what it settled on, and show the URL's query only when the flag is clear (so Back / Forward still fills the box). And write the URL only from a settle of something typed: the debounce settles once for the value it starts with too, and on a deep link (`/search?q=a&page=2`) that settle would write the query back over the URL — `?q=` or `?q=a`, without the `page`.
|
|
206
|
+
- **Announcing the result count.** Write the sentence ("12 books found") from the response of the request — the `<wcs-fetch>`'s response event, `eventToken.value: results` with `$on: { results(state, event) { … } }` ([which response `value` holds](../fetch/README.md#output-state-bindable-async-state)) — not from `value` and the current query in a getter: `value` keeps the previous response while the new query's request is in flight, so the region first said the new query with the previous total. Put the region outside the route content (see [Accessibility contract](#accessibility-contract)).
|
|
207
|
+
|
|
203
208
|
**Multiple routers**: `params` / `routeName` reflect each router's own match, but the page URL has a single query string — a query written through *any* router replaces the query for the whole page. Reads, however, are per-router: a router commits `searchParams` only when it processes a navigation under its own `basename`, so its value is "the query as of the last navigation this router processed".
|
|
204
209
|
|
|
205
210
|
#### Query strings in navigation targets
|
|
@@ -279,7 +284,7 @@ Place as a child of `<wcs-route>` to declaratively define a guard decision funct
|
|
|
279
284
|
- If the function returns `false`, navigation is cancelled and the user is redirected to the `guard` path; a non-empty string redirects there instead (e.g. `` return `/login?next=${encodeURIComponent(toPath)}` ``). `toPath` has no query string: rebuild it from the third argument's `searchParams` when the target needs it (`new URLSearchParams(searchParams)`)
|
|
280
285
|
- A redirect **replaces** the history entry of the cancelled navigation, so Back does not lead to the guarded URL (and straight back to the redirect). It is not logged — it is what the guard is for. Guards that keep redirecting each other are stopped after 10 redirects in a row, with an error naming the last one. A `navigate()` / `replace()` whose navigation is redirected rejects with an `AbortError`
|
|
281
286
|
- The module is evaluated **once**; the function runs on every navigation. Read anything that changes — a session — inside the function, not at the module's top level
|
|
282
|
-
- A guard does not see the `<wcs-state>` tree, and on a page load the landing route's guard can run before `@wcstack/state` has loaded. Read what the session is kept in directly — `localStorage`, under the key a `<wcs-storage>` saves it to
|
|
287
|
+
- A guard does not see the `<wcs-state>` tree, and on a page load the landing route's guard can run before `@wcstack/state` has loaded. Read what the session is kept in directly — `localStorage`, under the key a `<wcs-storage>` saves it to — which is also current in every tab. `<wcs-storage>` stores an object or an array as JSON, but a string as it is ([Auto JSON serialization](../storage/README.md#auto-json-serialization)): `JSON.parse(localStorage.getItem(key))` reads a saved session object, and throws on a saved token string — read that with `getItem` alone
|
|
283
288
|
- The function can return a `Promise` for async checks — the route is not committed until it settles
|
|
284
289
|
- The third argument carries the match being entered (`params` / `typedParams` / `searchParams` / `routeName`); `toPath` / `fromPath` are basename-sliced paths
|
|
285
290
|
- It guards the `<wcs-route>` it is inside, wherever it sits there — before or after the nested routes, or inside an element. A parent's guard runs for every navigation into its child routes too
|
|
@@ -457,16 +462,16 @@ Link. Converted to an `<a>`, and the route path in the `to` attribute is convert
|
|
|
457
462
|
| `to` | Destination path or URL. Paths starting with `/` are treated as internal paths (basename is prepended to the pathname; a `?query` / `#hash` suffix is kept as-is). A value starting with `?` is a **query-only** link: the href is assembled as "current pathname + that query" and tracks location changes. Other values are treated as external URLs. While `to` is empty — bound with `attr.to:` and not written yet, as when the router loads before state — the `<a>` has no `href` and is never active; it takes the `to` when it arrives. |
|
|
458
463
|
| `match` | `exact` (default) or `prefix`. With `prefix` the link is also active on the paths under it — a side navigation's "Products" on `/products/3` — with `aria-current="true"` there (`"page"` on the path itself). A link to a path under it is marked as well: on `/products/new`, a `prefix` "Products" and a "New product" are both active, with `aria-current="true"` and `"page"`; to show one mark, style `[aria-current="page"]`. |
|
|
459
464
|
|
|
460
|
-
**Active state**: The generated `<a>` receives the `active` class when its path matches the current location, and `aria-current="page"` alongside it — the same fact, expressed in ARIA, so screen readers announce the current page in navigation.
|
|
465
|
+
**Active state**: The generated `<a>` receives the `active` class when its path matches the current location, and `aria-current="page"` alongside it — the same fact, expressed in ARIA, so screen readers announce the current page in navigation. A `to` without a query compares the **pathname only** — the page's query does not matter, so `to="/products"` stays active on `/products?page=2`. Since 4.10, a `to` with a query is active only when the current URL's query has every parameter of `to`'s query with the same value(s): `to="?q=a&page=2"` ("Next page") is not the current page on `/search?q=a`, and is on `/search?q=a&page=2` — and on `/search?q=a&page=2&sort=new`, since parameters the link does not name are allowed. A repeated key (`?tag=a&tag=b`) needs the same set of values, in any order, and values are compared decoded (`+` and `%20` are the same). `match="prefix"` keeps its path rule and adds the same query rule. Up to 4.9 the query was ignored on both sides, so every pagination link on a page was its "current page" and a screen reader read "Next page, current page". Tracking is updated on navigation events (`currententrychange`, `wcs:navigate`, `popstate`), query-only navigations included.
|
|
461
466
|
|
|
462
467
|
```css
|
|
463
468
|
/* Style active links */
|
|
464
469
|
a.active { font-weight: bold; color: blue; }
|
|
465
470
|
```
|
|
466
471
|
|
|
467
|
-
**Attribute forwarding**: when the `<a>` is generated, all `aria-*` attributes plus seven fixed names (`title`, `rel`, `target`, `download`, `hreflang`, `lang`, `dir`) are copied from the host to the anchor (`lang` / `dir` matter to screen readers — they set the announcement language and direction of the link text). `to`, `style`, and `class` are never forwarded (the host is `display:none`, and `class` carries the `active` contract). After connection, only the seven fixed names keep tracking changes; **
|
|
472
|
+
**Attribute forwarding**: when the `<a>` is generated, all `aria-*` attributes plus seven fixed names (`title`, `rel`, `target`, `download`, `hreflang`, `lang`, `dir`) are copied from the host to the anchor (`lang` / `dir` matter to screen readers — they set the announcement language and direction of the link text). `to`, `style`, and `class` are never forwarded (the host is `display:none`, and `class` carries the `active` contract). After connection, only the seven fixed names keep tracking changes; **an `aria-*` value is copied once, when the anchor is created**, and a later change never reaches the anchor. With a `data-wcs` binding (`<wcs-link data-wcs="attr.aria-label: ...">`) it depends on when the value is written: a `<wcs-link>` in a `for:` row or an `if:` branch is bound before it is connected, so its first value is on the host when the anchor is created and is copied — but a later change of that value is not; a `<wcs-link>` in the page markup may have its anchor before state binds it, and then the value never arrives. Write `aria-*` that does not change as static attributes, and give a link a name that changes through its content: the host's children are moved into the anchor, so a bound `<span data-wcs="textContent: …">` inside `<wcs-link>` keeps updating.
|
|
468
473
|
|
|
469
|
-
**Plain `<a>` note**: in browsers with the Navigation API, a plain `<a href="/about">` under the basename also becomes an SPA navigation (the router intercepts it). This does not hold in fallback browsers, where only `<wcs-link>`'s click handler provides SPA navigation — so `<wcs-link>` remains the recommendation.
|
|
474
|
+
**Plain `<a>` note**: in browsers with the Navigation API, a plain `<a href="/about">` under the basename also becomes an SPA navigation (the router intercepts it). This does not hold in fallback browsers, where only `<wcs-link>`'s click handler provides SPA navigation — so `<wcs-link>` remains the recommendation. Since 4.10, a plain `<a href="#main">` (a bare fragment) is never a route change: it moves within the current page, on both paths — see [In-page links](#in-page-links-skip-links).
|
|
470
475
|
|
|
471
476
|
**Reload note**: since 4.7, a reload the page asks for — `location.reload()`, `history.go(0)`, `navigation.reload()` — reloads the document, and with `leaveConfirm` set it gets the browser's own prompt. Up to 4.6 the router took it as a route change in the same document, so an "update available — reload" button or a service worker's update flow did nothing. Every other navigation under the basename, `location.replace(location.href)` included, stays an SPA navigation.
|
|
472
477
|
|
|
@@ -575,6 +580,52 @@ These are the specification defaults; writing them out records the delegation as
|
|
|
575
580
|
|
|
576
581
|
See [docs/a11y-design.md](https://github.com/wcstack/wcstack/blob/main/docs/a11y-design.md) §3 for the design record.
|
|
577
582
|
|
|
583
|
+
### In-page links (skip links)
|
|
584
|
+
|
|
585
|
+
Since 4.10, a link whose `href` as written is a bare fragment — a skip link, `<a href="#main">`, and `href="#"` for the top of the page — moves within the current page, and is never a route change:
|
|
586
|
+
|
|
587
|
+
```html
|
|
588
|
+
<head><base href="/"></head>
|
|
589
|
+
<body>
|
|
590
|
+
<a class="skip-link" href="#main">Skip to content</a>
|
|
591
|
+
<wcs-router>
|
|
592
|
+
<template>
|
|
593
|
+
<wcs-route path="/search"><main id="main">…</main></wcs-route>
|
|
594
|
+
…
|
|
595
|
+
</template>
|
|
596
|
+
</wcs-router>
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
- The URL becomes the current path and query plus that hash (`/search?q=a#main`), with a history entry as any fragment link makes (the same fragment again replaces it). The browser scrolls to the target — the element with that `id`, or an `<a name>` — and the router moves focus to it, adding `tabindex="-1"` when it does not take focus itself, as `focus="heading"` does. `#` and `#top` scroll to the top and leave focus where it is.
|
|
600
|
+
- Nothing about the route changes: no guard runs, nothing is rendered again, `leaveConfirm` does not ask. Back / Forward between the two entries are fragment navigations as well — the route stays and the browser restores the scroll position.
|
|
601
|
+
- Why: under `<base href="/">`, which every SPA has, `#main` resolves to `/#main`. Up to 4.9 a skip link on `/search?q=a` therefore took the reader to the home route (under `<base href="/ja/">`, to `/ja/`).
|
|
602
|
+
- It works on both paths. With the Navigation API the router reads the link from the `navigate` event (`sourceElement`, which current Chromium, Firefox and Safari give); without it, or where the event has no `sourceElement`, it listens for the click on `window`, after the page's own listeners — a click the page cancelled is left alone.
|
|
603
|
+
- Unchanged: a click with a modifier (Ctrl / ⌘ / Shift / Alt) or the middle button, a link with a `target` other than `_self` or with `download`, a link to another page's fragment (`/faq#x`, `?q=b#x`), and a page outside every router's `basename`.
|
|
604
|
+
|
|
605
|
+
### What the router leaves to the page
|
|
606
|
+
|
|
607
|
+
- **A message meant to be heard after a navigation does not belong in the route content.** The route content is inserted together with its text, so a `role="status"` / `aria-live` region in it arrives with its message already there, and a screen reader announces changes to a region it already knows: the message is never read. With `<wcs-view-transition>`, even a region filled from a response after the route was placed can be inserted with its text (the swap runs inside the transition). Keep one region for the page, outside the router and its `<wcs-outlet>`; empty it when a navigation commits (a `$watch` on the router's `path`), and write the new page's sentence after that, when the page has it. For the page title, `announce="title"` does this already, in the router's own region.
|
|
608
|
+
|
|
609
|
+
```html
|
|
610
|
+
<wcs-router data-wcs="path: route"><template>…</template></wcs-router>
|
|
611
|
+
<wcs-outlet></wcs-outlet>
|
|
612
|
+
<p class="visually-hidden" role="status" data-wcs="textContent: status"></p>
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
```js
|
|
616
|
+
$eventTokens: ["results"],
|
|
617
|
+
$watch: {
|
|
618
|
+
route() { this.status = ""; }, // a navigation empties it…
|
|
619
|
+
},
|
|
620
|
+
$on: {
|
|
621
|
+
results(state, event) { // …and the new page writes when it has something to say
|
|
622
|
+
state.status = `${event.detail.value.length} books found`;
|
|
623
|
+
},
|
|
624
|
+
},
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
- **Focus after a dialog closes.** A modal `<dialog>` gives focus back to the element that opened it when it closes. When that element is gone — the dialog deleted the row whose button opened it — focus falls to `<body>`, and a keyboard or screen-reader user starts again from the top of the page. Move it yourself after such a removal, to the list or its heading: `<h2 tabindex="-1" data-wcs="command.focus: $command.focusList">` and `this.$command.focusList.emit()` once the row is gone (a native element's `command.` methods come with the `native-commands` add-on, in the full entries).
|
|
628
|
+
|
|
578
629
|
## Path Specification (Router / Route / Link)
|
|
579
630
|
|
|
580
631
|
### Terminology
|
|
@@ -638,12 +689,22 @@ With basename `/ja`, a link to `/en/orders` falls outside `_isOwnPath`, the
|
|
|
638
689
|
router declines to intercept, and the browser performs a real navigation. The
|
|
639
690
|
"just a link" language switch works *because* of the basename.
|
|
640
691
|
|
|
692
|
+
It also leaves the page, so with `leaveConfirm` set it asks first — and the page
|
|
693
|
+
cannot tell whether the reader accepted: a click listener runs before the
|
|
694
|
+
question, and a declined switch stays on the page in the old language. Record
|
|
695
|
+
the chosen language on the next page, not on the click: mark it in
|
|
696
|
+
`sessionStorage` on click, and let the next page's head script commit it (to
|
|
697
|
+
`localStorage`) when the URL carries that language, and drop the mark otherwise.
|
|
698
|
+
|
|
641
699
|
Two consequences worth having:
|
|
642
700
|
|
|
643
701
|
* **Route patterns carry no locale** — `path="/"`, `path="/about"`. In-app links
|
|
644
702
|
stay locale-free too (`<wcs-link to="/about">` prepends the basename).
|
|
645
703
|
* **Every URL on the page must be absolute**, since `<base>` now changes what
|
|
646
|
-
relative URLs resolve against.
|
|
704
|
+
relative URLs resolve against. A link to a bare fragment (`href="#main"`) is
|
|
705
|
+
the exception since 4.10: the router keeps it on the current page
|
|
706
|
+
([In-page links](#in-page-links-skip-links)). Inline-SVG fragment references
|
|
707
|
+
(`url(#gradient)`, `clip-path`) are not links, and still resolve against the base.
|
|
647
708
|
|
|
648
709
|
Repairing a URL that carries no locale, or an unknown one, belongs in that same
|
|
649
710
|
head script (`location.replace`) rather than a route guard: a guard's redirect
|
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t={tagNames:{route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function e(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function a(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class n extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const s={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function r(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function i(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}const o={static:2,param:1,"catch-all":0};class l extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,n){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&a(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&a(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):n()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=o[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(s).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${n}$`)})}}this._hasGuard=!1,e.hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||a(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath,s=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:r(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof s&&""!==s)throw new n("Navigation cancelled by guard.",s);if(!s)throw new n("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof s?s:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const h="data-wcs-ssr",c="data-wcs-ssr-link",u="@@wcs-route-ph:",d="@@wcs-route-start:",m="@@wcs-route-end:";class p extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new l(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||a(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${m}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}enableGuard(){this._core.enableGuard()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,n){if(this._initialized)return;let s;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",r=!0):this.hasAttribute("fallback")?(s="",i=!0):a(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=n;const o=n||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,i&&(n&&a(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&a(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),n&&(this._core.parentCore=n._core),this._core.parsePath(s,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const f=Symbol.for("wcstack.trustedTypes.policy"),g=Symbol.for("wcstack.trustedTypes.internal"),_="wcstack";function b(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let y=!1;function w(t){const e=function(){const t=globalThis,e=t[g];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(_,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof b()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${_}". Allow it in the CSP (\`trusted-types ${_};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[g]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=b(),s=n?.createHTML;return"function"==typeof s?(y||(y=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${_}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${_};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const N=new Map;class v extends HTMLElement{_uuid=e();constructor(){super()}async _loadTemplateFromSource(e){try{const n=await fetch(e);n.ok||a(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${n.status}`);const s=await n.text();return N.set(e,s),s}catch(n){a(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${n}`,{cause:n})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)N.has(e)?n.innerHTML=w(N.get(e)||""):n.innerHTML=w(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=w(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class C extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const P=new Set(["props","states","attr",""]);function k(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function A(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";P.has(n)||a(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const s=n,r=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);r&&void 0===customElements.get(r)?customElements.whenDefined(r).then(()=>{t.isConnected&&k(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${r}`)}):k(t,e,s)}const E=Symbol.for("wcstack.binder");function S(){const t=globalThis[E];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const $=Symbol.for("wcstack.binder.pending"),T=Symbol.for("wcstack.binder.taken");function x(){const t=globalThis;let e=t[T];return void 0===e&&(e=new WeakSet,t[T]=e),e}function R(t,e){const a=S();return null===a?(function(){const t=globalThis;let e=t[$];return void 0===e&&(e=[],t[$]=e),e}().push(t),!1):(x().add(t),a.bind(t,e),!0)}const L={range:!0};function H(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),H(a,e);return e}function z(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:H(t,new Set),r=[];let i=0;for(let o=e.nextSibling;null!==o&&o!==a&&(null===s||8!==o.nodeType||!/^@@(route:|wcs-route-)/.test(o.data)||s.has(o));o=o.nextSibling)r.push(o),(n||t.childNodeArray.includes(o))&&(i=r.length);return r.length=i,r}const I=new WeakSet;function M(e){const a=t.tagNames.router,n=t.tagNames.outlet;for(const t of e.querySelectorAll(n))I.has(t)||t.previousElementSibling?.matches(a)||(I.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${a}> uses only the element right after it as its outlet, and this page has a <${n}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${n}> you placed stays empty. Move the <${n}> right after the <${a}>.`,t))}const O=t=>{for(const e of t)if(e.nodeType===Node.ELEMENT_NODE||e.nodeType===Node.TEXT_NODE&&""!==e.textContent.trim())return!0;return!1};function U(e){console.warn(`[@wcstack/router] [wcs/layout-slot-missing] This layout's template has no default <slot>, so what its <${t.tagNames.layout}> holds outside the named slots — the nested routes and their pages — is not shown. Put a <slot></slot> where the page goes.`,e)}class F extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||a(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));const t=[];for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),e instanceof Element&&e.getAttribute("slot")||t.push(e),this.appendChild(e);!this.shadowRoot.querySelector('slot:not([name]), slot[name=""]')&&O(t)&&U(this),M(this.shadowRoot)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,r=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}r.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const i=n.get("");i?i.replaceWith(r):O(r.childNodes)&&U(this),this.appendChild(a),M(this)}!function(t){if(null!==S())for(const e of t)1===e.nodeType&&R(e,L)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){null!==this._layout&&(this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected))}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{A(e,t)}),e.hasAttribute("data-bind")&&A(e,t))}}function W(){return document.createElement(t.tagNames.layoutOutlet)}const D="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function j(t,e){let n=null,s=null;const r=e.uuid||"",i=`\n//# sourceURL=${r?`wcs-guard-handler:${r}`:"wcs-guard-handler"}\n`,o=t.text+i;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),a(function(t,e,a){return a?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${D}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${D}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return n&&"function"==typeof n.default?n.default:null}function G(e,a){j(e,a).then(e=>{e?a.guardHandler=e:(console.error(`${t.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),a.notifyGuardHandlerLoadFailed())}).catch(t=>{console.error("loadGuardHandler failed:",t),a.notifyGuardHandlerLoadFailed()})}function B(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function q(e,a,n,s){const r=document.createDocumentFragment();let i=null;const o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a,h=n;const c=l.tagName.toLowerCase();if(c===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,n),B(s,r),o=r.placeHolder,l=r,h=r,i=r}else{if(c===t.tagNames.guardHandler){const e=n??i,a=l.querySelector('script[type="module"]');null===e?console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards nothing: put it inside the route it guards.`):a?(null===n&&console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards the route before it, "${e.absolutePath}": put it inside that route.`),e.enableGuard(),G(a,e)):(e.enableGuard(),e.notifyGuardHandlerLoadFailed(),console.error(`[@wcstack/router] [wcs/guard-handler-ignored] The <${t.tagNames.guardHandler}> of route "${e.absolutePath}" has no <script type="module">, so its guard cannot run: every navigation into the route is redirected to "${e.getAttribute("guard")||"/"}".`));continue}if("template"===c){r.appendChild(l);continue}if(c===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=W();n.layout=a,o=n,l=e}}const u=await q(e,l,h,s);l.replaceChildren(),l.appendChild(u),r.appendChild(o)}else r.appendChild(a);return r}async function K(t){const e=new Map;return await q(t,t.template.content,null,e)}function V(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(X(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(X(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}function X(t){return!1!==t.checkVisibility?.()}function Y(t,e,a,n){const r=function(t,e,a){const n={},r={};let i=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){i=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,r[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){i=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,r["*"]=t,o=!0;break}l++,h++}let c=!1;return i&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:r,lastPath:""}:null}(t,e,a);r&&n.push(r);for(const s of t.routeChildNodes)Y(s,e,a,n)}function J(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),r=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)Y(t,e,r,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const r=a.absoluteWeight-n.absoluteWeight;if(0!==r)return-r;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let Q=null,Z=null;function tt(){const e=t.basenameFileExtensions;return 0===e.length?null:(Q===e&&Z||(Q=e,Z=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Z)}function et(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=tt();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function at(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function nt(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=tt();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function st(t){if(null!==t.held)return;const e=z(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)a.has(r)?s=r:null===r.parentNode||n.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),a.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const a=e.map(t=>t.parentNode);for(let n=0;n<e.length;n++)e[n].parentNode===a[n]&&t.appendChild(e[n])}(r,e),r.appendChild(t.endMarker),t.held=r}function rt(t){t.clearParams(),st(t)}function it(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{A(t,e.typedParams)}),n.hasAttribute("data-bind")&&A(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}const ot=new WeakSet;function lt(t){const e=t.placeHolder;null!==e.parentNode&&(ot.has(t)||null!==t.endMarker.parentNode?(st(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),ot.add(t))}const ht=Symbol.for("wcstack.transition-runner");function ct(t,e,a){const n=function(t){const e=globalThis[ht];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const ut=new WeakSet,dt="data-wcs";function mt(t){return t.hasAttribute(dt)||null!==t.querySelector(`[${dt}]`)}function pt(t,e,a){!ut.has(t)&&mt(t)&&(ut.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==S()||(n=t,x().has(n))||console.warn(`[@wcstack/router] ${e} contains ${dt} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${a}`)}))}function ft(t){return"AbortError"===t?.name}const gt=new WeakMap;function _t(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(R(e,L))continue}else if(null!==S())continue;pt(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function bt(e,a){try{let t=null;for(const e of a.routes){const n=await e.guardCheck(a);n&&(t=null===t?n:Object.assign({},t,n))}a.data=t,gt.delete(e)}catch(s){if(s instanceof n){const n=(gt.get(e)??0)+1;return n>10?(gt.delete(e),console.error(`${t.tagNames.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${a.path} → ${s.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(gt.set(e,n),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(s.fallbackPath)).catch(t=>{ft(t)||console.error("Fallback navigation failed:",t)}),!1)}throw s}return!0}async function yt(e,n,s,r,i=""){const o=at(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:o}),!0;let l=J(e,o);l||(e.fallbackRoute?l={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:r}:a(`${t.tagNames.router} No route matched for path: ${o}`)),l.lastPath=r,l.search=i;const h=n.lastRoutes,c=await async function(t,e,a,n){if(!await bt(t,e))return!1;n?.();const s=new Set(e.routes),r=new Set(a),i=()=>{for(const t of a)s.has(t)||rt(t);const t=[];for(const a of e.routes)(t.length>0||!r.has(a)||a.shouldChange(e.params))&&(t.push(a),it(a,e));let n=!1;for(const e of t){const t=r.has(e);t&&n||lt(e),n||=t,a.length>0&&!t&&_t(e)}};let o;return 0===a.length?i():o=ct("router",i),void 0!==o&&await o,!0}(e,l,h,()=>{e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:i,path:o},!0)});return!!c&&(e.releasePath(),n.lastRoutes=l.routes,h.length>0&&V(e,l),!0)}function wt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Nt(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:a}}function vt(t){return"?"===t?"":t}function Ct(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}const Pt=new WeakSet;function kt(t,e,a){if(Pt.has(t))return;Pt.add(t);const n=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${n}> has the attribute ${e}="${a}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const At=new WeakMap;function Et(t,e,a){const n=function(t,e){let a=At.get(t);return void 0===a&&(a=new Map,At.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}(t,e);!function(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}(t,e,void 0===a?n:null===a?null:String(a))}function St(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const $t=Object.freeze({});class Tt extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"},{name:"leaveConfirm",attribute:"leave-confirm"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=$t;_typedParams=$t;_searchParams=$t;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_unloadConfirmed=!1;_listeningUnload=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return et(t)}_normalizeBasename(t){return nt(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}set basename(t){Et(this,"basename",t)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(t){Et(this,"leave-confirm",!0===t?"Leave this page? Changes you made may not be saved.":!1===t?null:t),this._syncBeforeUnload()}_onBeforeUnload=t=>{null===this.leaveConfirm||this._unloadConfirmed||t.preventDefault()};_syncBeforeUnload(){const t=this.isConnected&&null!==this.leaveConfirm&&!St();t!==this._listeningUnload&&(this._listeningUnload=t,t?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(t){const e=this.leaveConfirm;return!(null!==e&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(at(this._normalizePathname(t),this._basename)))||(this._leaveConfirmed=window.confirm(e))}_confirmUnload(t){const e=this.leaveConfirm;null!==e&&!1!==t.cancelable&&this._hasCommitted&&!this._unloadConfirmed&&(window.confirm(e)?(this._unloadConfirmed=!0,setTimeout(()=>{this._unloadConfirmed=!1},0)):t.preventDefault?.())}_ownedByAnotherRouter(e){for(const a of document.querySelectorAll(t.tagNames.router))if(a!==this&&a instanceof Tt&&a._isOwnPath(e))return!0;return!1}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(t){const e=t.getRootNode();e.nodeType!==Node.DOCUMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE||M(e)}(this);const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||a(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||a(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t,e=!1){const a=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),s=r(t.search),o=t.data??null,l=this._data!==o,h=!i(this._params,a),c=this._routeName!==t.routeName,u=!i(this._searchParams,s),d=this._path!==t.path;l&&(this._data=o),h&&(this._params=a,this._typedParams=n),c&&(this._routeName=t.routeName),u&&(this._searchParams=s),this._path=t.path,this._hasCommitted=!0,this._leaveConfirmed=!1,l&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=d&&e,d&&!e&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{ft(e)||console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{ft(e)||console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const a=Nt(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+vt(a.search)+a.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(n)))return;const r=wt();if(r?.navigate){let t;this._leaveChecked=!0;try{t=e?r.navigate(s,{history:"replace"}):r.navigate(s)}finally{this._leaveChecked=!1}await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),r=this.isSameMatch(at(t,this._basename));await yt(this,this.outlet,t,this._path,vt(a.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_onNavigateFunc(e){if(e.defaultPrevented||e.hashChange||null!==e.downloadRequest||"reload"===e.navigationType)return;const a=new URL(e.destination.url),n=this._normalizePathname(a.pathname);if(!e.canIntercept||!this._isOwnPath(n))return void(e.canIntercept&&this._ownedByAnotherRouter(n)||this._confirmUnload(e));if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(n))return void e.preventDefault?.();const s=this.isSameMatch(at(n,this._basename)),r=s&&("push"===e.navigationType||"replace"===e.navigationType),i=a.search,o=this;e.intercept({handler:async()=>{try{await yt(o,o.outlet,n,o.path,i)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:r?"manual":"after-transition",focusReset:s||null!==o.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await yt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const e=St();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const n=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||n||"/"===s.pathname||a(`${t.tagNames.router} basename is empty, but current path is not "/".`),e||""===this._basename||n||this.getAttribute("basename")||console.warn(`[@wcstack/router] [wcs/base-href-missing] The basename "${this._basename}" was taken from this page's URL: the page has no <base href> and <${t.tagNames.router}> no basename, so routes and links resolve under it, and a deep link or a reload away from the app's root shows the wrong route. Add <base href="/"> (or the app's folder) to <head>.`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||a(`${t.tagNames.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await K(this),o=!e&&this._outlet.hasAttribute(h);if(o||this._outlet.rootNode.appendChild(i),null!==r){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}0===this.routeChildNodes.length&&a(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(h);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}await yt(this,this.outlet,l,this._path,window.location.search||""),(o||null!==S())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const r=new Map,i=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let c=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(c++,e.startsWith(u)){const a=e.slice(15);if(r.has(a)||!n.has(a))return!1;r.set(a,t)}else if(e.startsWith(d)){const a=e.slice(18);if(i.has(a)||!n.has(a))return!1;i.set(a,{comment:t,index:c})}else if(e.startsWith(m)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(i.size!==o.size)return!1;const p=[];for(const[t,e]of i){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;p.push({start:e.index,end:a.index})}for(const t of p)for(const e of p)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const f=at(e,this._basename);let g=J(this,f);if(!g){if(null===this._fallbackRoute)return!1;g={routes:[this._fallbackRoute],params:{},typedParams:{},path:f,lastPath:this._path}}if(g.lastPath=this._path,g.routes.length!==i.size)return!1;for(const t of g.routes)if(!i.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of g.routes)for(const e of t.routeChildNodes)_.add(e.absolutePath);if(r.size!==_.size)return!1;for(const t of _)if(!r.has(t))return!1;for(const[t,e]of r){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of g.routes){const a=i.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],r=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(d)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(r.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&r.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s,n)}for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(h);for(const t of g.routes)it(t,g);return this.outlet.lastRoutes=g.routes,!await bt(this,g)||(this.commitNavigation({params:g.params,typedParams:g.typedParams,routeName:g.routes[g.routes.length-1].name,data:g.data??null,search:window.location.search||"",path:f}),!0)}async _renderForSsr(e){const n=at(e,this._basename),s=J(this,n),r=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&a(`${t.tagNames.router} No route matched for path: ${n}`),!r.some(t=>t.hasGuard)){await yt(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${u}${t.absolutePath}`}),this.outlet.setAttribute(h,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${d}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&R(e,L)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0===a)return;const n=t.getAttribute;for(const e of a){const a=e.name,s="function"==typeof n?n.call(t,a.toLowerCase()):null;if(null!==s&&s.startsWith("[object ")&&kt(t,a,s),!Object.prototype.hasOwnProperty.call(t,a))continue;if(!Ct(t,a))continue;const r=t,i=r[a];delete r[a],r[a]=i}}(this),this._syncBeforeUnload(),St()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=wt();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(wt()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const xt=["title","rel","target","download","hreflang","lang","dir"];class Rt extends HTMLElement{static get observedAttributes(){return["to","match",...xt]}_childNodeArray=[];_uuid=e();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(t.tagNames.router);if(e)return this._router=e;const n=this.getRootNode(),s=n.querySelector?.(t.tagNames.router);if(s)return this._router=s;a(`${t.tagNames.link} is not connected to a router.`)}_initialize(){St()||(this.style.display="none"),this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return et(t)}_joinInternalPath(t,e){const a=nt(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,n){if(""!==n)if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=Nt(n),r=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=r+vt(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}else e.removeAttribute("href")}connectedCallback(){St()?queueMicrotask(()=>{if(this.isConnected)try{this._connect()}catch(t){console.error(t)}}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(c)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(c),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||xt.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,St())return this._updateActiveState(),void a.setAttribute(c,"");wt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),""!==this._path&&!this._isInternalTarget(this._path)||wt()?.navigate||(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){wt()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("match"!==t||e===a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(xt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}else this._updateActiveState()}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=Nt(this._path),a=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e),n=""!==this._path&&t===a,s=!n&&""!==this._path&&"prefix"===this.getAttribute("match")&&t.startsWith(a+"/");this._anchorElement&&(n||s?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",n?"page":"true")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Lt=[],Ht=new Map;let zt=!1;const It=new WeakMap,Mt=new WeakMap;class Ot extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super()}_initialize(){if(!this._initialized&&(this._initialized=!0,this._childElementArray=Array.from(this.children),!St())){this.style.display="none";for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),zt||(this._captureInitialHead(),zt=!0),Lt.push(this),this._reapplyHead()}disconnectedCallback(){const t=Lt.indexOf(this);-1!==t&&Lt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_cloneOf(t){if(!mt(t))return t.cloneNode(!0);let e=Mt.get(t);return void 0===e&&(e=t.cloneNode(!0),Mt.set(t,e)),e}_getKey(t){const e=It.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return It.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Ht.has(t)||Ht.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of Lt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Ht.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=Lt.length-1;t>=0;t--){const a=Lt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=this._cloneOf(t);break}if(e)break}if(!e&&Ht.has(n)){e=Ht.get(n).cloneNode(!0)}const s=a.get(n)??null;null!==e&&s===e||(e&&s?.isEqualNode(e)&&!mt(e)||(e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),R(e)||pt(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(s?.remove(),a.delete(n))))}}}function Ut(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,v),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,F),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,C),e.get(t.tagNames.route)||e.define(t.tagNames.route,p),e.get(t.tagNames.router)||e.define(t.tagNames.router,Tt),e.get(t.tagNames.link)||e.define(t.tagNames.link,Rt),e.get(t.tagNames.head)||e.define(t.tagNames.head,Ot)}var Ft;await void Ut(Ft);
|
|
1
|
+
const t={tagNames:{route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},enableShadowRoot:!1,basenameFileExtensions:[".html"]};function e(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function a(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}class n extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}}const s={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,a,n]=t.split("-").map(Number),s=new Date(e,a-1,n);return s.getFullYear()===e&&s.getMonth()===a-1&&s.getDate()===n?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function r(t){const e={};for(const[a,n]of new URLSearchParams(t))e[a]=n;return Object.freeze(e)}function i(t,e){const a=Object.keys(t),n=Object.keys(e);if(a.length!==n.length)return!1;for(const n of a){if(!Object.prototype.hasOwnProperty.call(e,n))return!1;if(t[n]!==e[n])return!1}return!0}const o={static:2,param:1,"catch-all":0};class l extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(e,n){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&a(`${t.tagNames.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&a(`${t.tagNames.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?e(this._parentCore):n()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=o[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const a=t.split("/");for(let t=0;t<a.length;t++){const n=a[t];if(!(""===n&&t===a.length-1&&t>0)){if("*"===n){this._segmentInfos.push({type:"catch-all",segmentText:n,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(n.startsWith(":")){const t=n.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,a="any";t?(e=t[1],t[3]&&Object.keys(s).includes(t[3])&&(a=t[3])):e=n.substring(1),this._segmentInfos.push({type:"param",segmentText:n,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:a})}else""===n&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:n,paramName:null,pattern:new RegExp(`^${n}$`)})}}this._hasGuard=!1,e.hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this.enableGuard())}enableGuard(){this._hasGuard||(this._hasGuard=!0,this._guardFallbackPath||="/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const a=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),a||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||a(`${t.tagNames.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,a=t.lastPath,s=await this._guardHandler(e,a,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:r(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof s&&""!==s)throw new n("Navigation cancelled by guard.",s);if(!s)throw new n("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof s?s:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new n("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}}const h="data-wcs-ssr",c="data-wcs-ssr-link",u="@@wcs-route-ph:",d="@@wcs-route-start:",m="@@wcs-route-end:";class f extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=e();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_endMarker;held=null;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new l(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||a(`${t.tagNames.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get endMarker(){return void 0===this._endMarker&&(this._endMarker=document.createComment(`${m}${this.absolutePath}`)),this._endMarker}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t,e){for(this._childNodeArray=[...t],e&&(this._endMarker=e);this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}enableGuard(){this._core.enableGuard()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(e,n){if(this._initialized)return;let s;this._initialized=!0;let r=!1,i=!1;this.hasAttribute("path")?s=this.getAttribute("path")||"":this.hasAttribute("index")?(s="",r=!0):this.hasAttribute("fallback")?(s="",i=!0):a(`${t.tagNames.route} should have a "path" or "index" attribute.`),this._routerNode=e,this._routeParentNode=n;const o=n||e;o.routeChildNodes.push(this),this._childIndex=o.routeChildNodes.length-1,i&&(n&&a(`${t.tagNames.route} with fallback attribute must be a direct child of ${t.tagNames.router}.`),e.fallbackRoute&&a(`${t.tagNames.router} can have only one fallback route.`),e.fallbackRoute=this),n&&(this._core.parentCore=n._core),this._core.parsePath(s,{isIndex:r,isFallback:i,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}}const p=Symbol.for("wcstack.trustedTypes.policy"),g=Symbol.for("wcstack.trustedTypes.internal"),_="wcstack";function b(){const t=globalThis[p];return null===t||"object"!=typeof t?null:t}let y=!1;function w(t){const e=function(){const t=globalThis,e=t[g];if(void 0!==e)return e;const a=globalThis.trustedTypes;let n=null;if(a&&"function"==typeof a.createPolicy)try{n=a.createPolicy(_,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof b()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${_}". Allow it in the CSP (\`trusted-types ${_};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[g]=n,n}(),a=e?.createHTML;if("function"==typeof a)return a.call(e,t);if(!("trustedTypes"in globalThis))return t;const n=b(),s=n?.createHTML;return"function"==typeof s?(y||(y=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${_}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${_};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(n,t)):t}const N=new Map;class v extends HTMLElement{_uuid=e();constructor(){super()}async _loadTemplateFromSource(e){try{const n=await fetch(e);n.ok||a(`${t.tagNames.layout} failed to fetch layout from source: ${e}, status: ${n.status}`);const s=await n.text();return N.set(e,s),s}catch(n){a(`${t.tagNames.layout} failed to load layout from source: ${e}, error: ${n}`,{cause:n})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const e=this.getAttribute("src"),a=this.getAttribute("layout");e&&a&&console.warn(`${t.tagNames.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(e)N.has(e)?n.innerHTML=w(N.get(e)||""):n.innerHTML=w(await this._loadTemplateFromSource(e)||"");else if(a){const e=this._loadTemplateFromDocument(a);e?n.innerHTML=w(e):console.warn(`${t.tagNames.layout} could not find template with id "${a}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}get name(){return this.getAttribute("name")||""}}class C extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||a(`${t.tagNames.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&t.enableShadowRoot}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}}const P=new Set(["props","states","attr",""]);function k(t,e,a){for(const[n,s]of Object.entries(e))switch(a){case"props":t.props={...t.props,[n]:s};break;case"states":t.states={...t.states,[n]:s};break;case"attr":null==s?t.removeAttribute(n):t.setAttribute(n,String(s));break;case"":t[n]=s}}function A(t,e){t.hasAttribute("data-bind")||a(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";P.has(n)||a(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const s=n,r=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const a=t.getAttribute("is");return a&&a.includes("-")?a:null}(t);r&&void 0===customElements.get(r)?customElements.whenDefined(r).then(()=>{t.isConnected&&k(t,e,s)}).catch(()=>{a(`Failed to define custom element: ${r}`)}):k(t,e,s)}const E=Symbol.for("wcstack.binder");function S(){const t=globalThis[E];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const $=Symbol.for("wcstack.binder.pending"),L=Symbol.for("wcstack.binder.taken");function T(){const t=globalThis;let e=t[L];return void 0===e&&(e=new WeakSet,t[L]=e),e}function R(t,e){const a=S();return null===a?(function(){const t=globalThis;let e=t[$];return void 0===e&&(e=[],t[$]=e),e}().push(t),!1):(T().add(t),a.bind(t,e),!0)}const x={range:!0};function H(t,e){for(const a of t.routeChildNodes)e.add(a.placeHolder).add(a.endMarker),H(a,e);return e}function z(t){const e=t.placeHolder,a=t.endMarker,n=null!==a.parentNode&&a.parentNode===e.parentNode&&!!(4&e.compareDocumentPosition(a)),s=n?null:H(t,new Set),r=[];let i=0;for(let o=e.nextSibling;null!==o&&o!==a&&(null===s||8!==o.nodeType||!/^@@(route:|wcs-route-)/.test(o.data)||s.has(o));o=o.nextSibling)r.push(o),(n||t.childNodeArray.includes(o))&&(i=r.length);return r.length=i,r}const I=new WeakSet;function M(e){const a=t.tagNames.router,n=t.tagNames.outlet;for(const t of e.querySelectorAll(n))I.has(t)||t.previousElementSibling?.matches(a)||(I.add(t),console.warn(`[@wcstack/router] [wcs/router-outlet-misplaced] A <${a}> uses only the element right after it as its outlet, and this page has a <${n}> that no router uses. The router makes an outlet of its own right after itself, so the routes render there and the <${n}> you placed stays empty. Move the <${n}> right after the <${a}>.`,t))}const O=t=>{for(const e of t)if(e.nodeType===Node.ELEMENT_NODE||e.nodeType===Node.TEXT_NODE&&""!==e.textContent.trim())return!0;return!1};function U(e){console.warn(`[@wcstack/router] [wcs/layout-slot-missing] This layout's template has no default <slot>, so what its <${t.tagNames.layout}> holds outside the named slots — the nested routes and their pages — is not shown. Put a <slot></slot> where the page goes.`,e)}class F extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||a(`${t.tagNames.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const e=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(e.content.cloneNode(!0));const t=[];for(const e of Array.from(this.layout.childNodes))this._layoutChildNodes.push(e),e instanceof Element&&e.getAttribute("slot")||t.push(e),this.appendChild(e);!this.shadowRoot.querySelector('slot:not([name]), slot[name=""]')&&O(t)&&U(this),M(this.shadowRoot)}else{const a=e.content.cloneNode(!0),n=new Map;a.querySelectorAll("slot").forEach(e=>{const a=e.getAttribute("name")||"";n.has(a)?console.warn(`${t.tagNames.layoutOutlet} duplicate slot name "${a}" in layout template.`):n.set(a,e)});const s=new Map,r=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){s.has(e)||s.set(e,document.createDocumentFragment()),s.get(e)?.appendChild(t);continue}}r.appendChild(t)}for(const[t,e]of n){const a=s.get(t);a&&e.replaceWith(a)}const i=n.get("");i?i.replaceWith(r):O(r.childNodes)&&U(this),this.appendChild(a),M(this)}!function(t){if(null!==S())for(const e of t)1===e.nodeType&&R(e,x)}(Array.from(this.childNodes))}finally{this._initializing=!1}}async connectedCallback(){null!==this._layout&&(this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected))}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{A(e,t)}),e.hasAttribute("data-bind")&&A(e,t))}}function W(){return document.createElement(t.tagNames.layoutOutlet)}const D="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";async function j(t,e){let n=null,s=null;const r=e.uuid||"",i=`\n//# sourceURL=${r?`wcs-guard-handler:${r}`:"wcs-guard-handler"}\n`,o=t.text+i;let l=!1;const h=t=>{t.effectiveDirective.startsWith("script-src")&&(l=!0)};document.addEventListener("securitypolicyviolation",h);try{if("function"==typeof URL.createObjectURL){const t=new Blob([o],{type:"application/javascript"}),e=URL.createObjectURL(t);try{n=await import(e)}catch(t){s=t}finally{URL.revokeObjectURL(e)}}if(!n){const t=btoa(String.fromCodePoint(...(new TextEncoder).encode(o)));try{n=await import(`data:application/javascript;base64,${t}`)}catch(t){await new Promise(t=>setTimeout(t)),a(function(t,e,a){return a?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL: give the page's nonce to the <script> that loads @wcstack/router, or allow blob: in script-src. See ${D}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${D}`}(t,s,l),{cause:s??t})}}}finally{document.removeEventListener("securitypolicyviolation",h)}return n&&"function"==typeof n.default?n.default:null}function G(e,a){j(e,a).then(e=>{e?a.guardHandler=e:(console.error(`${t.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`),a.notifyGuardHandlerLoadFailed())}).catch(t=>{console.error("loadGuardHandler failed:",t),a.notifyGuardHandlerLoadFailed()})}function B(t,e){let a=t.get(e.absolutePath);a||(a=[]);for(const t of a)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}a.push(e),1===a.length&&t.set(e.absolutePath,a)}async function q(e,a,n,s){const r=document.createDocumentFragment();let i=null;const o=Array.from(a.childNodes);for(const a of o)if(a.nodeType===Node.ELEMENT_NODE){let o=a,l=a,h=n;const c=l.tagName.toLowerCase();if(c===t.tagNames.route){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const a=document.importNode(l,!0);customElements.upgrade(a),a.appendChild(t);const r=a;r.initialize(e,n),B(s,r),o=r.placeHolder,l=r,h=r,i=r}else{if(c===t.tagNames.guardHandler){const e=n??i,a=l.querySelector('script[type="module"]');null===e?console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards nothing: put it inside the route it guards.`):a?(null===n&&console.error(`[@wcstack/router] [wcs/guard-handler-ignored] A <${t.tagNames.guardHandler}> outside a <${t.tagNames.route}> guards the route before it, "${e.absolutePath}": put it inside that route.`),e.enableGuard(),G(a,e)):(e.enableGuard(),e.notifyGuardHandlerLoadFailed(),console.error(`[@wcstack/router] [wcs/guard-handler-ignored] The <${t.tagNames.guardHandler}> of route "${e.absolutePath}" has no <script type="module">, so its guard cannot run: every navigation into the route is redirected to "${e.getAttribute("guard")||"/"}".`));continue}if("template"===c){r.appendChild(l);continue}if(c===t.tagNames.layout){const t=document.createDocumentFragment();for(const e of Array.from(l.childNodes))t.appendChild(e);const e=document.importNode(l,!0);customElements.upgrade(e),e.appendChild(t);const a=e,n=W();n.layout=a,o=n,l=e}}const u=await q(e,l,h,s);l.replaceChildren(),l.appendChild(u),r.appendChild(o)}else r.appendChild(a);return r}async function K(t){const e=new Map;return await q(t,t.template.content,null,e)}function V(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(X(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(X(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}function X(t){return!1!==t.checkVisibility?.()}function Y(t,e,a,n){const r=function(t,e,a){const n={},r={};let i=!0,o=!1,l=0,h=0;for(;l<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[l];if(e.isIndex){l++;continue}if(0===l&&""===e.segmentText&&"static"===e.type){l++;continue}const c=a[h];if(void 0===c){i=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",a=s[t].parse(c);void 0!==a&&(e.paramName&&(n[e.paramName]=c,r[e.paramName]=a),u=!0)}else u=null!==e.pattern.exec(c);if(!u){i=!1;break}if("catch-all"===e.type){const t=a.slice(h).join("/");n["*"]=t,r["*"]=t,o=!0;break}l++,h++}let c=!1;return i&&(o||l===t.absoluteSegmentInfos.length&&h===a.length)&&(c=!0),c?{path:e,routes:t.routes,params:n,typedParams:r,lastPath:""}:null}(t,e,a);r&&n.push(r);for(const s of t.routeChildNodes)Y(s,e,a,n)}function J(t,e){const a=t.routeChildNodes,n=[],s=e.split("/"),r=s.filter((t,e)=>(0!==e||""!==t)&&!(e===s.length-1&&""===t&&s.length>1));for(const t of a)Y(t,e,r,n);return n.sort((t,e)=>{const a=t.routes.at(-1),n=e.routes.at(-1),s=a.absoluteSegmentCount-n.absoluteSegmentCount;if(0!==s)return-s;const r=a.absoluteWeight-n.absoluteWeight;if(0!==r)return-r;return a.childIndex-n.childIndex}),n.length>0?n[0]:null}let Q=null,Z=null;function tt(){const e=t.basenameFileExtensions;return 0===e.length?null:(Q===e&&Z||(Q=e,Z=new RegExp(`\\/[^/]+(?:${e.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Z)}function et(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=tt();return a&&(e=e.replace(a,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function at(t,e){let a=t;return""!==e&&(t===e?a="":t.startsWith(e+"/")&&(a=t.slice(e.length))),""===a?"/":a}function nt(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const a=tt();return a&&(e=e.replace(a,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function st(t){if(null!==t.held)return;const e=z(t),a=new Set(e),n=[...e,...t.childNodeArray];let s=null;for(const r of t.childNodeArray)a.has(r)?s=r:null===r.parentNode||n.some(t=>t!==r&&t.contains(r))||(e.splice(null===s?0:e.indexOf(s)+1,0,r),a.add(r),s=r);const r=document.createDocumentFragment();!function(t,e){const a=e.map(t=>t.parentNode);for(let n=0;n<e.length;n++)e[n].parentNode===a[n]&&t.appendChild(e[n])}(r,e),r.appendChild(t.endMarker),t.held=r}function rt(t){t.clearParams(),st(t)}function it(e,a){const n={},s={};for(const t of e.paramNames)n[t]=a.params[t],s[t]=a.typedParams[t];e.setParams(n,s);for(const a of e.childNodeArray)if(a.nodeType===Node.ELEMENT_NODE){const n=a;n.querySelectorAll("[data-bind]").forEach(t=>{A(t,e.typedParams)}),n.hasAttribute("data-bind")&&A(n,e.typedParams),n.querySelectorAll(t.tagNames.layoutOutlet).forEach(t=>{t.assignParams(e.typedParams)}),n.tagName.toLowerCase()===t.tagNames.layoutOutlet&&n.assignParams(e.typedParams)}}const ot=new WeakSet;function lt(t){const e=t.placeHolder;null!==e.parentNode&&(ot.has(t)||null!==t.endMarker.parentNode?(st(t),e.after(t.held),t.held=null):e.after(...t.childNodeArray,t.endMarker),ot.add(t))}const ht=Symbol.for("wcstack.transition-runner");function ct(t,e,a){const n=function(t){const e=globalThis[ht];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==n)return n.run(e,{source:t,types:a});e()}const ut=new WeakSet,dt="data-wcs";function mt(t){return t.hasAttribute(dt)||null!==t.querySelector(`[${dt}]`)}function ft(t,e,a){!ut.has(t)&&mt(t)&&(ut.add(t),function(t){if("complete"!==document.readyState)return void window.addEventListener("load",t,{once:!0});t()}(()=>{var n;null!==S()||(n=t,T().has(n))||console.warn(`[@wcstack/router] ${e} contains ${dt} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${a}`)}))}function pt(t){return"AbortError"===t?.name}const gt=new WeakMap;function _t(t){for(const e of t.childNodeArray)if(1===e.nodeType){if(e.isConnected){if(R(e,x))continue}else if(null!==S())continue;ft(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.')}}async function bt(e,a){try{let t=null;for(const e of a.routes){const n=await e.guardCheck(a);n&&(t=null===t?n:Object.assign({},t,n))}a.data=t,gt.delete(e)}catch(s){if(s instanceof n){const n=(gt.get(e)??0)+1;return n>10?(gt.delete(e),console.error(`${t.tagNames.router}: guard redirect loop — stopped after 10 redirects in a row (the last: ${a.path} → ${s.fallbackPath}). The guards of these routes send each other back and forth.`),!1):(gt.set(e,n),e.connectedCallbackPromise.catch(()=>{}).then(()=>e.replace(s.fallbackPath)).catch(t=>{pt(t)||console.error("Fallback navigation failed:",t)}),!1)}throw s}return!0}async function yt(e,n,s,r,i=""){const o=at(s,e.basename);if(e.isSameMatch(o))return e.commitNavigation({params:e.params,typedParams:e.typedParams,routeName:e.routeName,data:e.data,search:i,path:o}),!0;let l=J(e,o);l||(e.fallbackRoute?l={routes:[e.fallbackRoute],params:{},typedParams:{},path:o,lastPath:r}:a(`${t.tagNames.router} No route matched for path: ${o}`)),l.lastPath=r,l.search=i;const h=n.lastRoutes,c=await async function(t,e,a,n){if(!await bt(t,e))return!1;n?.();const s=new Set(e.routes),r=new Set(a),i=()=>{for(const t of a)s.has(t)||rt(t);const t=[];for(const a of e.routes)(t.length>0||!r.has(a)||a.shouldChange(e.params))&&(t.push(a),it(a,e));let n=!1;for(const e of t){const t=r.has(e);t&&n||lt(e),n||=t,a.length>0&&!t&&_t(e)}};let o;return 0===a.length?i():o=ct("router",i),void 0!==o&&await o,!0}(e,l,h,()=>{e.commitNavigation({params:l.params,typedParams:l.typedParams,routeName:l.routes[l.routes.length-1]?.name??"",data:l.data??null,search:i,path:o},!0)});return!!c&&(e.releasePath(),n.lastRoutes=l.routes,h.length>0&&V(e,l),!0)}function wt(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function Nt(t){let e=t,a="";const n=e.indexOf("#");n>=0&&(a=e.slice(n),e=e.slice(0,n));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:a}}function vt(t){return"?"===t?"":t}function Ct(t,e){let a=Object.getPrototypeOf(t);for(;null!==a;){const t=Object.getOwnPropertyDescriptor(a,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;a=Object.getPrototypeOf(a)}return!1}const Pt=new WeakSet;function kt(t,e,a){if(Pt.has(t))return;Pt.add(t);const n=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${n}> has the attribute ${e}="${a}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const At=new WeakMap;function Et(t,e,a){const n=function(t,e){let a=At.get(t);return void 0===a&&(a=new Map,At.set(t,a)),a.has(e)||a.set(e,t.getAttribute(e)),a.get(e)}(t,e);!function(t,e,a){null===a?t.removeAttribute(e):t.setAttribute(e,a)}(t,e,void 0===a?n:null===a?null:String(a))}function St(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}function $t(t){if(!t||"a"!==t.localName&&"area"!==t.localName)return null;const e=t.getAttribute("href")?.trim();return void 0!==e&&e.startsWith("#")?e:null}function Lt(t){const e=new URL(window.location.href),a=new URL(t);return e.hash="",a.hash="",e.href===a.href}function Tt(t){const e=function(t){if(""===t)return null;const e=t=>document.getElementById(t)??Array.from(document.getElementsByName(t)).find(t=>"a"===t.localName)??null,a=e(t);if(null!==a)return a;let n;try{n=decodeURIComponent(t)}catch{return null}return n===t?null:e(n)}(t);null!==e&&(e.matches("a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable], audio[controls], video[controls], [tabindex]")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}))}function Rt(t){const e=new URL(t,window.location.href);window.location.assign(e.href),Tt(e.hash.slice(1))}const xt=Object.freeze({});class Ht extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"},{name:"leaveConfirm",attribute:"leave-confirm"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_listeningClick=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=xt;_typedParams=xt;_searchParams=xt;_routeName="";_data=null;_hasCommitted=!1;_pathHeld=!1;_leaveChecked=!1;_leaveConfirmed=!1;_unloadConfirmed=!1;_listeningUnload=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return et(t)}_normalizeBasename(t){return nt(t)}_joinInternalPath(t,e){const a=this._normalizeBasename(t);let n=e.startsWith("/")?e:"/"+e;return n=this._normalizePathname(n),a?"/"===n?a+"/":a+n:n}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}set basename(t){Et(this,"basename",t)}get leaveConfirm(){return this.getAttribute("leave-confirm")||null}set leaveConfirm(t){Et(this,"leave-confirm",!0===t?"Leave this page? Changes you made may not be saved.":!1===t?null:t),this._syncBeforeUnload()}_onBeforeUnload=t=>{null===this.leaveConfirm||this._unloadConfirmed||t.preventDefault()};_syncBeforeUnload(){const t=this.isConnected&&null!==this.leaveConfirm&&!St();t!==this._listeningUnload&&(this._listeningUnload=t,t?window.addEventListener("beforeunload",this._onBeforeUnload):window.removeEventListener("beforeunload",this._onBeforeUnload))}_confirmLeave(t){const e=this.leaveConfirm;return!(null!==e&&this._hasCommitted&&!this._leaveConfirmed&&!this.isSameMatch(at(this._normalizePathname(t),this._basename)))||(this._leaveConfirmed=window.confirm(e))}_confirmUnload(t){const e=this.leaveConfirm;null!==e&&!1!==t.cancelable&&this._hasCommitted&&!this._unloadConfirmed&&(window.confirm(e)?(this._unloadConfirmed=!0,setTimeout(()=>{this._unloadConfirmed=!1},0)):t.preventDefault?.())}_ownedByAnotherRouter(e){for(const a of document.querySelectorAll(t.tagNames.router))if(a!==this&&a instanceof Ht&&a._isOwnPath(e))return!0;return!1}_getOutlet(){const e=this.nextElementSibling;if(e&&e.matches(t.tagNames.outlet))return e;!function(t){const e=t.getRootNode();e.nodeType!==Node.DOCUMENT_NODE&&e.nodeType!==Node.DOCUMENT_FRAGMENT_NODE||M(e)}(this);const a=document.createElement(t.tagNames.outlet);return this.parentNode?this.parentNode.insertBefore(a,this.nextSibling):document.body.appendChild(a),a}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||a(`${t.tagNames.router} has no outlet.`),this._outlet}get template(){return this._template||a(`${t.tagNames.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t,e=!1){const a=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),s=r(t.search),o=t.data??null,l=this._data!==o,h=!i(this._params,a),c=this._routeName!==t.routeName,u=!i(this._searchParams,s),d=this._path!==t.path;l&&(this._data=o),h&&(this._params=a,this._typedParams=n),c&&(this._routeName=t.routeName),u&&(this._searchParams=s),this._path=t.path,this._hasCommitted=!0,this._leaveConfirmed=!1,l&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),h&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),u&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),this._pathHeld=d&&e,d&&!e&&this._firePathChanged()}releasePath(){this._pathHeld&&(this._pathHeld=!1,this._firePathChanged())}_firePathChanged(){this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:this._path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(e){null!=e&&""!==e&&this._navigateUrl!==e&&(this._navigateUrl=e,this.navigate(e).catch(e=>{pt(e)||console.error(`${t.tagNames.router} navigate failed:`,e)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(e){null!=e&&""!==e&&this._replaceUrl!==e&&(this._replaceUrl=e,this.replace(e).catch(e=>{pt(e)||console.error(`${t.tagNames.router} replace failed:`,e)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const a=Nt(t),n=""!==a.pathname||""===a.search&&""===a.hash?this._joinInternalPath(this._basename,a.pathname):window.location.pathname,s=n+vt(a.search)+a.hash;if(null!==this.leaveConfirm&&(await Promise.resolve(),!this._confirmLeave(n)))return;const r=wt();if(r?.navigate){let t;this._leaveChecked=!0;try{t=e?r.navigate(s,{history:"replace"}):r.navigate(s)}finally{this._leaveChecked=!1}await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(n),r=this.isSameMatch(at(t,this._basename));await yt(this,this.outlet,t,this._path,vt(a.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||(t===this._basename||t.startsWith(this._basename+"/"))}_ownsCurrentPage(){return this._isOwnPath(this._normalizePathname(window.location.pathname))}_onFragmentLinkNavigate(t,e){if(!this._ownsCurrentPage())return;const a=t.destination.url;Lt(a)?Tt(new URL(a).hash.slice(1)):(t.preventDefault?.(),Rt(e))}_onNavigateFunc(e){if(e.defaultPrevented||null!==e.downloadRequest||"reload"===e.navigationType)return;const a=e.sourceElement,n=a?.ownerDocument===document?$t(a):null;if(null!==n)return void this._onFragmentLinkNavigate(e,n);if(e.hashChange||e.destination.url.includes("#")&&Lt(e.destination.url))return;const s=new URL(e.destination.url),r=this._normalizePathname(s.pathname);if(!e.canIntercept||!this._isOwnPath(r))return void(e.canIntercept&&this._ownedByAnotherRouter(r)||this._confirmUnload(e));if(!this._leaveChecked&&!1!==e.cancelable&&!this._confirmLeave(r))return void e.preventDefault?.();const i=this.isSameMatch(at(r,this._basename)),o=i&&("push"===e.navigationType||"replace"===e.navigationType),l=s.search,h=this;e.intercept({handler:async()=>{try{await yt(h,h.outlet,r,h.path,l)}catch(e){throw console.error(`${t.tagNames.router} applyRoute failed:`,e),e}},scroll:o?"manual":"after-transition",focusReset:i||null!==h.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await yt(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};_onClick=t=>{if(t.defaultPrevented||0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const e=t.composedPath().find(t=>t instanceof Element&&("a"===t.localName||"area"===t.localName)&&t.hasAttribute("href")),a=$t(e);null!==a&&!e.hasAttribute("download")&&function(t){const e=t.getAttribute("target")??document.querySelector("base[target]")?.getAttribute("target")??"";return""===e||"_self"===e.toLowerCase()}(e)&&this._ownsCurrentPage()&&(t.preventDefault(),Rt(a))};async _initialize(){this._initializing=!0;try{const e=St();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const n=null!==document.querySelector("base[href]"),s=new URL(window.location.href);""!==this._basename||n||"/"===s.pathname||a(`${t.tagNames.router} basename is empty, but current path is not "/".`),e||""===this._basename||n||this.getAttribute("basename")||console.warn(`[@wcstack/router] [wcs/base-href-missing] The basename "${this._basename}" was taken from this page's URL: the page has no <base href> and <${t.tagNames.router}> no basename, so routes and links resolve under it, and a deep link or a reload away from the app's root shows the wrong route. Add <base href="/"> (or the app's folder) to <head>.`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||a(`${t.tagNames.router} should have a <template> child element.`);const r=e?this._template.content.cloneNode(!0):null,i=await K(this),o=!e&&this._outlet.hasAttribute(h);if(o||this._outlet.rootNode.appendChild(i),null!==r){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(r)}0===this.routeChildNodes.length&&a(`${t.tagNames.router} has no route definitions.`),e||this._ensureA11yRegion();const l=this._normalizePathname(window.location.pathname);if(e)return await this._renderForSsr(l),void(this._initialized=!0);if(o){if(await this._hydrateFromSsr(l))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(h);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(i)}await yt(this,this.outlet,l,this._path,window.location.search||""),(o||null!==S())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(e){const a=this.outlet.rootNode,n=new Map;let s=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?s=!0:n.set(t.absolutePath,t)}),s)return!1;if(null!==a.querySelector(t.tagNames.layoutOutlet))return!1;const r=new Map,i=new Map,o=new Map,l=document.createTreeWalker(a,NodeFilter.SHOW_COMMENT);let c=0;for(;l.nextNode();){const t=l.currentNode,e=t.data;if(c++,e.startsWith(u)){const a=e.slice(15);if(r.has(a)||!n.has(a))return!1;r.set(a,t)}else if(e.startsWith(d)){const a=e.slice(18);if(i.has(a)||!n.has(a))return!1;i.set(a,{comment:t,index:c})}else if(e.startsWith(m)){const a=e.slice(16);if(o.has(a)||!n.has(a))return!1;o.set(a,{comment:t,index:c})}}if(i.size!==o.size)return!1;const f=[];for(const[t,e]of i){const a=o.get(t);if(!a)return!1;if(a.comment.parentNode!==e.comment.parentNode)return!1;if(a.index<=e.index)return!1;f.push({start:e.index,end:a.index})}for(const t of f)for(const e of f)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const p=at(e,this._basename);let g=J(this,p);if(!g){if(null===this._fallbackRoute)return!1;g={routes:[this._fallbackRoute],params:{},typedParams:{},path:p,lastPath:this._path}}if(g.lastPath=this._path,g.routes.length!==i.size)return!1;for(const t of g.routes)if(!i.has(t.absolutePath))return!1;const _=new Set;for(const t of this.routeChildNodes)_.add(t.absolutePath);for(const t of g.routes)for(const e of t.routeChildNodes)_.add(e.absolutePath);if(r.size!==_.size)return!1;for(const t of _)if(!r.has(t))return!1;for(const[t,e]of r){const a=n.get(t);e.parentNode.replaceChild(a.placeHolder,e)}for(const e of g.routes){const a=i.get(e.absolutePath).comment,n=o.get(e.absolutePath).comment,s=[],r=new Set;let l=a.nextSibling;for(;null!==l&&l!==n;){if(l.nodeType===Node.COMMENT_NODE){const t=l.data;if(t.startsWith(d)){const e=t.slice(18);l=o.get(e).comment.nextSibling;continue}}if(r.has(l))l=l.nextSibling;else{if(l.nodeType===Node.ELEMENT_NODE&&l.tagName.toLowerCase()===t.tagNames.link){const t=l.anchorElement;null!==t&&r.add(t)}s.push(l),l=l.nextSibling}}e.adoptChildNodes(s,n)}for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(h);for(const t of g.routes)it(t,g);return this.outlet.lastRoutes=g.routes,!await bt(this,g)||(this.commitNavigation({params:g.params,typedParams:g.typedParams,routeName:g.routes[g.routes.length-1].name,data:g.data??null,search:window.location.search||"",path:p}),!0)}async _renderForSsr(e){const n=at(e,this._basename),s=J(this,n),r=s?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===r.length&&a(`${t.tagNames.router} No route matched for path: ${n}`),!r.some(t=>t.hasGuard)){await yt(this,this.outlet,e,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${u}${t.absolutePath}`}),this.outlet.setAttribute(h,"");for(const t of this.outlet.lastRoutes)t.placeHolder.after(document.createComment(`${d}${t.absolutePath}`))}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&e.isConnected&&R(e,x)}_forEachRoute(t,e=this){for(const a of e.routeChildNodes)t(a),this._forEachRoute(t,a)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,a=e?.inputs;if(void 0===a)return;const n=t.getAttribute;for(const e of a){const a=e.name,s="function"==typeof n?n.call(t,a.toLowerCase()):null;if(null!==s&&s.startsWith("[object ")&&kt(t,a,s),!Object.prototype.hasOwnProperty.call(t,a))continue;if(!Ct(t,a))continue;const r=t,i=r[a];delete r[a],r[a]=i}}(this),this._syncBeforeUnload(),St()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=wt();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),t&&function(){const t=globalThis.NavigateEvent;return"function"==typeof t&&"sourceElement"in t.prototype}()||this._listeningClick||(window.addEventListener("click",this._onClick),this._listeningClick=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(wt()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),this._listeningClick&&(window.removeEventListener("click",this._onClick),this._listeningClick=!1),this._syncBeforeUnload(),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const zt=["title","rel","target","download","hreflang","lang","dir"];class It extends HTMLElement{static get observedAttributes(){return["to","match",...zt]}_childNodeArray=[];_uuid=e();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const e=this.closest(t.tagNames.router);if(e)return this._router=e;const n=this.getRootNode(),s=n.querySelector?.(t.tagNames.router);if(s)return this._router=s;a(`${t.tagNames.link} is not connected to a router.`)}_initialize(){St()||(this.style.display="none"),this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return et(t)}_joinInternalPath(t,e){const a=nt(t),n=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(n);return a?"/"===s?a+"/":a+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(e,n){if(""!==n)if(this._isInternalTarget(n)){const{pathname:t,search:a,hash:s}=Nt(n),r=""===t?window.location.pathname:this._joinInternalPath(this.router.basename,t);e.href=r+vt(a)+s}else try{e.href=new URL(n).toString()}catch{a(`[${t.tagNames.link}] Invalid URL in 'to' attribute: ${n}`)}else e.removeAttribute("href")}connectedCallback(){St()?queueMicrotask(()=>{if(this.isConnected)try{this._connect()}catch(t){console.error(t)}}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(c)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let a;if(null!==e)a=e,a.removeAttribute(c),this._childNodeArray=Array.from(a.childNodes),this._setAnchorHref(a,this._path);else{const e=this.nextSibling;a=document.createElement("a"),this._setAnchorHref(a,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||zt.includes(t.name))&&a.setAttribute(t.name,t.value);for(const t of this._childNodeArray)a.appendChild(t);e?t.insertBefore(a,e):t.appendChild(a)}if(this._anchorElement=a,St())return this._updateActiveState(),void a.setAttribute(c,"");wt()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),""!==this._path&&!this._isInternalTarget(this._path)||wt()?.navigate||(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},a.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){wt()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,a){if("match"!==t||e===a){if("to"===t&&e!==a)this._path=a||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(zt.includes(t)){const e=this._anchorElement;e&&(null===a?e.removeAttribute(t):e.setAttribute(t,a))}}else this._anchorElement&&this._updateActiveState()}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=new URL(window.location.href),e=this._normalizePathname(t.pathname),{pathname:a,search:n}=Nt(this._path),s=function(t,e){const a=new URLSearchParams(e),n=new URLSearchParams(t);for(const t of new Set(a.keys())){const e=a.getAll(t).sort(),s=n.getAll(t).sort();if(e.length!==s.length||e.some((t,e)=>t!==s[e]))return!1}return!0}(t.search,vt(n)),r=this._normalizePathname(this._isInternalTarget(this._path)?""===a?window.location.pathname:this._joinInternalPath(this.router.basename,a):a),i=""!==this._path&&s&&e===r,o=!i&&""!==this._path&&s&&"prefix"===this.getAttribute("match")&&e.startsWith(r+"/");this._anchorElement&&(i||o?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current",i?"page":"true")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const Mt=[],Ot=new Map;let Ut=!1;const Ft=new WeakMap,Wt=new WeakMap;class Dt extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super()}_initialize(){if(!this._initialized&&(this._initialized=!0,this._childElementArray=Array.from(this.children),!St())){this.style.display="none";for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Ut||(this._captureInitialHead(),Ut=!0),Mt.push(this),this._reapplyHead()}disconnectedCallback(){const t=Mt.indexOf(this);-1!==t&&Mt.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||a("Head component is not initialized yet."),this._childElementArray}_cloneOf(t){if(!mt(t))return t.cloneNode(!0);let e=Wt.get(t);return void 0===e&&(e=t.cloneNode(!0),Wt.set(t,e)),e}_getKey(t){const e=Ft.get(t);if(void 0!==e)return e;const a=this._computeKey(t);return Ft.set(t,a),a}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e){return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`}if("link"===e){return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`}if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",a=t.getAttribute("id")||"",n=t.getAttribute("type")||"";return e||a?`script:${e}:${a}:${n}`:`script::${n}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",a=t.getAttribute("media")||"";return e?`style:${e}:${a}`:`style::${a}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const a=this._getKey(e);t.has(a)||t.set(a,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Ot.has(t)||Ot.set(t,e.cloneNode(!0))}}_reapplyHead(){const e=new Set;for(const t of Mt)for(const a of t._childElementArray)e.add(this._getKey(a));for(const t of Ot.keys())e.add(t);const a=this._buildHeadElementMap();for(const t of a.keys())e.add(t);for(const n of e){let e=null;for(let t=Mt.length-1;t>=0;t--){const a=Mt[t];for(const t of a._childElementArray)if(this._getKey(t)===n){e=this._cloneOf(t);break}if(e)break}if(!e&&Ot.has(n)){e=Ot.get(n).cloneNode(!0)}const s=a.get(n)??null;null!==e&&s===e||(e&&s?.isEqualNode(e)&&!mt(e)||(e?(s?s.replaceWith(e):document.head.appendChild(e),a.set(n,e),R(e)||ft(e,`<${e.tagName.toLowerCase()}> inside <${t.tagNames.head}>`,`<${t.tagNames.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(s?.remove(),a.delete(n))))}}}function jt(e=customElements){e.get(t.tagNames.layout)||e.define(t.tagNames.layout,v),e.get(t.tagNames.layoutOutlet)||e.define(t.tagNames.layoutOutlet,F),e.get(t.tagNames.outlet)||e.define(t.tagNames.outlet,C),e.get(t.tagNames.route)||e.define(t.tagNames.route,f),e.get(t.tagNames.router)||e.define(t.tagNames.router,Ht),e.get(t.tagNames.link)||e.define(t.tagNames.link,It),e.get(t.tagNames.head)||e.define(t.tagNames.head,Dt)}var Gt;await void jt(Gt);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|