@wcstack/router 4.0.4 → 4.1.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
@@ -194,7 +194,10 @@ interface IRoute extends IRouteChildContainer {
194
194
  readonly absoluteSegmentCount: number;
195
195
  readonly segmentInfos: ISegmentInfo[];
196
196
  readonly absoluteSegmentInfos: ISegmentInfo[];
197
- /** guard 属性の有無。SSR の guard バリア判定に使う(docs/ssr-router-design.md §2-4) */
197
+ /**
198
+ * guard を持つか(`guard` 属性、または `<wcs-guard-handler>`)。SSR の guard バリア判定に使う
199
+ * (docs/ssr-router-design.md §2-4)
200
+ */
198
201
  readonly hasGuard: boolean;
199
202
  guardHandler: GuardHandler;
200
203
  shouldChange(newParams: Record<string, string>): boolean;
@@ -205,6 +208,11 @@ interface IRoute extends IRouteChildContainer {
205
208
  setParams(params: Record<string, string>, typedParams: Record<string, any>): void;
206
209
  clearParams(): void;
207
210
  notifyGuardHandlerLoadFailed(): void;
211
+ /**
212
+ * `<wcs-guard-handler>` を持つルートの guard を有効にする(`guard` 属性が無くても)。ハンドラの
213
+ * 読み込みより前に呼ぶ — 最初のナビゲーションの guard 相がハンドラを待てるように(parse)
214
+ */
215
+ enableGuard(): void;
208
216
  /**
209
217
  * SSR ハイドレーションの採用: サーバー描画済みノード列を内容として引き取る
210
218
  * (docs/ssr-router-design.md §4)
@@ -247,6 +255,11 @@ interface IRouter extends IRouteChildContainer {
247
255
  navigate(path: string): Promise<void>;
248
256
  /** navigateUrl(push)の対になる replace 遷移(§4.2) */
249
257
  replace(path: string): Promise<void>;
258
+ /**
259
+ * 初期化(最初のルート適用と navigate リスナの登録)が終わると決着する。guard のリダイレクトは
260
+ * これを待つ — 初期化中の遷移はリスナに捕まらず、文書ごとの読み込みになるため
261
+ */
262
+ readonly connectedCallbackPromise: Promise<void>;
250
263
  /**
251
264
  * same-match 判定(§4.4)。比較は basename スライス後の path 同士。
252
265
  * 最初の成功 commit より前は常に false(初回ガード)。
@@ -254,9 +267,13 @@ interface IRouter extends IRouteChildContainer {
254
267
  isSameMatch(path: string): boolean;
255
268
  /**
256
269
  * 観測面のコミットと発火(§3.4)。全内部値を先にコミットし、その後で
257
- * params → route-name → search → path の順に変化したものだけ発火する。
270
+ * data → params → route-name → search → path の順に変化したものだけ発火する。
271
+ * `holdPath` なら path だけ発火を保留し、`releasePath()` で発火する — ルートの中身を
272
+ * 描く前に出力を渡し、描いた後で「遷移完了」を知らせるため(applyRoute)。
258
273
  */
259
- commitNavigation(commit: IRouterCommit): void;
274
+ commitNavigation(commit: IRouterCommit, holdPath?: boolean): void;
275
+ /** `commitNavigation(…, true)` で保留した path-changed を発火する(保留が無ければ何もしない) */
276
+ releasePath(): void;
260
277
  /** `announce=` 用 live region。未生成なら null(docs/a11y-design.md §3-4) */
261
278
  readonly a11yRegion: HTMLElement | null;
262
279
  /**
@@ -318,6 +335,13 @@ declare class Router extends HTMLElement implements IRouter {
318
335
  private _data;
319
336
  /** 最初の成功 commit を通過したか(§4.4 の初回ガード) */
320
337
  private _hasCommitted;
338
+ /** commitNavigation(…, true) が path-changed の発火を保留している(releasePath で発火) */
339
+ private _pathHeld;
340
+ /** 自分の navigate() / replace() が離脱の確認を済ませて navigation.navigate() を呼んでいる間 */
341
+ private _leaveChecked;
342
+ /** 離脱が確認された: 次の commit まで(その遷移の guard のリダイレクトで聞き直さない) */
343
+ private _leaveConfirmed;
344
+ private _listeningUnload;
321
345
  private _connectedCallbackPromise;
322
346
  private _resolveConnectedCallback;
323
347
  private _rejectConnectedCallback;
@@ -358,6 +382,16 @@ declare class Router extends HTMLElement implements IRouter {
358
382
  private _getBasename;
359
383
  get basename(): string;
360
384
  set basename(value: string | null | undefined);
385
+ get leaveConfirm(): string | null;
386
+ set leaveConfirm(value: string | null | undefined);
387
+ private _onBeforeUnload;
388
+ /** beforeunload は leaveConfirm がある間だけ聞く(リスナーがあるだけで bfcache を外すブラウザがある) */
389
+ private _syncBeforeUnload;
390
+ /**
391
+ * 別のルートへ出る前の確認。断られたら false。leaveConfirm が無い・最初の表示の前・同じルート
392
+ * (クエリだけの遷移)・確認済みの遷移の続き(guard のリダイレクト)では聞かない。
393
+ */
394
+ private _confirmLeave;
361
395
  private _getOutlet;
362
396
  private _getTemplate;
363
397
  get outlet(): IOutlet;
@@ -394,8 +428,16 @@ declare class Router extends HTMLElement implements IRouter {
394
428
  * 先頭に置くのは、params のリスナーがロード済みデータを読めるようにするため。
395
429
  * `path` を最後に置くのは、既存例で `path` が「ナビゲーション完了」の信号として
396
430
  * 使われているため。各イベントは変化した commit のみ発火する。
397
- */
398
- commitNavigation(commit: IRouterCommit): void;
431
+ *
432
+ * `holdPath` は path-changed だけを `releasePath()` まで保留する。applyRoute はルートの中身を
433
+ * 描く前にこれで commit する — 中身のバインディング(state)が、その遷移の params / data を
434
+ * 最初から読めるように。保留しないと、中身は前のルートの値で一度評価され、getter や
435
+ * フィルタが例外を出しうる(docs/seam-apps.md、router-auth)。path は中身を描いた後に発火し、
436
+ * 「ナビゲーション完了」の意味を保つ。
437
+ */
438
+ commitNavigation(commit: IRouterCommit, holdPath?: boolean): void;
439
+ releasePath(): void;
440
+ private _firePathChanged;
399
441
  get fallbackRoute(): IRoute | null;
400
442
  /**
401
443
  * Routeのfallback属性がある場合にそのルートを設定します。
@@ -514,6 +556,7 @@ declare class Route extends HTMLElement implements IRoute {
514
556
  shouldChange(newParams: Record<string, string>): boolean;
515
557
  guardCheck(matchResult: IRouteMatchResult): Promise<GuardData | null>;
516
558
  notifyGuardHandlerLoadFailed(): void;
559
+ enableGuard(): void;
517
560
  /**
518
561
  * Shell(Route)の routeParentNode を辿って祖先関係を判定する。
519
562
  *
@@ -590,6 +633,11 @@ declare class RouteCore extends EventTarget {
590
633
  get segmentCount(): number;
591
634
  get absoluteSegmentCount(): number;
592
635
  parsePath(path: string, options?: RouteParseOptions): void;
636
+ /**
637
+ * guard を有効にする: guard 相がハンドラの設定を待つようにする。`guard` 属性(parsePath)と
638
+ * `<wcs-guard-handler>`(parse)のどちらからも呼ばれる。リダイレクト先の既定は '/'。
639
+ */
640
+ enableGuard(): void;
593
641
  setParams(params: Record<string, string>, typedParams: Record<string, any>): void;
594
642
  clearParams(): void;
595
643
  shouldChange(newParams: Record<string, string>): boolean;
package/dist/index.esm.js CHANGED
@@ -485,14 +485,25 @@ class RouteCore extends EventTarget {
485
485
  });
486
486
  }
487
487
  }
488
- this._hasGuard = options.hasGuard || false;
489
- if (this._hasGuard) {
488
+ this._hasGuard = false;
489
+ if (options.hasGuard) {
490
490
  this._guardFallbackPath = options.guardFallback || '/';
491
- this._waitForSetGuardHandler = new Promise((resolve) => {
492
- this._resolveSetGuardHandler = resolve;
493
- });
491
+ this.enableGuard();
494
492
  }
495
493
  }
494
+ /**
495
+ * guard を有効にする: guard 相がハンドラの設定を待つようにする。`guard` 属性(parsePath)と
496
+ * `<wcs-guard-handler>`(parse)のどちらからも呼ばれる。リダイレクト先の既定は '/'。
497
+ */
498
+ enableGuard() {
499
+ if (this._hasGuard)
500
+ return;
501
+ this._hasGuard = true;
502
+ this._guardFallbackPath ||= '/';
503
+ this._waitForSetGuardHandler = new Promise((resolve) => {
504
+ this._resolveSetGuardHandler = resolve;
505
+ });
506
+ }
496
507
  setParams(params, typedParams) {
497
508
  const wasActive = this._active;
498
509
  this._params = params;
@@ -756,6 +767,9 @@ class Route extends HTMLElement {
756
767
  notifyGuardHandlerLoadFailed() {
757
768
  this._core.notifyGuardHandlerLoadFailed();
758
769
  }
770
+ enableGuard() {
771
+ this._core.enableGuard();
772
+ }
759
773
  /**
760
774
  * Shell(Route)の routeParentNode を辿って祖先関係を判定する。
761
775
  *
@@ -1555,6 +1569,8 @@ function loadGuardHandler(script, route) {
1555
1569
  route.guardHandler = handler;
1556
1570
  }
1557
1571
  else {
1572
+ // default export が関数でない: 黙ってリダイレクトに倒すと理由が分からないので知らせる
1573
+ console.error(`${config.tagNames.guardHandler}: the <script type="module"> has no default-exported function, so the route's guard redirects every navigation.`);
1558
1574
  // ハンドラが取得できなかった場合は guardCheck の待ちを解除する
1559
1575
  route.notifyGuardHandlerLoadFailed();
1560
1576
  }
@@ -1618,6 +1634,10 @@ async function _parseNode(routerNode, node, routes, routesByPath) {
1618
1634
  const route = routes[routes.length - 1];
1619
1635
  const script = element.querySelector('script[type="module"]');
1620
1636
  if (script) {
1637
+ // ハンドラがあれば guard を有効にする(`guard` 属性が無くても)。読み込みより前に —
1638
+ // 最初のナビゲーションの guard 相がハンドラを待てるように。属性が無いと待たずに通し、
1639
+ // 最初の表示だけ守られなかった(docs/seam-apps.md、router-auth)
1640
+ route.enableGuard();
1621
1641
  loadGuardHandler(script, route);
1622
1642
  }
1623
1643
  }
@@ -2243,6 +2263,10 @@ function whenLoadOrderSettled(check) {
2243
2263
  check();
2244
2264
  }
2245
2265
 
2266
+ /** 続けて起きた guard のリダイレクトの数(guard 相を通った遷移で数え直す) */
2267
+ const redirectCounts = new WeakMap();
2268
+ /** これを超えて続くリダイレクトはループとして止める(docs/seam-apps.md、router-auth) */
2269
+ const MAX_GUARD_REDIRECTS = 10;
2246
2270
  /**
2247
2271
  * 差し込んだルート内容を binder へ渡す。binder が居なければ、バインドが効かない
2248
2272
  * ことを 1 回だけ報告する。
@@ -2275,7 +2299,13 @@ function bindRouteContent(route) {
2275
2299
  }
2276
2300
  /**
2277
2301
  * ガード相の単独実装。何も触らずに全ルートの guardCheck を待ち、GuardCancel なら
2278
- * フォールバックへの再ナビゲートを microtask で予約して false を返す。
2302
+ * フォールバックへの再ナビゲートを予約して false を返す。
2303
+ *
2304
+ * リダイレクトは設計どおりの使い方なので、コンソールには何も出さない。履歴は**置き換える** —
2305
+ * 守られた URL は表示されていないので「戻る」の行き先にしない(push だと、戻るたびに同じ
2306
+ * リダイレクトへ戻される)。初期化(connectedCallbackPromise)の後で行う — 初期化中の遷移は
2307
+ * navigate リスナに捕まらず、文書ごと読み直される。guard 同士が送り合うループは
2308
+ * MAX_GUARD_REDIRECTS 回で止めてエラーにする。
2279
2309
  *
2280
2310
  * showRouteContent の相 1 であると同時に、SSR ハイドレーション
2281
2311
  * (docs/ssr-router-design.md §4 — 採用はレンダリング最適化であって認可の
@@ -2294,14 +2324,23 @@ async function runGuardPhase(routerNode, matchResult) {
2294
2324
  }
2295
2325
  }
2296
2326
  matchResult.data = data;
2327
+ redirectCounts.delete(routerNode);
2297
2328
  }
2298
2329
  catch (e) {
2299
2330
  if (e instanceof GuardCancel) {
2300
- console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`);
2301
- queueMicrotask(() => {
2302
- routerNode.navigate(e.fallbackPath).catch((err) => {
2303
- console.error('Fallback navigation failed:', err);
2304
- });
2331
+ const count = (redirectCounts.get(routerNode) ?? 0) + 1;
2332
+ if (count > MAX_GUARD_REDIRECTS) {
2333
+ redirectCounts.delete(routerNode);
2334
+ console.error(`${config.tagNames.router}: guard redirect loop — stopped after ${MAX_GUARD_REDIRECTS} redirects in a row ` +
2335
+ `(the last: ${matchResult.path} → ${e.fallbackPath}). The guards of these routes send each other back and forth.`);
2336
+ return false;
2337
+ }
2338
+ redirectCounts.set(routerNode, count);
2339
+ routerNode.connectedCallbackPromise
2340
+ .catch(() => { })
2341
+ .then(() => routerNode.replace(e.fallbackPath))
2342
+ .catch((err) => {
2343
+ console.error('Fallback navigation failed:', err);
2305
2344
  });
2306
2345
  return false;
2307
2346
  }
@@ -2325,16 +2364,20 @@ async function runGuardPhase(routerNode, matchResult) {
2325
2364
  * 相を分けたことで「ガードが拒否したのに旧ルートだけ先に消えている」という
2326
2365
  * 順序の歪みも同時に解消している。
2327
2366
  *
2367
+ * `beforeChange` はガード相を通った後、変更相の前に呼ぶ(applyRoute はここで commit する)。
2368
+ *
2328
2369
  * @returns ガードチェックを通過してコンテンツ表示が成立した場合 true、
2329
2370
  * GuardCancel により中断(フォールバックへ再ナビゲート)した場合 false。
2330
2371
  * 呼び出し側(applyRoute)は false の場合、router.path / outlet.lastRoutes を
2331
2372
  * 更新しないことで「拒否されたパスでの path-changed 発火」を防ぐ。
2332
2373
  */
2333
- async function showRouteContent(routerNode, matchResult, lastRoutes) {
2374
+ async function showRouteContent(routerNode, matchResult, lastRoutes, beforeChange) {
2334
2375
  // --- ガード相 ---
2335
2376
  if (!(await runGuardPhase(routerNode, matchResult))) {
2336
2377
  return false;
2337
2378
  }
2379
+ // 中身を描く前(applyRoute の commit — 中身のバインディングがこの遷移の出力を読めるように)
2380
+ beforeChange?.();
2338
2381
  // --- 変更相 ---
2339
2382
  const routesSet = new Set(matchResult.routes);
2340
2383
  const lastRouteSet = new Set(lastRoutes);
@@ -2444,22 +2487,24 @@ async function applyRoute(routerNode, outlet, fullPath, lastPath, search = "") {
2444
2487
  // guard 相の第 3 引数(IGuardContext.searchParams)が commit と同じクエリを読めるように供給する
2445
2488
  matchResult.search = search;
2446
2489
  const lastRoutes = outlet.lastRoutes;
2447
- const committed = await showRouteContent(routerNode, matchResult, lastRoutes);
2448
- // GuardCancel により中断された場合は state を更新しない
2449
- // (拒否されたパスでの wcs-router:path-changed 発火を防ぐため)
2490
+ // guard 相を通ったら、中身を描く前に commit する(path-changed だけ描いた後)。中身の
2491
+ // バインディングが最初からこの遷移の params / data を読めるように(Router.commitNavigation)。
2492
+ // GuardCancel で中断された場合は commit しない(拒否されたパスでの発火を防ぐため)
2493
+ const committed = await showRouteContent(routerNode, matchResult, lastRoutes, () => {
2494
+ // routeName は最深マッチの name。fallback 時は fallback ルートの name(D8)。
2495
+ routerNode.commitNavigation({
2496
+ params: matchResult.params,
2497
+ typedParams: matchResult.typedParams,
2498
+ routeName: matchResult.routes[matchResult.routes.length - 1]?.name ?? "",
2499
+ // guard 相(runGuardPhase)が集めたロード済みデータ。無ければ null に戻る
2500
+ data: matchResult.data ?? null,
2501
+ search,
2502
+ path,
2503
+ }, true);
2504
+ });
2450
2505
  if (!committed)
2451
2506
  return false;
2452
- // if successful, update router and outlet state
2453
- // routeName は最深マッチの name。fallback 時は fallback ルートの name(D8)。
2454
- routerNode.commitNavigation({
2455
- params: matchResult.params,
2456
- typedParams: matchResult.typedParams,
2457
- routeName: matchResult.routes[matchResult.routes.length - 1]?.name ?? "",
2458
- // guard 相(runGuardPhase)が集めたロード済みデータ。無ければ null に戻る
2459
- data: matchResult.data ?? null,
2460
- search,
2461
- path,
2462
- });
2507
+ routerNode.releasePath();
2463
2508
  outlet.lastRoutes = matchResult.routes;
2464
2509
  // オプトインの focus/announce は commit 直後・mutate() の外で適用する(D3)。
2465
2510
  // 初回描画(lastRoutes が空)では動かない — ページロードはブラウザの担当で、
@@ -2653,6 +2698,7 @@ class Router extends HTMLElement {
2653
2698
  { name: "basename", attribute: "basename" },
2654
2699
  { name: "navigateUrl" },
2655
2700
  { name: "replaceUrl" },
2701
+ { name: "leaveConfirm", attribute: "leave-confirm" },
2656
2702
  ],
2657
2703
  commands: [
2658
2704
  { name: "navigate", async: true },
@@ -2685,6 +2731,13 @@ class Router extends HTMLElement {
2685
2731
  _data = null;
2686
2732
  /** 最初の成功 commit を通過したか(§4.4 の初回ガード) */
2687
2733
  _hasCommitted = false;
2734
+ /** commitNavigation(…, true) が path-changed の発火を保留している(releasePath で発火) */
2735
+ _pathHeld = false;
2736
+ /** 自分の navigate() / replace() が離脱の確認を済ませて navigation.navigate() を呼んでいる間 */
2737
+ _leaveChecked = false;
2738
+ /** 離脱が確認された: 次の commit まで(その遷移の guard のリダイレクトで聞き直さない) */
2739
+ _leaveConfirmed = false;
2740
+ _listeningUnload = false;
2688
2741
  _connectedCallbackPromise;
2689
2742
  _resolveConnectedCallback = null;
2690
2743
  _rejectConnectedCallback = null;
@@ -2794,6 +2847,44 @@ class Router extends HTMLElement {
2794
2847
  set basename(value) {
2795
2848
  reflectAttribute(this, "basename", value);
2796
2849
  }
2850
+ // `leaveConfirm` は input(属性は leave-confirm)。空でない文字列の間、別のルートへ出るナビゲーション
2851
+ // (リンク・戻る / 進む・navigate())の前に confirm(値) を出し、断られたら出ない。ページを閉じる・
2852
+ // 読み直すときはブラウザ自身の確認(beforeunload)。未保存の変更を守る口(docs/seam-apps.md、
2853
+ // router-admin — Navigation API を直接使うしかなかった)。null は属性を外し、undefined は最初の属性へ戻す。
2854
+ get leaveConfirm() {
2855
+ return this.getAttribute("leave-confirm") || null;
2856
+ }
2857
+ set leaveConfirm(value) {
2858
+ reflectAttribute(this, "leave-confirm", value);
2859
+ this._syncBeforeUnload();
2860
+ }
2861
+ _onBeforeUnload = (e) => {
2862
+ if (this.leaveConfirm !== null)
2863
+ e.preventDefault();
2864
+ };
2865
+ /** beforeunload は leaveConfirm がある間だけ聞く(リスナーがあるだけで bfcache を外すブラウザがある) */
2866
+ _syncBeforeUnload() {
2867
+ const want = this.isConnected && this.leaveConfirm !== null && !inSsr();
2868
+ if (want === this._listeningUnload)
2869
+ return;
2870
+ this._listeningUnload = want;
2871
+ if (want)
2872
+ window.addEventListener("beforeunload", this._onBeforeUnload);
2873
+ else
2874
+ window.removeEventListener("beforeunload", this._onBeforeUnload);
2875
+ }
2876
+ /**
2877
+ * 別のルートへ出る前の確認。断られたら false。leaveConfirm が無い・最初の表示の前・同じルート
2878
+ * (クエリだけの遷移)・確認済みの遷移の続き(guard のリダイレクト)では聞かない。
2879
+ */
2880
+ _confirmLeave(fullPath) {
2881
+ const message = this.leaveConfirm;
2882
+ if (message === null || !this._hasCommitted || this._leaveConfirmed ||
2883
+ this.isSameMatch(sliceBasename(this._normalizePathname(fullPath), this._basename))) {
2884
+ return true;
2885
+ }
2886
+ return (this._leaveConfirmed = window.confirm(message));
2887
+ }
2797
2888
  _getOutlet() {
2798
2889
  // outlet は自身の直後の兄弟だけ(docs/router-outlet-placement.md)。マルチ Router で router と
2799
2890
  // outlet を 1 対 1 に結ぶための規則で、SSR の採用経路もこの位置を前提にする。
@@ -2888,8 +2979,14 @@ class Router extends HTMLElement {
2888
2979
  * 先頭に置くのは、params のリスナーがロード済みデータを読めるようにするため。
2889
2980
  * `path` を最後に置くのは、既存例で `path` が「ナビゲーション完了」の信号として
2890
2981
  * 使われているため。各イベントは変化した commit のみ発火する。
2982
+ *
2983
+ * `holdPath` は path-changed だけを `releasePath()` まで保留する。applyRoute はルートの中身を
2984
+ * 描く前にこれで commit する — 中身のバインディング(state)が、その遷移の params / data を
2985
+ * 最初から読めるように。保留しないと、中身は前のルートの値で一度評価され、getter や
2986
+ * フィルタが例外を出しうる(docs/seam-apps.md、router-auth)。path は中身を描いた後に発火し、
2987
+ * 「ナビゲーション完了」の意味を保つ。
2891
2988
  */
2892
- commitNavigation(commit) {
2989
+ commitNavigation(commit, holdPath = false) {
2893
2990
  const nextParams = Object.freeze({ ...commit.params });
2894
2991
  const nextTypedParams = Object.freeze({ ...commit.typedParams });
2895
2992
  const nextSearchParams = parseSearchParams(commit.search);
@@ -2919,6 +3016,7 @@ class Router extends HTMLElement {
2919
3016
  }
2920
3017
  this._path = commit.path;
2921
3018
  this._hasCommitted = true;
3019
+ this._leaveConfirmed = false;
2922
3020
  // --- その後で発火(順序規範: data → params → route-name → search → path) ---
2923
3021
  if (dataChanged) {
2924
3022
  this.dispatchEvent(new CustomEvent("wcs-router:data-changed", {
@@ -2944,13 +3042,23 @@ class Router extends HTMLElement {
2944
3042
  bubbles: true,
2945
3043
  }));
2946
3044
  }
2947
- if (pathChanged) {
2948
- this.dispatchEvent(new CustomEvent("wcs-router:path-changed", {
2949
- detail: commit.path,
2950
- bubbles: true,
2951
- }));
3045
+ this._pathHeld = pathChanged && holdPath;
3046
+ if (pathChanged && !holdPath) {
3047
+ this._firePathChanged();
2952
3048
  }
2953
3049
  }
3050
+ releasePath() {
3051
+ if (this._pathHeld) {
3052
+ this._pathHeld = false;
3053
+ this._firePathChanged();
3054
+ }
3055
+ }
3056
+ _firePathChanged() {
3057
+ this.dispatchEvent(new CustomEvent("wcs-router:path-changed", {
3058
+ detail: this._path,
3059
+ bubbles: true,
3060
+ }));
3061
+ }
2954
3062
  get fallbackRoute() {
2955
3063
  return this._fallbackRoute;
2956
3064
  }
@@ -3026,6 +3134,13 @@ class Router extends HTMLElement {
3026
3134
  ? window.location.pathname
3027
3135
  : this._joinInternalPath(this._basename, target.pathname);
3028
3136
  const url = fullPath + effectiveSearch(target.search) + target.hash;
3137
+ if (this.leaveConfirm !== null) {
3138
+ // 1 マイクロタスク待ってから確かめる: 保存のハンドラが leaveConfirm を外すバインディングと
3139
+ // navigateUrl を同じ drain で書いたとき、どちらが先に適用されても外れた後の値を見る
3140
+ await Promise.resolve();
3141
+ if (!this._confirmLeave(fullPath))
3142
+ return;
3143
+ }
3029
3144
  const navigation = getNavigation();
3030
3145
  if (navigation?.navigate) {
3031
3146
  // Navigation API は { committed, finished } を返す。
@@ -3033,9 +3148,17 @@ class Router extends HTMLElement {
3033
3148
  // 実際のナビゲーション完了まで pending となり、_navigateUrl / _replaceUrl の
3034
3149
  // 二重起動ガード (setter 内の同一値チェック) が適切な時間ウィンドウで機能する。
3035
3150
  // Polyfill や mock 環境で undefined / 戻り値なしのケースもあるため optional chaining。
3036
- const result = replace
3037
- ? navigation.navigate(url, { history: "replace" })
3038
- : navigation.navigate(url);
3151
+ // navigate イベントは navigate() の中で同期に来る: そこでの確認は済ませた
3152
+ this._leaveChecked = true;
3153
+ let result;
3154
+ try {
3155
+ result = replace
3156
+ ? navigation.navigate(url, { history: "replace" })
3157
+ : navigation.navigate(url);
3158
+ }
3159
+ finally {
3160
+ this._leaveChecked = false;
3161
+ }
3039
3162
  await result?.finished;
3040
3163
  }
3041
3164
  else {
@@ -3073,6 +3196,9 @@ class Router extends HTMLElement {
3073
3196
  }
3074
3197
  _onNavigateFunc(navEvent) {
3075
3198
  if (!navEvent.canIntercept ||
3199
+ // ページ側が取り消したナビゲーション(未保存の確認など)に intercept() を呼ぶと
3200
+ // InvalidStateError が投げられる(docs/seam-apps.md、router-admin)
3201
+ navEvent.defaultPrevented ||
3076
3202
  navEvent.hashChange ||
3077
3203
  navEvent.downloadRequest !== null) {
3078
3204
  return;
@@ -3082,6 +3208,12 @@ class Router extends HTMLElement {
3082
3208
  // basename 配下でない URL は無視(マルチ Router 対応)
3083
3209
  if (!this._isOwnPath(fullPath))
3084
3210
  return;
3211
+ // 別のルートへ出る前の確認(leaveConfirm)。取り消せないナビゲーション(一部の戻る / 進む)では
3212
+ // 聞けない。自分の navigate() / replace() からのものは確認済み
3213
+ if (!this._leaveChecked && navEvent.cancelable !== false && !this._confirmLeave(fullPath)) {
3214
+ navEvent.preventDefault?.();
3215
+ return;
3216
+ }
3085
3217
  // same-match 判定は applyRoute 内の分岐と同じ共有実装(§4.4: スライス後比較)。
3086
3218
  // intercept オプションは applyRoute 実行前に決める必要があるためここでも判定する。
3087
3219
  const sameMatch = this.isSameMatch(sliceBasename(fullPath, this._basename));
@@ -3495,6 +3627,8 @@ class Router extends HTMLElement {
3495
3627
  // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)。
3496
3628
  // await より前に同期で行い、初期化が古い値を読まないようにする。
3497
3629
  upgradeProperties(this);
3630
+ // マークアップに書いた leave-confirm も beforeunload で守る(初期化の成否によらず)
3631
+ this._syncBeforeUnload();
3498
3632
  // SSR モード(docs/ssr-router-design.md §3.2):
3499
3633
  // - enable-ssr 無し → サーバーでは一切初期化しない(クライアント専用 = 部分 CSR)
3500
3634
  // - enable-ssr あり → SSR 初期化のみ。navigate / popstate リスナは登録しない
@@ -3576,6 +3710,7 @@ class Router extends HTMLElement {
3576
3710
  window.removeEventListener("popstate", this._onPopState);
3577
3711
  this._listeningPopState = false;
3578
3712
  }
3713
+ this._syncBeforeUnload();
3579
3714
  // live region は router の寿命に同期して撤去する(body 直下に置かない理由と同根)
3580
3715
  if (this._a11yRegion !== null) {
3581
3716
  this._a11yRegion.remove();
@@ -3592,7 +3727,7 @@ class Router extends HTMLElement {
3592
3727
  const MIRRORED_ATTRIBUTES = ['title', 'rel', 'target', 'download', 'hreflang', 'lang', 'dir'];
3593
3728
  class Link extends HTMLElement {
3594
3729
  static get observedAttributes() {
3595
- return ['to', ...MIRRORED_ATTRIBUTES];
3730
+ return ['to', 'match', ...MIRRORED_ATTRIBUTES];
3596
3731
  }
3597
3732
  _childNodeArray = [];
3598
3733
  _uuid = getUUID();
@@ -3807,6 +3942,10 @@ class Link extends HTMLElement {
3807
3942
  this._router = null;
3808
3943
  }
3809
3944
  attributeChangedCallback(name, oldValue, newValue) {
3945
+ if (name === 'match' && oldValue !== newValue) {
3946
+ this._updateActiveState();
3947
+ return;
3948
+ }
3810
3949
  if (name === 'to' && oldValue !== newValue) {
3811
3950
  this._path = newValue || '';
3812
3951
  if (this._anchorElement) {
@@ -3841,12 +3980,16 @@ class Link extends HTMLElement {
3841
3980
  ? window.location.pathname
3842
3981
  : this._joinInternalPath(this.router.basename, pathname))
3843
3982
  : pathname);
3983
+ // match="prefix": 下のパスでも active(サイドナビの「商品」が /products/3 でも印を付ける —
3984
+ // docs/seam-apps.md、router-admin)。そのページそのものではないので aria-current は "true"
3985
+ const exact = currentPath === linkPath;
3986
+ const within = !exact && this.getAttribute('match') === 'prefix' && currentPath.startsWith(linkPath + '/');
3844
3987
  if (this._anchorElement) {
3845
- if (currentPath === linkPath) {
3988
+ if (exact || within) {
3846
3989
  this._anchorElement.classList.add('active');
3847
3990
  // 修理・既定オン(docs/a11y-design.md §3-3): active class と同じ事実の ARIA 表現。
3848
3991
  // 鮮度保証は active class と同一(同じ分岐・同じ呼び出し経路)。
3849
- this._anchorElement.setAttribute('aria-current', 'page');
3992
+ this._anchorElement.setAttribute('aria-current', exact ? 'page' : 'true');
3850
3993
  }
3851
3994
  else {
3852
3995
  this._anchorElement.classList.remove('active');
@@ -4137,7 +4280,7 @@ function bootstrapRouter(config, registry) {
4137
4280
  registerComponents(registry);
4138
4281
  }
4139
4282
 
4140
- var version = "4.0.4";
4283
+ var version = "4.1.0";
4141
4284
  var pkg = {
4142
4285
  version: version};
4143
4286