@real-router/angular 0.4.0 → 0.6.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.md CHANGED
@@ -110,6 +110,8 @@ All inject functions must be called within an injection context (constructor, fi
110
110
  | `injectRouteUtils()` | `RouteUtils` | Never |
111
111
  | `injectRouterTransition()` | `Signal<RouterTransitionSnapshot>` | On transition start/end |
112
112
  | `injectIsActiveRoute(name, params?, opts?)` | `Signal<boolean>` | On active state change |
113
+ | `injectRouteExit(handler, options?)` | `void` — wraps `subscribeLeave` with abort + same-route guards | Never (handler captured at injection time) |
114
+ | `injectRouteEnter(handler, options?)` | `void` — fires once on nav-driven mount via `effect()` + `transition.from` | Never (handler captured at injection time) |
113
115
 
114
116
  `RouteSignals` shape:
115
117
 
@@ -166,8 +168,48 @@ export class BackButtonComponent {
166
168
  export class ProgressComponent {
167
169
  readonly transition = injectRouterTransition();
168
170
  }
171
+
172
+ // injectRouteExit — exit animations, draft autosave, AbortSignal-aware cleanup
173
+ @Component({
174
+ selector: "app-fade-out",
175
+ template: `<div #box>...</div>`,
176
+ })
177
+ export class FadeOutComponent {
178
+ private el = viewChild.required<ElementRef<HTMLDivElement>>("box");
179
+
180
+ constructor() {
181
+ injectRouteExit(async ({ signal }) => {
182
+ const el = this.el().nativeElement;
183
+ el.classList.add("fade-out");
184
+ const cleanup = () => el.classList.remove("fade-out");
185
+ signal.addEventListener("abort", cleanup, { once: true });
186
+ el.getBoundingClientRect(); // style flush
187
+ await Promise.allSettled(el.getAnimations().map((a) => a.finished));
188
+ cleanup();
189
+ });
190
+ }
191
+ }
192
+
193
+ // injectRouteEnter — page-enter analytics, focus management, entry animations
194
+ @Component({ selector: "app-page-enter", template: "" })
195
+ export class PageEnterAnalyticsComponent {
196
+ constructor() {
197
+ injectRouteEnter(({ route, previousRoute }) => {
198
+ analytics.track("page_enter", {
199
+ route: route.name,
200
+ from: previousRoute.name,
201
+ });
202
+ });
203
+ }
204
+ }
169
205
  ```
170
206
 
207
+ > **Angular handler-reactivity:** `inject*` functions run once at construction,
208
+ > so `handler` is captured at injection time. Pass a class method (stable
209
+ > identity) and read signals **inside** the handler body to react to changes.
210
+ > See [CLAUDE.md](./CLAUDE.md) → "injectRouteExit / injectRouteEnter Handler
211
+ > Is Captured At Injection Time".
212
+
171
213
  ## Components
172
214
 
173
215
  ### `<route-view>`
@@ -358,11 +400,28 @@ bootstrapApplication(AppComponent, {
358
400
  ```typescript
359
401
  interface RealRouterOptions {
360
402
  scrollRestoration?: ScrollRestorationOptions; // { mode?, anchorScrolling?, scrollContainer? }
403
+ viewTransitions?: boolean;
361
404
  }
362
405
  ```
363
406
 
364
407
  Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"manual"`. Custom containers via `scrollContainer: () => HTMLElement | null`. The utility is created by `provideEnvironmentInitializer` and torn down via `inject(DestroyRef)`. Options are a snapshot at bootstrap — not reactive to runtime changes. See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for details.
365
408
 
409
+ ## View Transitions
410
+
411
+ Opt-in animated route transitions via the browser's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API):
412
+
413
+ ```typescript
414
+ import { provideRealRouter } from "@real-router/angular";
415
+
416
+ bootstrapApplication(AppComponent, {
417
+ providers: [
418
+ provideRealRouter(router, { viewTransitions: true }),
419
+ ],
420
+ });
421
+ ```
422
+
423
+ No-op on unsupported browsers (Firefox as of 2026-04, SSR). Utility is created by `provideEnvironmentInitializer` at bootstrap and torn down via `inject(DestroyRef)`. Option is a snapshot at bootstrap — not reactive to runtime changes. Customization is pure CSS via `::view-transition-*` pseudo-elements and `view-transition-name` for hero morphs. See [View Transitions guide](https://github.com/greydragon888/real-router/wiki/View-Transitions) for patterns.
424
+
366
425
  ## Angular-Specific Patterns
367
426
 
368
427
  ### Signals, Not Observables
@@ -460,7 +519,7 @@ const transitionSignal = sourceToSignal(createTransitionSource(router));
460
519
  Full documentation: [Wiki](https://github.com/greydragon888/real-router/wiki)
461
520
 
462
521
  - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration)
463
- - [injectRouter](https://github.com/greydragon888/real-router/wiki/injectRouter) · [injectRoute](https://github.com/greydragon888/real-router/wiki/injectRoute) · [injectRouteNode](https://github.com/greydragon888/real-router/wiki/injectRouteNode) · [injectNavigator](https://github.com/greydragon888/real-router/wiki/injectNavigator) · [injectRouteUtils](https://github.com/greydragon888/real-router/wiki/injectRouteUtils) · [injectRouterTransition](https://github.com/greydragon888/real-router/wiki/injectRouterTransition)
522
+ - [injectRouter](https://github.com/greydragon888/real-router/wiki/injectRouter) · [injectRoute](https://github.com/greydragon888/real-router/wiki/injectRoute) · [injectRouteNode](https://github.com/greydragon888/real-router/wiki/injectRouteNode) · [injectNavigator](https://github.com/greydragon888/real-router/wiki/injectNavigator) · [injectRouteUtils](https://github.com/greydragon888/real-router/wiki/injectRouteUtils) · [injectRouterTransition](https://github.com/greydragon888/real-router/wiki/injectRouterTransition) · [injectRouteExit](https://github.com/greydragon888/real-router/wiki/injectRouteExit) · [injectRouteEnter](https://github.com/greydragon888/real-router/wiki/injectRouteEnter)
464
523
 
465
524
  ## Related Packages
466
525
 
package/dist/README.md CHANGED
@@ -110,6 +110,8 @@ All inject functions must be called within an injection context (constructor, fi
110
110
  | `injectRouteUtils()` | `RouteUtils` | Never |
111
111
  | `injectRouterTransition()` | `Signal<RouterTransitionSnapshot>` | On transition start/end |
112
112
  | `injectIsActiveRoute(name, params?, opts?)` | `Signal<boolean>` | On active state change |
113
+ | `injectRouteExit(handler, options?)` | `void` — wraps `subscribeLeave` with abort + same-route guards | Never (handler captured at injection time) |
114
+ | `injectRouteEnter(handler, options?)` | `void` — fires once on nav-driven mount via `effect()` + `transition.from` | Never (handler captured at injection time) |
113
115
 
114
116
  `RouteSignals` shape:
115
117
 
@@ -166,8 +168,48 @@ export class BackButtonComponent {
166
168
  export class ProgressComponent {
167
169
  readonly transition = injectRouterTransition();
168
170
  }
171
+
172
+ // injectRouteExit — exit animations, draft autosave, AbortSignal-aware cleanup
173
+ @Component({
174
+ selector: "app-fade-out",
175
+ template: `<div #box>...</div>`,
176
+ })
177
+ export class FadeOutComponent {
178
+ private el = viewChild.required<ElementRef<HTMLDivElement>>("box");
179
+
180
+ constructor() {
181
+ injectRouteExit(async ({ signal }) => {
182
+ const el = this.el().nativeElement;
183
+ el.classList.add("fade-out");
184
+ const cleanup = () => el.classList.remove("fade-out");
185
+ signal.addEventListener("abort", cleanup, { once: true });
186
+ el.getBoundingClientRect(); // style flush
187
+ await Promise.allSettled(el.getAnimations().map((a) => a.finished));
188
+ cleanup();
189
+ });
190
+ }
191
+ }
192
+
193
+ // injectRouteEnter — page-enter analytics, focus management, entry animations
194
+ @Component({ selector: "app-page-enter", template: "" })
195
+ export class PageEnterAnalyticsComponent {
196
+ constructor() {
197
+ injectRouteEnter(({ route, previousRoute }) => {
198
+ analytics.track("page_enter", {
199
+ route: route.name,
200
+ from: previousRoute.name,
201
+ });
202
+ });
203
+ }
204
+ }
169
205
  ```
170
206
 
207
+ > **Angular handler-reactivity:** `inject*` functions run once at construction,
208
+ > so `handler` is captured at injection time. Pass a class method (stable
209
+ > identity) and read signals **inside** the handler body to react to changes.
210
+ > See [CLAUDE.md](./CLAUDE.md) → "injectRouteExit / injectRouteEnter Handler
211
+ > Is Captured At Injection Time".
212
+
171
213
  ## Components
172
214
 
173
215
  ### `<route-view>`
@@ -358,11 +400,28 @@ bootstrapApplication(AppComponent, {
358
400
  ```typescript
359
401
  interface RealRouterOptions {
360
402
  scrollRestoration?: ScrollRestorationOptions; // { mode?, anchorScrolling?, scrollContainer? }
403
+ viewTransitions?: boolean;
361
404
  }
362
405
  ```
363
406
 
364
407
  Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"manual"`. Custom containers via `scrollContainer: () => HTMLElement | null`. The utility is created by `provideEnvironmentInitializer` and torn down via `inject(DestroyRef)`. Options are a snapshot at bootstrap — not reactive to runtime changes. See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for details.
365
408
 
409
+ ## View Transitions
410
+
411
+ Opt-in animated route transitions via the browser's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API):
412
+
413
+ ```typescript
414
+ import { provideRealRouter } from "@real-router/angular";
415
+
416
+ bootstrapApplication(AppComponent, {
417
+ providers: [
418
+ provideRealRouter(router, { viewTransitions: true }),
419
+ ],
420
+ });
421
+ ```
422
+
423
+ No-op on unsupported browsers (Firefox as of 2026-04, SSR). Utility is created by `provideEnvironmentInitializer` at bootstrap and torn down via `inject(DestroyRef)`. Option is a snapshot at bootstrap — not reactive to runtime changes. Customization is pure CSS via `::view-transition-*` pseudo-elements and `view-transition-name` for hero morphs. See [View Transitions guide](https://github.com/greydragon888/real-router/wiki/View-Transitions) for patterns.
424
+
366
425
  ## Angular-Specific Patterns
367
426
 
368
427
  ### Signals, Not Observables
@@ -460,7 +519,7 @@ const transitionSignal = sourceToSignal(createTransitionSource(router));
460
519
  Full documentation: [Wiki](https://github.com/greydragon888/real-router/wiki)
461
520
 
462
521
  - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration)
463
- - [injectRouter](https://github.com/greydragon888/real-router/wiki/injectRouter) · [injectRoute](https://github.com/greydragon888/real-router/wiki/injectRoute) · [injectRouteNode](https://github.com/greydragon888/real-router/wiki/injectRouteNode) · [injectNavigator](https://github.com/greydragon888/real-router/wiki/injectNavigator) · [injectRouteUtils](https://github.com/greydragon888/real-router/wiki/injectRouteUtils) · [injectRouterTransition](https://github.com/greydragon888/real-router/wiki/injectRouterTransition)
522
+ - [injectRouter](https://github.com/greydragon888/real-router/wiki/injectRouter) · [injectRoute](https://github.com/greydragon888/real-router/wiki/injectRoute) · [injectRouteNode](https://github.com/greydragon888/real-router/wiki/injectRouteNode) · [injectNavigator](https://github.com/greydragon888/real-router/wiki/injectNavigator) · [injectRouteUtils](https://github.com/greydragon888/real-router/wiki/injectRouteUtils) · [injectRouterTransition](https://github.com/greydragon888/real-router/wiki/injectRouterTransition) · [injectRouteExit](https://github.com/greydragon888/real-router/wiki/injectRouteExit) · [injectRouteEnter](https://github.com/greydragon888/real-router/wiki/injectRouteEnter)
464
523
 
465
524
  ## Related Packages
466
525
 
@@ -1,11 +1,69 @@
1
1
  import * as i0 from '@angular/core';
2
- import { signal, inject, DestroyRef, InjectionToken, provideEnvironmentInitializer, makeEnvironmentProviders, input, TemplateRef, Directive, contentChildren, computed, Component, output, effect, ElementRef } from '@angular/core';
2
+ import { signal, inject, DestroyRef, InjectionToken, provideEnvironmentInitializer, ApplicationRef, makeEnvironmentProviders, assertInInjectionContext, effect, input, TemplateRef, Directive, contentChildren, computed, Component, output, ElementRef } from '@angular/core';
3
3
  import { getNavigator, UNKNOWN_ROUTE } from '@real-router/core';
4
4
  import { createRouteSource, createRouteNodeSource, getTransitionSource, createActiveRouteSource, createDismissableError } from '@real-router/sources';
5
5
  import { getPluginApi } from '@real-router/core/api';
6
6
  import { getRouteUtils, startsWithSegment } from '@real-router/route-utils';
7
7
  import { NgTemplateOutlet } from '@angular/common';
8
8
 
9
+ const NOOP_INSTANCE$2 = Object.freeze({
10
+ destroy: () => {
11
+ /* no-op */
12
+ },
13
+ });
14
+ /**
15
+ * Track navigation direction (forward / back) and write it to
16
+ * `<html data-nav-direction>` on every leave. CSS / JS readers consume
17
+ * the attribute via `html[data-nav-direction="back"]` selectors or
18
+ * `document.documentElement.dataset.navDirection`.
19
+ *
20
+ * Mechanism-agnostic — works identically whether downstream UI uses CSS
21
+ * `@keyframes`, View Transitions pseudo-elements, or library state
22
+ * (motion's `motion.div initial={{ x: ... }}`).
23
+ *
24
+ * Implementation:
25
+ * - On install, set `data-nav-direction="forward"` baseline.
26
+ * - Attach a `popstate` listener that flips an internal flag to
27
+ * `true`. Browser back/forward navigation triggers popstate; user
28
+ * clicks on `<Link>` / programmatic `router.navigate(...)` do not.
29
+ * - On every `subscribeLeave`, write
30
+ * `popstateFlag ? "back" : "forward"` and reset the flag.
31
+ *
32
+ * Returns `{ destroy }` to clean up the listener and clear the dataset
33
+ * attribute.
34
+ */
35
+ function createDirectionTracker(router) {
36
+ if (typeof document === "undefined") {
37
+ return NOOP_INSTANCE$2;
38
+ }
39
+ let popstateFlag = false;
40
+ document.documentElement.dataset.navDirection = "forward";
41
+ const onPopstate = () => {
42
+ popstateFlag = true;
43
+ };
44
+ // IMPORTANT — listener-ordering: `popstate` fires on `window`, which
45
+ // has no DOM descendants, so capture phase is moot. Listeners are
46
+ // dispatched in registration order. To beat the browser-plugin's own
47
+ // popstate handler, this tracker must be installed **before**
48
+ // `router.usePlugin(browserPluginFactory())` in user code. Otherwise
49
+ // the plugin's handler runs first and synchronously fires
50
+ // `subscribeLeave` while `popstateFlag` is still `false`.
51
+ globalThis.addEventListener("popstate", onPopstate);
52
+ const offLeave = router.subscribeLeave(() => {
53
+ document.documentElement.dataset.navDirection = popstateFlag
54
+ ? "back"
55
+ : "forward";
56
+ popstateFlag = false;
57
+ });
58
+ return {
59
+ destroy: () => {
60
+ offLeave();
61
+ globalThis.removeEventListener("popstate", onPopstate);
62
+ delete document.documentElement.dataset.navDirection;
63
+ },
64
+ };
65
+ }
66
+
9
67
  const CLEAR_DELAY = 7000;
10
68
  const SAFARI_READY_DELAY = 100;
11
69
  const ANNOUNCER_ATTR = "data-real-router-announcer";
@@ -102,7 +160,7 @@ function resolveText(route, prefix, getCustomText, h1) {
102
160
  if (getCustomText) {
103
161
  return getCustomText(route);
104
162
  }
105
- const h1Text = h1?.textContent.trim() ?? "";
163
+ const h1Text = (h1?.textContent ?? "").trim();
106
164
  const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)
107
165
  ? ""
108
166
  : route.name;
@@ -120,21 +178,21 @@ function manageFocus(h1) {
120
178
  }
121
179
 
122
180
  const STORAGE_KEY = "real-router:scroll";
123
- const NOOP_INSTANCE = Object.freeze({
181
+ const NOOP_INSTANCE$1 = Object.freeze({
124
182
  destroy: () => {
125
183
  /* no-op */
126
184
  },
127
185
  });
128
186
  function createScrollRestoration(router, options) {
129
187
  if (typeof globalThis.window === "undefined") {
130
- return NOOP_INSTANCE;
188
+ return NOOP_INSTANCE$1;
131
189
  }
132
190
  const mode = options?.mode ?? "restore";
133
191
  // mode "manual" = utility does nothing. Don't flip history.scrollRestoration,
134
192
  // don't subscribe, don't register pagehide — leave the browser's native
135
193
  // auto-restore intact for the app to override if it wants to.
136
194
  if (mode === "manual") {
137
- return NOOP_INSTANCE;
195
+ return NOOP_INSTANCE$1;
138
196
  }
139
197
  const anchorEnabled = options?.anchorScrolling ?? true;
140
198
  const getContainer = options?.scrollContainer;
@@ -277,6 +335,125 @@ function canonicalReplacer(_key, val) {
277
335
  return val;
278
336
  }
279
337
 
338
+ const NOOP_INSTANCE = Object.freeze({
339
+ destroy: () => {
340
+ /* no-op */
341
+ },
342
+ });
343
+ function createViewTransitions(router) {
344
+ if (typeof document === "undefined" ||
345
+ typeof document.startViewTransition !== "function") {
346
+ return NOOP_INSTANCE;
347
+ }
348
+ let closeVT = null;
349
+ let currentVT = null;
350
+ // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to
351
+ // distinguish "benign cleanup abort" (router's async path aborts its own
352
+ // controller in a finally block after successful navigation) from "real
353
+ // cancellation" (concurrent navigate, guard rejection, dispose).
354
+ let successFired = false;
355
+ const resolveAndClear = () => {
356
+ closeVT?.();
357
+ closeVT = null;
358
+ };
359
+ const offLeave = router.subscribeLeave(({ signal }) => {
360
+ // Reentrant abort: signal already aborted when we're called. Open no VT
361
+ // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()
362
+ // after leave resolves. addEventListener("abort", ...) does not re-fire
363
+ // for past events, so skipping startViewTransition is the safe path.
364
+ if (signal.aborted) {
365
+ return;
366
+ }
367
+ successFired = false;
368
+ resolveAndClear();
369
+ // Return a Promise so the router awaits until the browser invokes
370
+ // updateCallback. This ensures old DOM snapshot is captured BEFORE the
371
+ // router commits the new state — giving correct exit→state→entry
372
+ // ordering (vs fire-and-forget, where URL changes before VT captures).
373
+ return new Promise((resolveLeave) => {
374
+ // Capture the resolver synchronously BEFORE startViewTransition() is
375
+ // called. The browser invokes updateCallback in a later task, but
376
+ // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we
377
+ // captured `resolve` inside the callback, subscribe would see closeVT
378
+ // still null and skip resolving — the deferred would hang for 4s
379
+ // until the VT API aborts with TimeoutError.
380
+ const deferred = new Promise((resolve) => {
381
+ closeVT = resolve;
382
+ });
383
+ signal.addEventListener("abort", () => {
384
+ if (successFired) {
385
+ // Router's async path (#finishAsyncNavigation) aborts its own
386
+ // controller in a finally block AFTER completeTransition (and
387
+ // thus AFTER subscribe fired). This is cleanup, not
388
+ // cancellation — VT is progressing normally, do nothing.
389
+ return;
390
+ }
391
+ // Real cancellation (concurrent navigate, dispose). Resolve the
392
+ // deferred so updateCallback can complete, skip the VT so no
393
+ // stale animation leaks, and unblock the router if the abort
394
+ // fires before updateCallback was invoked.
395
+ resolveAndClear();
396
+ currentVT?.skipTransition?.();
397
+ resolveLeave();
398
+ }, { once: true });
399
+ try {
400
+ currentVT = document.startViewTransition(() => {
401
+ // Resolving here unblocks the router at the moment the browser
402
+ // enters updateCallback — by spec, old DOM snapshot is captured
403
+ // before this callback runs. Router now proceeds through
404
+ // activation guards and setState; the VT animation waits on
405
+ // `deferred`, which is resolved from router.subscribe after a
406
+ // task-queue tick (see NOTE on setTimeout below).
407
+ resolveLeave();
408
+ return deferred;
409
+ });
410
+ }
411
+ catch {
412
+ // Defensive: spec says startViewTransition doesn't throw under
413
+ // normal conditions, but Chromium has had edge cases (detached
414
+ // document, extension interference). Clean up and unblock router.
415
+ resolveAndClear();
416
+ resolveLeave();
417
+ }
418
+ });
419
+ });
420
+ const offSuccess = router.subscribe(() => {
421
+ const resolver = closeVT;
422
+ successFired = true;
423
+ closeVT = null;
424
+ if (resolver === null) {
425
+ currentVT = null;
426
+ }
427
+ else {
428
+ // CRITICAL: CANNOT use requestAnimationFrame here. When the router
429
+ // takes the async path (leave returned a Promise), subscribe fires
430
+ // AFTER the browser has already transitioned VT into the
431
+ // "update-callback-called" phase. In that phase Chromium sets
432
+ // rendering suppression to true, which ALSO blocks rAF callbacks.
433
+ // rAF would never fire → deferred never resolves → browser aborts
434
+ // vt.ready with TimeoutError after 4s (observed in Chromium).
435
+ //
436
+ // setTimeout runs on the task queue independent of the rendering
437
+ // pipeline, so it fires regardless of suppression. React's scheduler
438
+ // uses MessageChannel tasks, which are queued before our setTimeout,
439
+ // so the new DOM is committed by the time our callback runs.
440
+ setTimeout(() => {
441
+ resolver();
442
+ currentVT = null;
443
+ }, 0);
444
+ }
445
+ });
446
+ return {
447
+ destroy: () => {
448
+ offLeave();
449
+ offSuccess();
450
+ currentVT?.skipTransition?.();
451
+ currentVT = null;
452
+ resolveAndClear();
453
+ },
454
+ };
455
+ }
456
+
280
457
  function shouldNavigate(evt) {
281
458
  return (evt.button === 0 &&
282
459
  !evt.metaKey &&
@@ -399,6 +576,32 @@ function provideRealRouter(router, options) {
399
576
  });
400
577
  }));
401
578
  }
579
+ if (options?.viewTransitions === true) {
580
+ providers.push(provideEnvironmentInitializer(() => {
581
+ const appRef = inject(ApplicationRef);
582
+ // Force synchronous change detection on every transition success
583
+ // BEFORE the VT utility resolves its deferred. The utility uses
584
+ // `setTimeout(0)` to release the new-snapshot capture, which is
585
+ // load-bearing because Chromium blocks rAF callbacks while VT sits
586
+ // in the `update-callback-called` phase. Angular's zoneless CD is
587
+ // rAF-driven by default — without this synchronous tick the new
588
+ // DOM is not committed when the browser captures the new snapshot,
589
+ // so old and new snapshots end up identical and animations finish
590
+ // in ~0 ms with no visible work (the inner-route `products.list ↔
591
+ // products.detail` morph in the example example was the canary).
592
+ // Subscribers fire in registration order; this one runs BEFORE
593
+ // `createViewTransitions` registers its own subscriber,
594
+ // guaranteeing CD completes first.
595
+ const offTick = router.subscribe(() => {
596
+ appRef.tick();
597
+ });
598
+ const vt = createViewTransitions(router);
599
+ inject(DestroyRef).onDestroy(() => {
600
+ offTick();
601
+ vt.destroy();
602
+ });
603
+ }));
604
+ }
402
605
  return makeEnvironmentProviders(providers);
403
606
  }
404
607
 
@@ -419,7 +622,11 @@ function injectNavigator() {
419
622
  }
420
623
 
421
624
  function injectRoute() {
422
- return injectOrThrow(ROUTE, "injectRoute");
625
+ const signals = injectOrThrow(ROUTE, "injectRoute");
626
+ if (!signals.routeState().route) {
627
+ throw new Error("injectRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?");
628
+ }
629
+ return signals;
423
630
  }
424
631
 
425
632
  function injectRouteNode(nodeName) {
@@ -450,6 +657,175 @@ function injectIsActiveRoute(routeName, params, options) {
450
657
  return sourceToSignal(source);
451
658
  }
452
659
 
660
+ /**
661
+ * Subscribe to the router's leave-window with the universal guards baked
662
+ * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
663
+ * boilerplate every time:
664
+ *
665
+ * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
666
+ * when the handler would run (rapid navigation superseded a slower
667
+ * one), the handler is skipped entirely.
668
+ * - **Same-route skip**: by default, `route.name === nextRoute.name`
669
+ * short-circuits the handler — query-only navigations skip the work.
670
+ * Opt out with `skipSameRoute: false`.
671
+ *
672
+ * Cleanup is bound to the injection context's `DestroyRef`. Must be
673
+ * called within an injection context (constructor, field initializer,
674
+ * or `runInInjectionContext`).
675
+ *
676
+ * If the handler returns a Promise, the router blocks on it. If the
677
+ * Promise resolves, navigation proceeds. If it rejects, the router emits
678
+ * `TRANSITION_CANCELLED`.
679
+ *
680
+ * **Handler reactivity (Angular):** `inject*` functions run **once**
681
+ * during component construction; `handler` is captured in closure at the
682
+ * call site. The common Angular pattern is to pass a class method
683
+ * (`this.onExit.bind(this)` or an arrow-property) — its identity is
684
+ * stable across change detection. To vary behavior over time, read
685
+ * signals **inside** the handler body — do not rely on swapping the
686
+ * handler reference.
687
+ *
688
+ * @example Animation
689
+ * ```ts
690
+ * \@Component({ ... })
691
+ * class FadeOutComponent {
692
+ * private el = inject(ElementRef<HTMLElement>);
693
+ *
694
+ * constructor() {
695
+ * injectRouteExit(async ({ signal }) => {
696
+ * const el = this.el.nativeElement;
697
+ * el.classList.add("fade-out");
698
+ * const cleanup = () => el.classList.remove("fade-out");
699
+ * signal.addEventListener("abort", cleanup, { once: true });
700
+ * try {
701
+ * el.getBoundingClientRect();
702
+ * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
703
+ * } finally {
704
+ * cleanup();
705
+ * }
706
+ * });
707
+ * }
708
+ * }
709
+ * ```
710
+ *
711
+ * @example Auto-save form draft
712
+ * ```ts
713
+ * injectRouteExit(async ({ signal }) => {
714
+ * if (this.formState.dirty) {
715
+ * await this.api.saveDraft(this.formState, { signal });
716
+ * }
717
+ * });
718
+ * ```
719
+ */
720
+ function injectRouteExit(handler, options) {
721
+ assertInInjectionContext(injectRouteExit);
722
+ const router = injectRouter();
723
+ const destroyRef = inject(DestroyRef);
724
+ const skipSameRoute = options?.skipSameRoute ?? true;
725
+ const off = router.subscribeLeave(({ route, nextRoute, signal }) => {
726
+ if (skipSameRoute && route.name === nextRoute.name) {
727
+ return;
728
+ }
729
+ if (signal.aborted) {
730
+ return;
731
+ }
732
+ return handler({ route, nextRoute, signal });
733
+ });
734
+ destroyRef.onDestroy(off);
735
+ }
736
+
737
+ /**
738
+ * Fire `handler` once when the component is created as a result of a
739
+ * navigation. Mirror of `injectRouteExit` for the entry side.
740
+ *
741
+ * What this function covers that an ad-hoc `effect()` + `injectRoute()`
742
+ * doesn't:
743
+ *
744
+ * - **Skip-initial**: handler is skipped when there is no
745
+ * `route.transition.from` (i.e. first-load mount). Most consumers
746
+ * want to fire side effects only on real navigations, not on
747
+ * hydration.
748
+ * - **Same-route skip** (default): handler is skipped when
749
+ * `route.transition.from === route.name`. Sort/filter/query-only
750
+ * navigations re-run the effect (because the `route` reference
751
+ * changes), but they are not "entries" in the animation / analytics
752
+ * sense. Opt out with `skipSameRoute: false`.
753
+ * - **Mount-time `route` / `previousRoute` snapshot**: handler receives
754
+ * the values that were live at the moment of effect activation.
755
+ *
756
+ * Effect cleanup is wired through the injection context's `DestroyRef`
757
+ * (Angular's `effect()` ties into the active context automatically).
758
+ * Must be called within an injection context (constructor, field
759
+ * initializer, or `runInInjectionContext`).
760
+ *
761
+ * **Handler reactivity (Angular):** `inject*` functions run **once**
762
+ * during component construction; `handler` is captured in closure at the
763
+ * call site. The common Angular pattern is to pass a class method —
764
+ * its identity is stable across change detection. To vary behavior
765
+ * over time, read signals **inside** the handler body.
766
+ *
767
+ * @example Direction-aware entry animation
768
+ * ```ts
769
+ * \@Component({ ... })
770
+ * class PageComponent {
771
+ * private el = inject(ElementRef<HTMLElement>);
772
+ *
773
+ * constructor() {
774
+ * injectRouteEnter(({ route }) => {
775
+ * const direction = route.context.browser?.direction;
776
+ * this.el.nativeElement.classList.add(
777
+ * direction === "back" ? "slide-from-left" : "slide-from-right",
778
+ * );
779
+ * });
780
+ * }
781
+ * }
782
+ * ```
783
+ *
784
+ * @example Analytics page-enter event (skip-initial built-in)
785
+ * ```ts
786
+ * injectRouteEnter(({ route, previousRoute }) => {
787
+ * analytics.track("page_enter", {
788
+ * route: route.name,
789
+ * from: previousRoute.name,
790
+ * });
791
+ * });
792
+ * ```
793
+ */
794
+ function injectRouteEnter(handler, options) {
795
+ assertInInjectionContext(injectRouteEnter);
796
+ const { routeState } = injectRoute();
797
+ const skipSameRoute = options?.skipSameRoute ?? true;
798
+ let lastHandledRoute = null;
799
+ effect(() => {
800
+ const { route, previousRoute } = routeState();
801
+ // Early-exit guards, top-down:
802
+ //
803
+ // - **Skip-initial**: `state.transition.from` is undefined only
804
+ // for the very first state committed by `router.start()`.
805
+ // - **Skip-same-route**: query-only navigations have
806
+ // `transition.from === route.name`. Opt-out via
807
+ // `skipSameRoute: false`.
808
+ // - **Defensive dedupe + missing `previousRoute`**: same `route`
809
+ // ref between effect re-runs is unexpected on Angular (the
810
+ // signal only fires on real reference changes); `!previousRoute`
811
+ // is unreachable once `transition.from` is set (core populates
812
+ // them together). Both kept for parity with React; v8-ignored.
813
+ if (!route.transition.from) {
814
+ return;
815
+ }
816
+ if (skipSameRoute && route.transition.from === route.name) {
817
+ return;
818
+ }
819
+ /* v8 ignore start */
820
+ if (lastHandledRoute === route || !previousRoute) {
821
+ return;
822
+ }
823
+ /* v8 ignore stop */
824
+ lastHandledRoute = route;
825
+ handler({ route, previousRoute });
826
+ });
827
+ }
828
+
453
829
  class RouteMatch {
454
830
  routeMatch = input.required(...(ngDevMode ? [{ debugName: "routeMatch" }] : /* istanbul ignore next */ []));
455
831
  templateRef = inject(TemplateRef);
@@ -752,5 +1128,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
752
1128
  * Generated bundle index. Do not edit.
753
1129
  */
754
1130
 
755
- export { NAVIGATOR, NavigationAnnouncer, ROUTE, ROUTER, RealLink, RealLinkActive, RouteMatch, RouteNotFound, RouteSelf, RouteView, RouterErrorBoundary, injectIsActiveRoute, injectNavigator, injectRoute, injectRouteNode, injectRouteUtils, injectRouter, injectRouterTransition, provideRealRouter, sourceToSignal };
1131
+ export { NAVIGATOR, NavigationAnnouncer, ROUTE, ROUTER, RealLink, RealLinkActive, RouteMatch, RouteNotFound, RouteSelf, RouteView, RouterErrorBoundary, injectIsActiveRoute, injectNavigator, injectRoute, injectRouteEnter, injectRouteExit, injectRouteNode, injectRouteUtils, injectRouter, injectRouterTransition, provideRealRouter, sourceToSignal };
756
1132
  //# sourceMappingURL=real-router-angular.mjs.map