@wcstack/router 4.0.4 → 4.1.1

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,20 @@ function whenLoadOrderSettled(check) {
2243
2263
  check();
2244
2264
  }
2245
2265
 
2266
+ /**
2267
+ * A navigation another one took over — a guard's redirect, a newer navigation — rejects with an
2268
+ * `AbortError` (Navigation API). That is the designed outcome, not a failure: the write surfaces
2269
+ * (`navigateUrl` / `replaceUrl`) and the guard's fallback do not report it (docs/seam-apps.md,
2270
+ * router-auth — `navigateUrl` to a guarded page logged "navigate failed: AbortError").
2271
+ */
2272
+ function isAbortError(error) {
2273
+ return error?.name === "AbortError";
2274
+ }
2275
+
2276
+ /** 続けて起きた guard のリダイレクトの数(guard 相を通った遷移で数え直す) */
2277
+ const redirectCounts = new WeakMap();
2278
+ /** これを超えて続くリダイレクトはループとして止める(docs/seam-apps.md、router-auth) */
2279
+ const MAX_GUARD_REDIRECTS = 10;
2246
2280
  /**
2247
2281
  * 差し込んだルート内容を binder へ渡す。binder が居なければ、バインドが効かない
2248
2282
  * ことを 1 回だけ報告する。
@@ -2275,7 +2309,13 @@ function bindRouteContent(route) {
2275
2309
  }
2276
2310
  /**
2277
2311
  * ガード相の単独実装。何も触らずに全ルートの guardCheck を待ち、GuardCancel なら
2278
- * フォールバックへの再ナビゲートを microtask で予約して false を返す。
2312
+ * フォールバックへの再ナビゲートを予約して false を返す。
2313
+ *
2314
+ * リダイレクトは設計どおりの使い方なので、コンソールには何も出さない。履歴は**置き換える** —
2315
+ * 守られた URL は表示されていないので「戻る」の行き先にしない(push だと、戻るたびに同じ
2316
+ * リダイレクトへ戻される)。初期化(connectedCallbackPromise)の後で行う — 初期化中の遷移は
2317
+ * navigate リスナに捕まらず、文書ごと読み直される。guard 同士が送り合うループは
2318
+ * MAX_GUARD_REDIRECTS 回で止めてエラーにする。
2279
2319
  *
2280
2320
  * showRouteContent の相 1 であると同時に、SSR ハイドレーション
2281
2321
  * (docs/ssr-router-design.md §4 — 採用はレンダリング最適化であって認可の
@@ -2294,14 +2334,24 @@ async function runGuardPhase(routerNode, matchResult) {
2294
2334
  }
2295
2335
  }
2296
2336
  matchResult.data = data;
2337
+ redirectCounts.delete(routerNode);
2297
2338
  }
2298
2339
  catch (e) {
2299
2340
  if (e instanceof GuardCancel) {
2300
- console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`);
2301
- queueMicrotask(() => {
2302
- routerNode.navigate(e.fallbackPath).catch((err) => {
2341
+ const count = (redirectCounts.get(routerNode) ?? 0) + 1;
2342
+ if (count > MAX_GUARD_REDIRECTS) {
2343
+ redirectCounts.delete(routerNode);
2344
+ console.error(`${config.tagNames.router}: guard redirect loop — stopped after ${MAX_GUARD_REDIRECTS} redirects in a row ` +
2345
+ `(the last: ${matchResult.path} → ${e.fallbackPath}). The guards of these routes send each other back and forth.`);
2346
+ return false;
2347
+ }
2348
+ redirectCounts.set(routerNode, count);
2349
+ routerNode.connectedCallbackPromise
2350
+ .catch(() => { })
2351
+ .then(() => routerNode.replace(e.fallbackPath))
2352
+ .catch((err) => {
2353
+ if (!isAbortError(err))
2303
2354
  console.error('Fallback navigation failed:', err);
2304
- });
2305
2355
  });
2306
2356
  return false;
2307
2357
  }
@@ -2325,16 +2375,20 @@ async function runGuardPhase(routerNode, matchResult) {
2325
2375
  * 相を分けたことで「ガードが拒否したのに旧ルートだけ先に消えている」という
2326
2376
  * 順序の歪みも同時に解消している。
2327
2377
  *
2378
+ * `beforeChange` はガード相を通った後、変更相の前に呼ぶ(applyRoute はここで commit する)。
2379
+ *
2328
2380
  * @returns ガードチェックを通過してコンテンツ表示が成立した場合 true、
2329
2381
  * GuardCancel により中断(フォールバックへ再ナビゲート)した場合 false。
2330
2382
  * 呼び出し側(applyRoute)は false の場合、router.path / outlet.lastRoutes を
2331
2383
  * 更新しないことで「拒否されたパスでの path-changed 発火」を防ぐ。
2332
2384
  */
