@real-router/vue 0.7.0 → 0.9.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.
@@ -2,12 +2,18 @@ import { UNKNOWN_ROUTE } from "@real-router/core";
2
2
  import { startsWithSegment } from "@real-router/route-utils";
3
3
  import { Fragment, isVNode } from "vue";
4
4
 
5
- import { Match, NotFound } from "./components";
5
+ import { Match, NotFound, Self } from "./components";
6
6
 
7
7
  import type { VNode } from "vue";
8
8
 
9
9
  type FallbackType = VNode | (() => VNode) | undefined;
10
10
 
11
+ interface FallbackSlots {
12
+ selfVNode: VNode | null;
13
+ selfFallback: FallbackType;
14
+ notFoundChildren: unknown;
15
+ }
16
+
11
17
  function isSegmentMatch(
12
18
  routeName: string,
13
19
  fullSegmentName: string,
@@ -46,7 +52,11 @@ export function collectElements(children: unknown, result: VNode[]): void {
46
52
  const vnodes = normalizeChildren(children);
47
53
 
48
54
  for (const child of vnodes) {
49
- if (child.type === Match || child.type === NotFound) {
55
+ if (
56
+ child.type === Match ||
57
+ child.type === Self ||
58
+ child.type === NotFound
59
+ ) {
50
60
  result.push(child);
51
61
  } else if (child.type === Fragment) {
52
62
  collectElements(child.children, result);
@@ -54,6 +64,71 @@ export function collectElements(children: unknown, result: VNode[]): void {
54
64
  }
55
65
  }
56
66
 
67
+ function recordFallback(child: VNode, slots: FallbackSlots): boolean {
68
+ if (child.type === NotFound) {
69
+ slots.notFoundChildren = child.children;
70
+
71
+ return true;
72
+ }
73
+
74
+ if (child.type === Self) {
75
+ if (slots.selfVNode === null) {
76
+ slots.selfVNode = child;
77
+ const props = child.props as { fallback?: FallbackType } | null;
78
+
79
+ slots.selfFallback = props?.fallback;
80
+ }
81
+
82
+ return true;
83
+ }
84
+
85
+ return false;
86
+ }
87
+
88
+ function evaluateMatch(
89
+ child: VNode,
90
+ routeName: string,
91
+ nodeName: string,
92
+ ): { isActive: boolean; fallback: FallbackType } {
93
+ const props = child.props as {
94
+ segment: string;
95
+ exact?: boolean;
96
+ fallback?: FallbackType;
97
+ } | null;
98
+ const segment = props?.segment ?? "";
99
+ const exact = props?.exact ?? false;
100
+ const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;
101
+ const isActive = isSegmentMatch(routeName, fullSegmentName, exact);
102
+
103
+ return { isActive, fallback: props?.fallback };
104
+ }
105
+
106
+ function appendFallback(
107
+ rendered: VNode[],
108
+ routeName: string,
109
+ nodeName: string,
110
+ slots: FallbackSlots,
111
+ elements: VNode[],
112
+ ): FallbackType {
113
+ if (slots.selfVNode !== null && routeName === nodeName) {
114
+ rendered.push(slots.selfVNode);
115
+
116
+ return slots.selfFallback;
117
+ }
118
+
119
+ if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {
120
+ const nfElements = elements.filter((element) => element.type === NotFound);
121
+ /* v8 ignore next 3 */
122
+ const lastNf = nfElements.at(-1);
123
+
124
+ if (lastNf) {
125
+ rendered.push(lastNf);
126
+ }
127
+ }
128
+
129
+ return undefined;
130
+ }
131
+
57
132
  export function buildRenderList(
58
133
  elements: VNode[],
59
134
  routeName: string,
@@ -63,47 +138,35 @@ export function buildRenderList(
63
138
  activeMatchFound: boolean;
64
139
  fallback?: FallbackType;
65
140
  } {
66
- let notFoundChildren: unknown = null;
141
+ const slots: FallbackSlots = {
142
+ selfVNode: null,
143
+ selfFallback: undefined,
144
+ notFoundChildren: null,
145
+ };
67
146
  let activeMatchFound = false;
68
147
  let fallback: FallbackType = undefined;
69
148
  const rendered: VNode[] = [];
70
149
 
71
150
  for (const child of elements) {
72
- if (child.type === NotFound) {
73
- notFoundChildren = child.children;
151
+ if (recordFallback(child, slots)) {
74
152
  continue;
75
153
  }
76
154
 
77
- const props = child.props as {
78
- segment: string;
79
- exact?: boolean;
80
- fallback?: FallbackType;
81
- } | null;
82
- const segment = props?.segment ?? "";
83
- const exact = props?.exact ?? false;
84
- const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;
85
- const isActive =
86
- !activeMatchFound && isSegmentMatch(routeName, fullSegmentName, exact);
87
-
88
- if (isActive) {
155
+ if (activeMatchFound) {
156
+ continue;
157
+ }
158
+
159
+ const result = evaluateMatch(child, routeName, nodeName);
160
+
161
+ if (result.isActive) {
89
162
  activeMatchFound = true;
90
- fallback = props?.fallback;
163
+ fallback = result.fallback;
91
164
  rendered.push(child);
92
165
  }
93
166
  }
94
167
 
95
- if (
96
- !activeMatchFound &&
97
- routeName === UNKNOWN_ROUTE &&
98
- notFoundChildren !== null
99
- ) {
100
- const nfElements = elements.filter((element) => element.type === NotFound);
101
- /* v8 ignore next 3 */
102
- const lastNf = nfElements.at(-1);
103
-
104
- if (lastNf) {
105
- rendered.push(lastNf);
106
- }
168
+ if (!activeMatchFound) {
169
+ fallback = appendFallback(rendered, routeName, nodeName, slots, elements);
107
170
  }
108
171
 
109
172
  return { rendered, activeMatchFound, fallback };
@@ -3,5 +3,6 @@ export { RouteView } from "./RouteView";
3
3
  export type {
4
4
  RouteViewProps,
5
5
  RouteViewMatchProps,
6
+ RouteViewSelfProps,
6
7
  RouteViewNotFoundProps,
7
8
  } from "./RouteView";
@@ -12,4 +12,9 @@ export interface MatchProps {
12
12
  readonly keepAlive?: boolean;
13
13
  }
14
14
 
15
+ export interface SelfProps {
16
+ /** Fallback content while children are suspended. */
17
+ readonly fallback?: VNode | (() => VNode);
18
+ }
19
+
15
20
  export type NotFoundProps = Record<string, never>;
@@ -0,0 +1,124 @@
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
+ // - **Defensive + skip-initial**: `route` may be undefined during
92
+ // SSR / pre-start hydration; `!transition.from` would catch the
93
+ // first commit from `router.start()`. Vue's `watch` (default
94
+ // `immediate: false`) does not fire on the initial state, so
95
+ // both are unreachable in Vue (covered by React/Preact tests).
96
+ // - **Skip-same-route**: query-only navigations have
97
+ // `transition.from === route.name`. Opt-out via
98
+ // `skipSameRoute: false`.
99
+ // - **Defensive dedupe + missing `previousRoute`**: same `route`
100
+ // ref between watcher activations is unexpected on Vue (driven
101
+ // off ref identity); `!prev` is unreachable once
102
+ // `transition.from` is set (core populates them together). Both
103
+ // kept for parity with React; v8-ignored.
104
+ /* v8 ignore start */
105
+ if (!newRoute) {
106
+ return;
107
+ }
108
+ if (!newRoute.transition.from) {
109
+ return;
110
+ }
111
+ /* v8 ignore stop */
112
+ if (skipSameRoute && newRoute.transition.from === newRoute.name) {
113
+ return;
114
+ }
115
+ /* v8 ignore start */
116
+ if (lastHandledRoute === newRoute || !prev) {
117
+ return;
118
+ }
119
+ /* v8 ignore stop */
120
+
121
+ lastHandledRoute = newRoute;
122
+ handler({ route: newRoute, previousRoute: prev });
123
+ });
124
+ }
@@ -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";