@real-router/vue 0.8.0 → 0.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.
@@ -0,0 +1,120 @@
1
+ import { watch } from "vue";
2
+
3
+ import { useRoute } from "./useRoute";
4
+
5
+ import type { State } from "@real-router/core";
6
+
7
+ export interface RouteEnterContext {
8
+ /** The route that was just activated. */
9
+ route: State;
10
+ /** The route that was active immediately before this navigation. */
11
+ previousRoute: State;
12
+ }
13
+
14
+ export type RouteEnterHandler = (context: RouteEnterContext) => void;
15
+
16
+ export interface UseRouteEnterOptions {
17
+ /**
18
+ * Skip the handler when `route.name === previousRoute.name`
19
+ * (sort/filter/query-only navigations on the same route). Default:
20
+ * `true`. Symmetric with `useRouteExit`'s same-name option.
21
+ */
22
+ skipSameRoute?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Fire `handler` once when the component mounts as a result of a
27
+ * navigation. Mirror of `useRouteExit` for the entry side.
28
+ *
29
+ * What this composable covers that an ad-hoc `watch` + `useRoute()`
30
+ * doesn't:
31
+ *
32
+ * - **Skip-initial**: `watch` (with default `immediate: false`) plus the
33
+ * explicit `route.transition.from` guard ensures the handler doesn't
34
+ * fire on the very first state committed by `router.start()`.
35
+ * - **Same-route skip** (default): handler is skipped when
36
+ * `route.transition.from === route.name`. Sort/filter/query-only
37
+ * navigations re-trigger the watcher, but they are not "entries" in
38
+ * the animation / analytics sense. Opt out with
39
+ * `skipSameRoute: false`.
40
+ * - **Mount-time `route` / `previousRoute` snapshot**: handler receives
41
+ * the values that were live at the moment of the new state, not the
42
+ * latest ones (which may have moved on if the user navigated again
43
+ * before the watcher drained).
44
+ *
45
+ * **Handler reactivity (Vue):** Vue composables run **once** during
46
+ * `setup()`; `handler` is captured in closure at the call site. To vary
47
+ * behavior over time, read refs/computeds inside the handler body.
48
+ *
49
+ * @example Direction-aware entry animation
50
+ * ```ts
51
+ * useRouteEnter(({ route }) => {
52
+ * const direction = route.context.browser?.direction;
53
+ * ref.value?.classList.add(
54
+ * direction === "back" ? "slide-from-left" : "slide-from-right",
55
+ * );
56
+ * });
57
+ * ```
58
+ *
59
+ * @example Analytics page-enter event (skip-initial built-in)
60
+ * ```ts
61
+ * useRouteEnter(({ route, previousRoute }) => {
62
+ * analytics.track("page_enter", {
63
+ * route: route.name,
64
+ * from: previousRoute.name,
65
+ * });
66
+ * });
67
+ * ```
68
+ *
69
+ * @example Reading rich transition metadata via `route.transition`
70
+ * ```ts
71
+ * useRouteEnter(({ route }) => {
72
+ * if (route.transition.redirected) {
73
+ * showToast(`Redirected from ${route.transition.from}`);
74
+ * }
75
+ * });
76
+ * ```
77
+ */
78
+ export function useRouteEnter(
79
+ handler: RouteEnterHandler,
80
+ options?: UseRouteEnterOptions,
81
+ ): void {
82
+ const { route, previousRoute } = useRoute();
83
+ const skipSameRoute = options?.skipSameRoute ?? true;
84
+ let lastHandledRoute: State | null = null;
85
+
86
+ watch(route, (newRoute) => {
87
+ const prev = previousRoute.value;
88
+
89
+ // Early-exit guards, top-down:
90
+ //
91
+ // - **Skip-initial**: `!transition.from` catches the first commit
92
+ // from `router.start()`. Vue's `watch` (default `immediate: false`)
93
+ // does not fire on the initial state — kept for parity with
94
+ // React/Preact and v8-ignored.
95
+ // - **Skip-same-route**: query-only navigations have
96
+ // `transition.from === route.name`. Opt-out via
97
+ // `skipSameRoute: false`.
98
+ // - **Defensive dedupe + missing `previousRoute`**: same `route`
99
+ // ref between watcher activations is unexpected on Vue (driven
100
+ // off ref identity); `!prev` is unreachable once
101
+ // `transition.from` is set (core populates them together). Both
102
+ // kept for parity with React; v8-ignored.
103
+ /* v8 ignore start */
104
+ if (!newRoute.transition.from) {
105
+ return;
106
+ }
107
+ /* v8 ignore stop */
108
+ if (skipSameRoute && newRoute.transition.from === newRoute.name) {
109
+ return;
110
+ }
111
+ /* v8 ignore start */
112
+ if (lastHandledRoute === newRoute || !prev) {
113
+ return;
114
+ }
115
+ /* v8 ignore stop */
116
+
117
+ lastHandledRoute = newRoute;
118
+ handler({ route: newRoute, previousRoute: prev });
119
+ });
120
+ }
@@ -0,0 +1,116 @@
1
+ import { onScopeDispose } from "vue";
2
+
3
+ import { useRouter } from "./useRouter";
4
+
5
+ import type { State } from "@real-router/core";
6
+
7
+ export interface RouteExitContext {
8
+ /** The route being left. */
9
+ route: State;
10
+ /** The route being navigated to. */
11
+ nextRoute: State;
12
+ /**
13
+ * AbortSignal that fires when this navigation is superseded by a later
14
+ * one (rapid clicks). Already filtered: when the handler runs,
15
+ * `signal.aborted` is guaranteed to be `false`. Use
16
+ * `signal.addEventListener("abort", cleanup, { once: true })` for
17
+ * cleanup that must run on cancellation.
18
+ */
19
+ signal: AbortSignal;
20
+ }
21
+
22
+ export interface UseRouteExitOptions {
23
+ /**
24
+ * Skip the handler when `route.name === nextRoute.name`
25
+ * (sort/filter/query-only navigations on the same route). Default:
26
+ * `true`.
27
+ */
28
+ skipSameRoute?: boolean;
29
+ }
30
+
31
+ export type RouteExitHandler = (
32
+ context: RouteExitContext,
33
+ ) => void | Promise<void>;
34
+
35
+ /**
36
+ * Subscribe to the router's leave-window with the universal guards baked
37
+ * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
38
+ * boilerplate every time:
39
+ *
40
+ * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
41
+ * when the handler would run (rapid navigation superseded a slower
42
+ * one), the handler is skipped entirely.
43
+ * - **Same-route skip**: by default, `route.name === nextRoute.name`
44
+ * short-circuits the handler — query-only navigations skip the work.
45
+ * Opt out with `skipSameRoute: false`.
46
+ *
47
+ * Cleanup is bound to the component's effect scope via `onScopeDispose`.
48
+ *
49
+ * If the handler returns a Promise, the router blocks on it. If the
50
+ * Promise resolves, navigation proceeds. If it rejects, the router emits
51
+ * `TRANSITION_CANCELLED`.
52
+ *
53
+ * **Handler reactivity (Vue):** Vue composables run **once** during
54
+ * `setup()`; `handler` is captured in closure at the call site. To vary
55
+ * behavior over time, read refs/computeds inside the handler body — do
56
+ * not rely on swapping the handler reference.
57
+ *
58
+ * @example Animation
59
+ * ```ts
60
+ * const ref = useTemplateRef<HTMLDivElement>("box");
61
+ *
62
+ * useRouteExit(async ({ signal }) => {
63
+ * const el = ref.value;
64
+ * if (!el) return;
65
+ * el.classList.add("fade-out");
66
+ * const cleanup = () => el.classList.remove("fade-out");
67
+ * signal.addEventListener("abort", cleanup, { once: true });
68
+ * try {
69
+ * el.getBoundingClientRect();
70
+ * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
71
+ * } finally {
72
+ * cleanup();
73
+ * }
74
+ * });
75
+ * ```
76
+ *
77
+ * @example Auto-save form draft
78
+ * ```ts
79
+ * useRouteExit(async ({ signal }) => {
80
+ * if (formState.value.dirty) {
81
+ * await api.saveDraft(formState.value, { signal });
82
+ * }
83
+ * });
84
+ * ```
85
+ *
86
+ * @example Reading rich transition metadata via `nextRoute.transition`
87
+ * ```ts
88
+ * useRouteExit(({ route, nextRoute }) => {
89
+ * if (nextRoute.transition.segments.deactivated.includes("products")) {
90
+ * productCache.clear();
91
+ * }
92
+ * if (nextRoute.transition.redirected) return;
93
+ * });
94
+ * ```
95
+ */
96
+ export function useRouteExit(
97
+ handler: RouteExitHandler,
98
+ options?: UseRouteExitOptions,
99
+ ): void {
100
+ const router = useRouter();
101
+ const skipSameRoute = options?.skipSameRoute ?? true;
102
+
103
+ const off = router.subscribeLeave(({ route, nextRoute, signal }) => {
104
+ if (skipSameRoute && route.name === nextRoute.name) {
105
+ return;
106
+ }
107
+
108
+ if (signal.aborted) {
109
+ return;
110
+ }
111
+
112
+ return handler({ route, nextRoute, signal });
113
+ });
114
+
115
+ onScopeDispose(off);
116
+ }
package/src/index.ts CHANGED
@@ -21,6 +21,10 @@ export { useRouteNode } from "./composables/useRouteNode";
21
21
 
22
22
  export { useRouterTransition } from "./composables/useRouterTransition";
23
23
 
24
+ export { useRouteExit } from "./composables/useRouteExit";
25
+
26
+ export { useRouteEnter } from "./composables/useRouteEnter";
27
+
24
28
  // Plugin
25
29
  export { createRouterPlugin } from "./createRouterPlugin";
26
30
 
@@ -42,6 +46,18 @@ export type {
42
46
  RouteViewNotFoundProps,
43
47
  } from "./components/RouteView";
44
48
 
49
+ export type {
50
+ RouteExitContext,
51
+ RouteExitHandler,
52
+ UseRouteExitOptions,
53
+ } from "./composables/useRouteExit";
54
+
55
+ export type {
56
+ RouteEnterContext,
57
+ RouteEnterHandler,
58
+ UseRouteEnterOptions,
59
+ } from "./composables/useRouteEnter";
60
+
45
61
  export type { Navigator } from "@real-router/core";
46
62
 
47
63
  export type { RouterTransitionSnapshot } from "@real-router/sources";