2333
- async function showRouteContent(routerNode, matchResult, lastRoutes) {
2385
+ async function showRouteContent(routerNode, matchResult, lastRoutes, beforeChange) {
2334
2386
  // --- ガード相 ---
2335
2387
  if (!(await runGuardPhase(routerNode, matchResult))) {
2336
2388
  return false;
2337
2389
  }
2390
+ // 中身を描く前(applyRoute の commit — 中身のバインディングがこの遷移の出力を読めるように)
2391
+ beforeChange?.();
2338
2392
  // --- 変更相 ---
2339
2393
  const routesSet = new Set(matchResult.routes);
2340
2394
  const lastRouteSet = new Set(lastRoutes);
@@ -2444,22 +2498,24 @@ async function applyRoute(routerNode, outlet, fullPath, lastPath, search = "") {
2444
2498
  // guard 相の第 3 引数(IGuardContext.searchParams)が commit と同じクエリを読めるように供給する
2445
2499
  matchResult.search = search;
2446
2500
  const lastRoutes = outlet.lastRoutes;
2447
- const committed = await showRouteContent(routerNode, matchResult, lastRoutes);
2448
- // GuardCancel により中断された場合は state を更新しない
2449
- // (拒否されたパスでの wcs-router:path-changed 発火を防ぐため)
2501
+ // guard 相を通ったら、中身を描く前に commit する(path-changed だけ描いた後)。中身の
2502
+ // バインディングが最初からこの遷移の params / data を読めるように(Router.commitNavigation)。
2503
+ // GuardCancel で中断された場合は commit しない(拒否されたパスでの発火を防ぐため)
2504
+ const committed = await showRouteContent(routerNode, matchResult, lastRoutes, () => {
2505
+ // routeName は最深マッチの name。fallback 時は fallback ルートの name(D8)。
2506
+ routerNode.commitNavigation({
2507
+ params: matchResult.params,
2508
+ typedParams: matchResult.typedParams,
2509
+ routeName: matchResult.routes[matchResult.routes.length - 1]?.name ?? "",
2510
+ // guard 相(runGuardPhase)が集めたロード済みデータ。無ければ null に戻る
2511
+ data: matchResult.data ?? null,
2512
+ search,
2513
+ path,
2514
+ }, true);
2515
+ });
2450
2516
  if (!committed)
2451
2517
  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
- });
2518
+ routerNode.releasePath();
2463
2519
  outlet.lastRoutes = matchResult.routes;
2464
2520
  // オプトインの focus/announce は commit 直後・mutate() の外で適用する(D3)。
2465
2521
  // 初回描画(lastRoutes が空)では動かない — ページロードはブラウザの担当で、
@@ -2653,6 +2709,7 @@ class Router extends HTMLElement {
2653
2709
  { name: "basename", attribute: "basename" },
2654
2710
  { name: "navigateUrl" },
2655
2711
  { name: "replaceUrl" },
2712
+ { name: "leaveConfirm", attribute: "leave-confirm" },
2656
2713
  ],
2657
2714
  commands: [
2658
2715
  { name: "navigate", async: true },
@@ -2685,6 +2742,13 @@ class Router extends HTMLElement {
2685
2742
  _data = null;
2686
2743
  /** 最初の成功 commit を通過したか(§4.4 の初回ガード) */
2687
2744
  _hasCommitted = false;
2745
+ /** commitNavigation(…, true) が path-changed の発火を保留している(releasePath で発火) */
2746
+ _pathHeld = false;
2747
+ /** 自分の navigate() / replace() が離脱の確認を済ませて navigation.navigate() を呼んでいる間 */
2748
+ _leaveChecked = false;
2749
+ /** 離脱が確認された: 次の commit まで(その遷移の guard のリダイレクトで聞き直さない) */
2750
+ _leaveConfirmed = false;
2751
+ _listeningUnload = false;
2688
2752
  _connectedCallbackPromise;
2689
2753
  _resolveConnectedCallback = null;
2690
2754
  _rejectConnectedCallback = null;
@@ -2794,6 +2858,44 @@ class Router extends HTMLElement {
2794
2858
  set basename(value) {
2795
2859
  reflectAttribute(this, "basename", value);
2796
2860
  }
2861
+ // `leaveConfirm` は input(属性は leave-confirm)。空でない文字列の間、別のルートへ出るナビゲーション
2862
+ // (リンク・戻る / 進む・navigate())の前に confirm(値) を出し、断られたら出ない。ページを閉じる・
2863
+ // 読み直すときはブラウザ自身の確認(beforeunload)。未保存の変更を守る口(docs/seam-apps.md、
2864
+ // router-admin — Navigation API を直接使うしかなかった)。null は属性を外し、undefined は最初の属性へ戻す。
2865
+ get leaveConfirm() {
2866
+ return this.getAttribute("leave-confirm") || null;
2867
+ }
2868
+ set leaveConfirm(value) {
2869
+ reflectAttribute(this, "leave-confirm", value);
2870
+ this._syncBeforeUnload();
2871
+ }
2872
+ _onBeforeUnload = (e) => {
2873
+ if (this.leaveConfirm !== null)
2874
+ e.preventDefault();
2875
+ };
2876
+ /** beforeunload は leaveConfirm がある間だけ聞く(リスナーがあるだけで bfcache を外すブラウザがある) */
2877
+ _syncBeforeUnload() {
2878
+ const want = this.isConnected && this.leaveConfirm !== null && !inSsr();
2879
+ if (want === this._listeningUnload)
2880
+ return;
2881
+ this._listeningUnload = want;
2882
+ if (want)
2883
+ window.addEventListener("beforeunload", this._onBeforeUnload);
2884
+ else
2885
+ window.removeEventListener("beforeunload", this._onBeforeUnload);
2886
+ }
2887
+ /**
2888
+ * 別のルートへ出る前の確認。断られたら false。leaveConfirm が無い・最初の表示の前・同じルート
2889
+ * (クエリだけの遷移)・確認済みの遷移の続き(guard のリダイレクト)では聞かない。
2890
+ */
2891
+ _confirmLeave(fullPath) {
2892
+ const message = this.leaveConfirm;
2893
+ if (message === null || !this._hasCommitted || this._leaveConfirmed ||
2894
+ this.isSameMatch(sliceBasename(this._normalizePathname(fullPath), this._basename))) {
2895
+ return true;
2896
+ }
2897
+ return (this._leaveConfirmed = window.confirm(message));
2898
+ }
2797
2899
  _getOutlet() {
2798
2900
  // outlet は自身の直後の兄弟だけ(docs/router-outlet-placement.md)。マルチ Router で router と
2799
2901
  // outlet を 1 対 1 に結ぶための規則で、SSR の採用経路もこの位置を前提にする。
@@ -2888,8 +2990,14 @@ class Router extends HTMLElement {
2888
2990
  * 先頭に置くのは、params のリスナーがロード済みデータを読めるようにするため。
2889
2991
  * `path` を最後に置くのは、既存例で `path` が「ナビゲーション完了」の信号として
2890
2992
  * 使われているため。各イベントは変化した commit のみ発火する。
2993
+ *
2994
+ * `holdPath` は path-changed だけを `releasePath()` まで保留する。applyRoute はルートの中身を
2995
+ * 描く前にこれで commit する — 中身のバインディング(state)が、その遷移の params / data を
2996
+ * 最初から読めるように。保留しないと、中身は前のルートの値で一度評価され、getter や
2997
+ * フィルタが例外を出しうる(docs/seam-apps.md、router-auth)。path は中身を描いた後に発火し、
2998
+ * 「ナビゲーション完了」の意味を保つ。
2891
2999
  */
2892
- commitNavigation(commit) {
3000
+ commitNavigation(commit, holdPath = false) {
2893
3001
  const nextParams = Object.freeze({ ...commit.params });
2894
3002
  const nextTypedParams = Object.freeze({ ...commit.typedParams });
2895
3003
  const nextSearchParams = parseSearchParams(commit.search);
@@ -2919,6 +3027,7 @@ class Router extends HTMLElement {
2919
3027
  }
2920
3028
  this._path = commit.path;
2921
3029
  this._hasCommitted = true;
3030
+ this._leaveConfirmed = false;
2922
3031
  // --- その後で発火(順序規範: data → params → route-name → search → path) ---
2923
3032
  if (dataChanged) {
2924
3033
  this.dispatchEvent(new CustomEvent("wcs-router:data-changed", {
@@ -2944,13 +3053,23 @@ class Router extends HTMLElement {
2944
3053
  bubbles: true,
2945
3054
  }));
2946
3055
  }
2947
- if (pathChanged) {
2948
- this.dispatchEvent(new CustomEvent("wcs-router:path-changed", {
2949
- detail: commit.path,
2950
- bubbles: true,
2951
- }));
3056
+ this._pathHeld = pathChanged && holdPath;
3057
+ if (pathChanged && !holdPath) {
3058
+ this._firePathChanged();
3059
+ }
3060
+ }
3061
+ releasePath() {
3062
+ if (this._pathHeld) {
3063
+ this._pathHeld = false;
3064
+ this._firePathChanged();
2952
3065
  }
2953
3066
  }
3067
+ _firePathChanged() {
3068
+ this.dispatchEvent(new CustomEvent("wcs-router:path-changed", {
3069
+ detail: this._path,
3070
+ bubbles: true,
3071
+ }));
3072
+ }
2954
3073
  get fallbackRoute() {
2955
3074
  return this._fallbackRoute;
2956
3075
  }
@@ -2971,7 +3090,8 @@ class Router extends HTMLElement {
2971
3090
  return;
2972
3091
  this._navigateUrl = value;
2973
3092
  this.navigate(value).catch((err) => {
2974
- console.error(`${config.tagNames.router} navigate failed:`, err);
3093
+ if (!isAbortError(err))
3094
+ console.error(`${config.tagNames.router} navigate failed:`, err);
2975
3095
  }).finally(() => {
2976
3096
  this._navigateUrl = null;
2977
3097
  this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed", {
@@ -2996,7 +3116,8 @@ class Router extends HTMLElement {
2996
3116
  return;
2997
3117
  this._replaceUrl = value;
2998
3118
  this.replace(value).catch((err) => {
2999
- console.error(`${config.tagNames.router} replace failed:`, err);
3119
+ if (!isAbortError(err))
3120
+ console.error(`${config.tagNames.router} replace failed:`, err);
3000
3121
  }).finally(() => {
3001
3122
  this._replaceUrl = null;
3002
3123
  this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed", {
@@ -3026,6 +3147,13 @@ class Router extends HTMLElement {
3026
3147
  ? window.location.pathname
3027
3148
  : this._joinInternalPath(this._basename, target.pathname);
3028
3149
  const url = fullPath + effectiveSearch(target.search) + target.hash;
3150
+ if (this.leaveConfirm !== null) {
3151
+ // 1 マイクロタスク待ってから確かめる: 保存のハンドラが leaveConfirm を外すバインディングと
3152
+ // navigateUrl を同じ drain で書いたとき、どちらが先に適用されても外れた後の値を見る
3153
+ await Promise.resolve();
3154
+ if (!this._confirmLeave(fullPath))
3155
+ return;
3156
+ }
3029
3157
  const navigation = getNavigation();
3030
3158
  if (navigation?.navigate) {
3031
3159
  // Navigation API は { committed, finished } を返す。
@@ -3033,9 +3161,17 @@ class Router extends HTMLElement {
3033
3161
  // 実際のナビゲーション完了まで pending となり、_navigateUrl / _replaceUrl の
3034
3162
  // 二重起動ガード (setter 内の同一値チェック) が適切な時間ウィンドウで機能する。
3035
3163
  // Polyfill や mock 環境で undefined / 戻り値なしのケースもあるため optional chaining。
3036
- const result = replace
3037
- ? navigation.navigate(url, { history: "replace" })
3038
- : navigation.navigate(url);
3164
+ // navigate イベントは navigate() の中で同期に来る: そこでの確認は済ませた
3165
+ this._leaveChecked = true;
3166
+ let result;
3167
+ try {
3168
+ result = replace
3169
+ ? navigation.navigate(url, { history: "replace" })
3170
+ : navigation.navigate(url);
3171
+ }
3172
+ finally {
3173
+ this._leaveChecked = false;
3174
+ }
3039
3175
  await result?.finished;
3040
3176
  }
3041
3177
  else {
@@ -3073,6 +3209,9 @@ class Router extends HTMLElement {
3073
3209
  }
3074
3210
  _onNavigateFunc(navEvent) {
3075
3211
  if (!navEvent.canIntercept ||
3212
+ // ページ側が取り消したナビゲーション(未保存の確認など)に intercept() を呼ぶと
3213
+ // InvalidStateError が投げられる(docs/seam-apps.md、router-admin)
3214
+ navEvent.defaultPrevented ||
3076
3215
  navEvent.hashChange ||
3077
3216
  navEvent.downloadRequest !== null) {
3078
3217
  return;
@@ -3082,6 +3221,12 @@ class Router extends HTMLElement {
3082
3221
  // basename 配下でない URL は無視(マルチ Router 対応)
3083
3222
  if (!this._isOwnPath(fullPath))
3084
3223
  return;
3224
+ // 別のルートへ出る前の確認(leaveConfirm)。取り消せないナビゲーション(一部の戻る / 進む)では
3225
+ // 聞けない。自分の navigate() / replace() からのものは確認済み
3226
+ if (!this._leaveChecked && navEvent.cancelable !== false && !this._confirmLeave(fullPath)) {
3227
+ navEvent.preventDefault?.();
3228
+ return;
3229
+ }
3085
3230
  // same-match 判定は applyRoute 内の分岐と同じ共有実装(§4.4: スライス後比較)。
3086
3231
  // intercept オプションは applyRoute 実行前に決める必要があるためここでも判定する。
3087
3232
  const sameMatch = this.isSameMatch(sliceBasename(fullPath, this._basename));
@@ -3495,6 +3640,8 @@ class Router extends HTMLElement {
3495
3640
  // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)。
3496
3641
  // await より前に同期で行い、初期化が古い値を読まないようにする。
3497
3642
  upgradeProperties(this);
3643
+ // マークアップに書いた leave-confirm も beforeunload で守る(初期化の成否によらず)
3644
+ this._syncBeforeUnload();
3498
3645
  // SSR モード(docs/ssr-router-design.md §3.2):
3499
3646
  // - enable-ssr 無し → サーバーでは一切初期化しない(クライアント専用 = 部分 CSR)
3500
3647
  // - enable-ssr あり → SSR 初期化のみ。navigate / popstate リスナは登録しない
@@ -3576,6 +3723,7 @@ class Router extends HTMLElement {
3576
3723
  window.removeEventListener("popstate", this._onPopState);
3577
3724
  this._listeningPopState = false;
3578
3725
  }
3726
+ this._syncBeforeUnload();
3579
3727
  // live region は router の寿命に同期して撤去する(body 直下に置かない理由と同根)
3580
3728
  if (this._a11yRegion !== null) {
3581
3729
  this._a11yRegion.remove();
@@ -3592,7 +3740,7 @@ class Router extends HTMLElement {
3592
3740
  const MIRRORED_ATTRIBUTES = ['title', 'rel', 'target', 'download', 'hreflang', 'lang', 'dir'];
3593
3741
  class Link extends HTMLElement {
3594
3742
  static get observedAttributes() {
3595
- return ['to', ...MIRRORED_ATTRIBUTES];
3743
+ return ['to', 'match', ...MIRRORED_ATTRIBUTES];
3596
3744
  }
3597
3745
  _childNodeArray = [];
3598
3746
  _uuid = getUUID();
@@ -3807,6 +3955,10 @@ class Link extends HTMLElement {
3807
3955
  this._router = null;
3808
3956
  }
3809
3957
  attributeChangedCallback(name, oldValue, newValue) {
3958
+ if (name === 'match' && oldValue !== newValue) {
3959
+ this._updateActiveState();
3960
+ return;
3961
+ }
3810
3962
  if (name === 'to' && oldValue !== newValue) {
3811
3963
  this._path = newValue || '';
3812
3964
  if (this._anchorElement) {
@@ -3841,12 +3993,16 @@ class Link extends HTMLElement {
3841
3993
  ? window.location.pathname
3842
3994
  : this._joinInternalPath(this.router.basename, pathname))
3843
3995
  : pathname);
3996
+ // match="prefix": 下のパスでも active(サイドナビの「商品」が /products/3 でも印を付ける —
3997
+ // docs/seam-apps.md、router-admin)。そのページそのものではないので aria-current は "true"
3998
+ const exact = currentPath === linkPath;
3999
+ const within = !exact && this.getAttribute('match') === 'prefix' && currentPath.startsWith(linkPath + '/');
3844
4000
  if (this._anchorElement) {
3845
- if (currentPath === linkPath) {
4001
+ if (exact || within) {
3846
4002
  this._anchorElement.classList.add('active');
3847
4003
  // 修理・既定オン(docs/a11y-design.md §3-3): active class と同じ事実の ARIA 表現。
3848
4004
  // 鮮度保証は active class と同一(同じ分岐・同じ呼び出し経路)。
3849
- this._anchorElement.setAttribute('aria-current', 'page');
4005
+ this._anchorElement.setAttribute('aria-current', exact ? 'page' : 'true');
3850
4006
  }
3851
4007
  else {
3852
4008
  this._anchorElement.classList.remove('active');
@@ -4137,7 +4293,7 @@ function bootstrapRouter(config, registry) {
4137
4293
  registerComponents(registry);
4138
4294
  }
4139
4295
 
4140
- var version = "4.0.4";
4296
+ var version = "4.1.1";
4141
4297
  var pkg = {
4142
4298
  version: version};
4143
4299