@wcstack/router 4.8.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/dist/index.d.ts CHANGED
@@ -323,6 +323,7 @@ declare class Router extends HTMLElement implements IRouter {
323
323
  private _fallbackRoute;
324
324
  private _listeningPopState;
325
325
  private _listeningNavigate;
326
+ private _listeningClick;
326
327
  private _navigateUrl;
327
328
  private _replaceUrl;
328
329
  private _disconnectedDuringInit;
@@ -385,7 +386,7 @@ declare class Router extends HTMLElement implements IRouter {
385
386
  get basename(): string;
386
387
  set basename(value: string | null | undefined);
387
388
  get leaveConfirm(): string | null;
388
- set leaveConfirm(value: string | null | undefined);
389
+ set leaveConfirm(value: string | boolean | null | undefined);
389
390
  private _onBeforeUnload;
390
391
  /** beforeunload は leaveConfirm がある間だけ聞く(リスナーがあるだけで bfcache を外すブラウザがある) */
391
392
  private _syncBeforeUnload;
@@ -476,9 +477,27 @@ declare class Router extends HTMLElement implements IRouter {
476
477
  * basename が空の場合はすべての URL にマッチする。
477
478
  */
478
479
  private _isOwnPath;
480
+ /** 今のページ(URL)がこの router の basename の下か — ページの中の移動を受け持つのはこの router */
481
+ private _ownsCurrentPage;
482
+ /**
483
+ * 素のフラグメントへのリンク(`href="#main"`)の navigate イベント: ページの中の移動であり、どの router の
484
+ * ルートの遷移でもない(docs/seam-apps.md、city-library)。今のページを受け持つ router だけが動く:
485
+ * ブラウザが今のページのフラグメントへ移すもの(`<base>` が無い、今のページを指す)はそのまま通して
486
+ * フォーカスだけ移し、`<base>` が別のページへ解決したもの(`/#main`)は取り消して、今のページの
487
+ * そのフラグメントへ移し直す。
488
+ */
489
+ private _onFragmentLinkNavigate;
479
490
  private _onNavigateFunc;
480
491
  private _onNavigate;
481
492
  private _onPopState;
493
+ /**
494
+ * 素のフラグメントへのリンクを click で拾う — navigate イベントでリンクが分からないブラウザ(Navigation API
495
+ * が無い、NavigateEvent に sourceElement が無い)の経路。navigate イベントの経路と同じく、今のページの
496
+ * そのフラグメントへ移す(docs/seam-apps.md、city-library)。修飾キー・中ボタン・`download`・別の
497
+ * ウィンドウで開くリンク・ページが取り消したクリックはブラウザに任せる。window で聞くので、ページ自身の
498
+ * click リスナーはこれより先に走る。
499
+ */
500
+ private _onClick;
482
501
  private _initialize;
483
502
  /**
484
503
  * サーバー描画済み outlet の採用(docs/ssr-router-design.md §4)。
package/dist/index.esm.js CHANGED
@@ -216,6 +216,23 @@ function shallowEqualRecords(a, b) {
216
216
  }
217
217
  return true;
218
218
  }
219
+ /**
220
+ * `<wcs-link to>` のクエリが今のページのクエリに含まれるか(active / aria-current の判定 — docs/seam-apps.md、
221
+ * city-library)。`to` のクエリの各パラメータについて、今のクエリが同じ値(重複キーは同じ値の組、順序は
222
+ * 問わない)を持てば true。今のページにある余分なパラメータは構わない。`to` にクエリが無ければ常に true。
223
+ * 値は `URLSearchParams` でデコードして比べる(`+` と `%20` は同じ)。
224
+ */
225
+ function queryIncludes(current, required) {
226
+ const want = new URLSearchParams(required);
227
+ const have = new URLSearchParams(current);
228
+ for (const key of new Set(want.keys())) {
229
+ const a = want.getAll(key).sort();
230
+ const b = have.getAll(key).sort();
231
+ if (a.length !== b.length || a.some((value, i) => value !== b[i]))
232
+ return false;
233
+ }
234
+ return true;
235
+ }
219
236
 
220
237
  /**
221
238
  * guard 判定関数に渡す第 3 引数を組み立てる。
@@ -2752,7 +2769,104 @@ function inSsr() {
2752
2769
  return html ? html.hasAttribute('data-wcs-server') : false;
2753
2770
  }
2754
2771
 
2772
+ /**
2773
+ * 素のフラグメントへのリンク(`<a href="#main">` — スキップリンク)は、ページの中の移動
2774
+ * (docs/seam-apps.md、city-library)。
2775
+ *
2776
+ * SPA は `<base href="/">`(多言語なら `<base href="/ja/">`)を置くので、`#main` は
2777
+ * `/#main` へ解決される: `/search?q=a` で押すと、router がそれを受けてホームのルートへ
2778
+ * 移っていた。書いたままの `href` がフラグメントだけのリンクは、今のページのそのフラグメントへ
2779
+ * 移る — `<base>` の無いページでブラウザがするのと同じナビゲーションで。
2780
+ */
2781
+ /**
2782
+ * `a` / `area` の、書いたままの `href` がフラグメントだけ(`#…`、`#` 単独も)ならその値。
2783
+ * そうでなければ null(`/faq#x`・`?q=b#x` は別のページへのリンク)。
2784
+ */
2785
+ function fragmentHref(element) {
2786
+ if (!element || (element.localName !== "a" && element.localName !== "area"))
2787
+ return null;
2788
+ // URL の解析と同じく、前後の空白は除く
2789
+ const href = element.getAttribute("href")?.trim();
2790
+ return href !== undefined && href.startsWith("#") ? href : null;
2791
+ }
2792
+ /**
2793
+ * HTML の "find a potential indicated element": その id を持つ要素、無ければその name を持つ `<a>`。
2794
+ * 書いたままの値で探し、見つからなければパーセントデコードした値で探す("select the indicated part")。
2795
+ */
2796
+ function findIndicatedElement(fragment) {
2797
+ if (fragment === "")
2798
+ return null;
2799
+ const find = (value) => document.getElementById(value) ??
2800
+ Array.from(document.getElementsByName(value)).find((el) => el.localName === "a") ??
2801
+ null;
2802
+ const found = find(fragment);
2803
+ if (found !== null)
2804
+ return found;
2805
+ let decoded;
2806
+ try {
2807
+ decoded = decodeURIComponent(fragment);
2808
+ }
2809
+ catch {
2810
+ return null;
2811
+ }
2812
+ return decoded === fragment ? null : find(decoded);
2813
+ }
2814
+ /** URL がフラグメントを除いて今のページの URL と同じか(そこへのナビゲーションはフラグメントのナビゲーション) */
2815
+ function isCurrentPage(url) {
2816
+ const here = new URL(window.location.href);
2817
+ const there = new URL(url);
2818
+ here.hash = "";
2819
+ there.hash = "";
2820
+ return here.href === there.href;
2821
+ }
2822
+ /**
2823
+ * リンクがこのウィンドウで開くか(`target` も `<base target>` も無い、または `_self`)。
2824
+ * 別のウィンドウ・タブで開くリンクは、そこでのナビゲーション(ブラウザに任せる)。
2825
+ */
2826
+ function opensInThisWindow(link) {
2827
+ const target = link.getAttribute("target") ?? document.querySelector("base[target]")?.getAttribute("target") ?? "";
2828
+ return target === "" || target.toLowerCase() === "_self";
2829
+ }
2830
+ /**
2831
+ * NavigateEvent が sourceElement(ナビゲーションを起こしたリンク)を持つか。Chromium・Firefox・
2832
+ * Safari の今の版は持つ。持たない(古い Chromium の Navigation API)なら、リンクは click で拾う。
2833
+ */
2834
+ function navigateEventHasSource() {
2835
+ const ctor = globalThis.NavigateEvent;
2836
+ return typeof ctor === "function" && "sourceElement" in ctor.prototype;
2837
+ }
2838
+ /** 自分でフォーカスを受ける要素(tabindex を足すとタブ順から外れてしまうもの) */
2839
+ const FOCUSABLE = "a[href], area[href], button, input, select, textarea, iframe, summary, [contenteditable], audio[controls], video[controls], [tabindex]";
2840
+ /**
2841
+ * フラグメントが指す要素へフォーカスを移す。フォーカスできない要素(`<main>`・見出し・`<a name>`)には
2842
+ * `tabindex="-1"` を足す(`focus="heading"` と同じ)。スクロールはフラグメントのナビゲーション
2843
+ * (ブラウザ)がする: ここでは動かさない — `scroll-margin` も `scroll-behavior: smooth` も効いたまま。
2844
+ */
2845
+ function focusFragmentTarget(fragment) {
2846
+ const target = findIndicatedElement(fragment);
2847
+ if (target === null)
2848
+ return;
2849
+ if (!target.matches(FOCUSABLE)) {
2850
+ target.setAttribute("tabindex", "-1");
2851
+ }
2852
+ target.focus({ preventScroll: true });
2853
+ }
2854
+ /**
2855
+ * ページの中の移動: URL を今のパスとクエリ+そのハッシュにする。`<base>` の無いページで
2856
+ * ブラウザがするのと同じフラグメントのナビゲーション(`location.assign`)— 履歴は push、
2857
+ * 今と同じ URL なら replace、スクロールは指す要素へ(`#` / `#top` は先頭へ)、`hashchange`
2858
+ * と `:target` もそのまま。ルートの遷移ではないので、どの router も受けない。
2859
+ */
2860
+ function navigateToFragment(href) {
2861
+ // 解決の基準は文書の URL(<base> ではない)
2862
+ const url = new URL(href, window.location.href);
2863
+ window.location.assign(url.href);
2864
+ focusFragmentTarget(url.hash.slice(1));
2865
+ }
2866
+
2755
2867
  const EMPTY_RECORD = Object.freeze({});
2868
+ /** `leaveConfirm = true` で聞く文言(ページの言語で聞くなら文字列を束ねる) */
2869
+ const DEFAULT_LEAVE_CONFIRM = "Leave this page? Changes you made may not be saved.";
2756
2870
  /**
2757
2871
  * AppRoutes - Root component for @wcstack/router
2758
2872
  *
@@ -2812,6 +2926,7 @@ class Router extends HTMLElement {
2812
2926
  _fallbackRoute = null;
2813
2927
  _listeningPopState = false;
2814
2928
  _listeningNavigate = false;
2929
+ _listeningClick = false;
2815
2930
  _navigateUrl = null;
2816
2931
  _replaceUrl = null;
2817
2932
  _disconnectedDuringInit = false;
@@ -2952,11 +3067,13 @@ class Router extends HTMLElement {
2952
3067
  // オリジンへのリンク、フォームの送信)の前に confirm(値) を出し、断られたら出ない。ページを閉じる・
2953
3068
  // 読み直すとき(と Navigation API の無いブラウザでページを離れるとき)はブラウザ自身の確認(beforeunload)。未保存の変更を守る口(docs/seam-apps.md、
2954
3069
  // router-admin — Navigation API を直接使うしかなかった)。null は属性を外し、undefined は最初の属性へ戻す。
3070
+ // 真偽値(`leaveConfirm: dirty`)は、true なら既定の文言で聞き、false なら聞かない — 文字列にすると
3071
+ // confirm("false") が遷移のたびに出ていた(docs/seam-apps.md、family-ledger)。
2955
3072
  get leaveConfirm() {
2956
3073
  return this.getAttribute("leave-confirm") || null;
2957
3074
  }
2958
3075
  set leaveConfirm(value) {
2959
- reflectAttribute(this, "leave-confirm", value);
3076
+ reflectAttribute(this, "leave-confirm", value === true ? DEFAULT_LEAVE_CONFIRM : value === false ? null : value);
2960
3077
  this._syncBeforeUnload();
2961
3078
  }
2962
3079
  _onBeforeUnload = (e) => {
@@ -3324,12 +3441,33 @@ class Router extends HTMLElement {
3324
3441
  return true;
3325
3442
  return fullPath === this._basename || fullPath.startsWith(this._basename + "/");
3326
3443
  }
3444
+ /** 今のページ(URL)がこの router の basename の下か — ページの中の移動を受け持つのはこの router */
3445
+ _ownsCurrentPage() {
3446
+ return this._isOwnPath(this._normalizePathname(window.location.pathname));
3447
+ }
3448
+ /**
3449
+ * 素のフラグメントへのリンク(`href="#main"`)の navigate イベント: ページの中の移動であり、どの router の
3450
+ * ルートの遷移でもない(docs/seam-apps.md、city-library)。今のページを受け持つ router だけが動く:
3451
+ * ブラウザが今のページのフラグメントへ移すもの(`<base>` が無い、今のページを指す)はそのまま通して
3452
+ * フォーカスだけ移し、`<base>` が別のページへ解決したもの(`/#main`)は取り消して、今のページの
3453
+ * そのフラグメントへ移し直す。
3454
+ */
3455
+ _onFragmentLinkNavigate(navEvent, href) {
3456
+ if (!this._ownsCurrentPage())
3457
+ return;
3458
+ const destination = navEvent.destination.url;
3459
+ if (isCurrentPage(destination)) {
3460
+ focusFragmentTarget(new URL(destination).hash.slice(1));
3461
+ return;
3462
+ }
3463
+ navEvent.preventDefault?.();
3464
+ navigateToFragment(href);
3465
+ }
3327
3466
  _onNavigateFunc(navEvent) {
3328
3467
  if (
3329
3468
  // ページ側が取り消したナビゲーション(未保存の確認など)に intercept() を呼ぶと
3330
3469
  // InvalidStateError が投げられる(docs/seam-apps.md、router-admin)
3331
3470
  navEvent.defaultPrevented ||
3332
- navEvent.hashChange ||
3333
3471
  navEvent.downloadRequest !== null ||
3334
3472
  // 読み直し(location.reload() / history.go(0) / navigation.reload())は文書を読み直す。受けると同じ
3335
3473
  // 文書でルートを描き直すだけになり、更新を促す「再読み込み」も Service Worker の更新も効かなかった
@@ -3337,6 +3475,18 @@ class Router extends HTMLElement {
3337
3475
  navEvent.navigationType === "reload") {
3338
3476
  return;
3339
3477
  }
3478
+ // 書いたままの href がフラグメントだけのリンク(スキップリンク)。sourceElement はこの文書のリンクだけ見る
3479
+ const source = navEvent.sourceElement;
3480
+ const fragment = source?.ownerDocument === document ? fragmentHref(source) : null;
3481
+ if (fragment !== null) {
3482
+ this._onFragmentLinkNavigate(navEvent, fragment);
3483
+ return;
3484
+ }
3485
+ // フラグメントのナビゲーションはブラウザのもの: フラグメントだけ変わる(戻る / 進むも)、今の URL のフラグメントへ
3486
+ // もう一度(同じ URL へは hashChange が false で来る — 受けると、2 度目のスキップリンクがスクロールしなかった)
3487
+ if (navEvent.hashChange || (navEvent.destination.url.includes("#") && isCurrentPage(navEvent.destination.url))) {
3488
+ return;
3489
+ }
3340
3490
  const url = new URL(navEvent.destination.url);
3341
3491
  const fullPath = this._normalizePathname(url.pathname);
3342
3492
  // basename 配下でない URL は受けない(マルチ Router 対応)。どの router も受けないもの(別の
@@ -3399,6 +3549,24 @@ class Router extends HTMLElement {
3399
3549
  await applyRoute(this, this.outlet, fullPath, this._path, window.location.search || "");
3400
3550
  this._notifyLocationChange();
3401
3551
  };
3552
+ /**
3553
+ * 素のフラグメントへのリンクを click で拾う — navigate イベントでリンクが分からないブラウザ(Navigation API
3554
+ * が無い、NavigateEvent に sourceElement が無い)の経路。navigate イベントの経路と同じく、今のページの
3555
+ * そのフラグメントへ移す(docs/seam-apps.md、city-library)。修飾キー・中ボタン・`download`・別の
3556
+ * ウィンドウで開くリンク・ページが取り消したクリックはブラウザに任せる。window で聞くので、ページ自身の
3557
+ * click リスナーはこれより先に走る。
3558
+ */
3559
+ _onClick = (e) => {
3560
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
3561
+ return;
3562
+ // クリックを受けるリンク: 合成パスの最初の a / area(href のあるもの)。open な shadow root の中も
3563
+ const link = e.composedPath().find((node) => node instanceof Element && (node.localName === "a" || node.localName === "area") && node.hasAttribute("href"));
3564
+ const fragment = fragmentHref(link);
3565
+ if (fragment === null || link.hasAttribute("download") || !opensInThisWindow(link) || !this._ownsCurrentPage())
3566
+ return;
3567
+ e.preventDefault();
3568
+ navigateToFragment(fragment);
3569
+ };
3402
3570
  async _initialize() {
3403
3571
  this._initializing = true;
3404
3572
  try {
@@ -3843,6 +4011,11 @@ class Router extends HTMLElement {
3843
4011
  window.addEventListener("popstate", this._onPopState);
3844
4012
  this._listeningPopState = true;
3845
4013
  }
4014
+ // 素のフラグメントへのリンク: navigate イベントで見分けられなければ click で拾う
4015
+ if ((!navigation || !navigateEventHasSource()) && !this._listeningClick) {
4016
+ window.addEventListener("click", this._onClick);
4017
+ this._listeningClick = true;
4018
+ }
3846
4019
  this._resolveConnectedCallback?.();
3847
4020
  }
3848
4021
  disconnectedCallback() {
@@ -3858,6 +4031,10 @@ class Router extends HTMLElement {
3858
4031
  window.removeEventListener("popstate", this._onPopState);
3859
4032
  this._listeningPopState = false;
3860
4033
  }
4034
+ if (this._listeningClick) {
4035
+ window.removeEventListener("click", this._onClick);
4036
+ this._listeningClick = false;
4037
+ }
3861
4038
  this._syncBeforeUnload();
3862
4039
  // live region は router の寿命に同期して撤去する(body 直下に置かない理由と同根)
3863
4040
  if (this._a11yRegion !== null) {
@@ -3871,7 +4048,8 @@ class Router extends HTMLElement {
3871
4048
  // 読み上げ言語・方向に直結するため含める(多言語ナビで anchor 側に届かないと
3872
4049
  // 読み上げが崩れる)。`aria-*` は開集合なので observedAttributes には載せられず、
3873
4050
  // anchor 生成時の一括コピーのみ(接続後の動的 aria-* 変更 — data-wcs バインド経由を
3874
- // 含む — には追従しない。README の明記された制限)。
4051
+ // 含む — には追従しない。`for:` の行・`if:` の枝の中のリンクは接続前に束ねられるので、
4052
+ // その時の値はコピーされる。README の明記された制限)。
3875
4053
  const MIRRORED_ATTRIBUTES = ['title', 'rel', 'target', 'download', 'hreflang', 'lang', 'dir'];
3876
4054
  class Link extends HTMLElement {
3877
4055
  static get observedAttributes() {
@@ -4111,7 +4289,10 @@ class Link extends HTMLElement {
4111
4289
  }
4112
4290
  attributeChangedCallback(name, oldValue, newValue) {
4113
4291
  if (name === 'match' && oldValue !== newValue) {
4114
- this._updateActiveState();
4292
+ // anchor 生成前(upgrade の属性の通知 — まだ router の下に居ないことがある)は接続時の判定に任せる
4293
+ if (this._anchorElement) {
4294
+ this._updateActiveState();
4295
+ }
4115
4296
  return;
4116
4297
  }
4117
4298
  if (name === 'to' && oldValue !== newValue) {
@@ -4140,9 +4321,13 @@ class Link extends HTMLElement {
4140
4321
  if (this._path.startsWith('?') && this._anchorElement) {
4141
4322
  this._setAnchorHref(this._anchorElement, this._path);
4142
4323
  }
4143
- // active 判定は pathname のみの比較(クエリ非感応 — §1.1 欠陥 7 の修理)。
4144
- const currentPath = this._normalizePathname(new URL(window.location.href).pathname);
4145
- const { pathname } = splitUrlTarget(this._path);
4324
+ // active 判定は pathname の比較(§1.1 欠陥 7 の修理)に、`to` のクエリが今のページのクエリに含まれること
4325
+ // を足す(`to` にクエリが無ければ pathname だけ)。`/search?q=a` の「次のページ」(`?q=a&page=2`)が
4326
+ // 「現在のページ」と読み上げられていた(docs/seam-apps.md、city-library)
4327
+ const current = new URL(window.location.href);
4328
+ const currentPath = this._normalizePathname(current.pathname);
4329
+ const { pathname, search } = splitUrlTarget(this._path);
4330
+ const queryMatches = queryIncludes(current.search, effectiveSearch(search));
4146
4331
  const linkPath = this._normalizePathname(this._isInternalTarget(this._path)
4147
4332
  ? (pathname === ""
4148
4333
  ? window.location.pathname
@@ -4151,8 +4336,8 @@ class Link extends HTMLElement {
4151
4336
  // match="prefix": 下のパスでも active(サイドナビの「商品」が /products/3 でも印を付ける —
4152
4337
  // docs/seam-apps.md、router-admin)。そのページそのものではないので aria-current は "true"
4153
4338
  // 行き先の無いリンク(`to` が空)はどこでも active ではない(空のパスは "/" に正規化される)
4154
- const exact = this._path !== '' && currentPath === linkPath;
4155
- const within = !exact && this._path !== '' && this.getAttribute('match') === 'prefix' && currentPath.startsWith(linkPath + '/');
4339
+ const exact = this._path !== '' && queryMatches && currentPath === linkPath;
4340
+ const within = !exact && this._path !== '' && queryMatches && this.getAttribute('match') === 'prefix' && currentPath.startsWith(linkPath + '/');
4156
4341
  if (this._anchorElement) {
4157
4342
  if (exact || within) {
4158
4343
  this._anchorElement.classList.add('active');
@@ -4488,7 +4673,7 @@ function bootstrapRouter(config, registry) {
4488
4673
  registerComponents(registry);
4489
4674
  }
4490
4675
 
4491
- var version = "4.8.0";
4676
+ var version = "4.10.0";
4492
4677
  var pkg = {
4493
4678
  version: version};
4494
4679