All files use.ts

97.32% Statements 109/112
96.77% Branches 30/31
100% Functions 12/12
97.32% Lines 109/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429  1x               1x                                   1x 1x 1x   1x 1x   1x 1x 1x   105x 105x 105x 3x 3x 3x 3x 102x 102x   8x 8x 8x 5x 5x   3x 3x 1x 1x       1x 1x   3x 3x 3x 3x                                                             1x 1x 1x                                                             1x 1x 1x           62x   62x 62x 53x 53x     9x 9x 9x                                                                   1x 26x 26x                                                                   1x 36x 36x                                                             1x 67x   67x   67x 67x   67x 67x 67x 67x   67x 67x   67x 67x 67x 67x 67x 67x 67x 67x 67x   67x 35x 33x 33x 33x 67x   67x 67x                                                               1x 32x   32x 29x 29x 29x 29x   32x 32x                                                     1x 3x 3x                                               1x 4x 4x 7x 7x 4x 4x 1x 1x                                                               1x 24x   24x 37x 24x 24x  
import type { Route, Router, RouterLinkProps } from '@esmx/router';
import {
    computed,
    getCurrentInstance,
    inject,
    onBeforeUnmount,
    provide,
    ref
} from 'vue';
import {
    createDependentProxy,
    createSymbolProperty,
    defineRouterProperties,
    isVue2
} from './util';
 
export interface VueInstance {
    $parent?: VueInstance | null;
    $root?: VueInstance | null;
    $children?: VueInstance[] | null;
}
 
interface RouterContext {
    router: Router;
    route: Route;
}
 
const ROUTER_CONTEXT_KEY = Symbol('router-context');
const ROUTER_INJECT_KEY = Symbol('router-inject');
const ROUTER_VIEW_DEPTH_KEY = Symbol('router-view-depth');
 
const routerContextProperty =
    createSymbolProperty<RouterContext>(ROUTER_CONTEXT_KEY);
 
const routerViewDepthProperty = createSymbolProperty<number>(
    ROUTER_VIEW_DEPTH_KEY
);
 
function getCurrentProxy(): VueInstance {
    const instance = getCurrentInstance();
    if (!instance || !instance.proxy) {
        throw new Error(
            '[@esmx/router-vue] Must be used within setup() or other composition functions'
        );
    }
    return instance.proxy;
}
 
function findRouterContext(vm: VueInstance): RouterContext {
    let context = routerContextProperty.get(vm);
    if (context) {
        return context;
    }
 
    let current = vm.$parent;
    while (current) {
        context = routerContextProperty.get(current);
        if (context) {
            routerContextProperty.set(vm, context);
            return context;
        }
        current = current.$parent;
    }
 
    throw new Error(
        '[@esmx/router-vue] Router context not found. Please ensure useProvideRouter() is called in a parent component.'
    );
}
 
/**
 * Get router instance from a Vue component instance.
 * This is a lower-level function used internally by useRouter().
 * Use this in Options API, use useRouter() in Composition API.
 *
 * @param instance - Vue component instance
 * @returns Router instance
 * @throws {Error} If router context is not found
 *
 * @example
 * ```typescript
 * // Options API usage
 * import { defineComponent } from 'vue';
 * import { getRouter } from '@esmx/router-vue';
 *
 * export default defineComponent({
 *   mounted() {
 *     const router = getRouter(this);
 *     router.push('/dashboard');
 *   },
 *   methods: {
 *     handleNavigation() {
 *       const router = getRouter(this);
 *       router.replace('/profile');
 *     }
 *   }
 * });
 * ```
 */
export function getRouter(instance: VueInstance): Router {
    return findRouterContext(instance).router;
}
 
/**
 * Get current route from a Vue component instance.
 * This is a lower-level function used internally by useRoute().
 * Use this in Options API, use useRoute() in Composition API.
 *
 * @param instance - Vue component instance
 * @returns Current route object
 * @throws {Error} If router context is not found
 *
 * @example
 * ```typescript
 * // Options API usage
 * import { defineComponent } from 'vue';
 * import { getRoute } from '@esmx/router-vue';
 *
 * export default defineComponent({
 *   computed: {
 *     routeInfo() {
 *       const route = getRoute(this);
 *       return {
 *         path: route.path,
 *         params: route.params,
 *         query: route.query
 *       };
 *     }
 *   }
 * });
 * ```
 */
export function getRoute(instance: VueInstance): Route {
    return findRouterContext(instance).route;
}
 
/**
 * Get router context using the optimal method available.
 * First tries provide/inject (works in setup), then falls back to hierarchy traversal.
 */
function useRouterContext(): RouterContext {
    // First try to get context from provide/inject (works in setup)
    const injectedContext = inject<RouterContext>(ROUTER_INJECT_KEY);
    if (injectedContext) {
        return injectedContext;
    }
 
    // Fallback to component hierarchy traversal (works after mount)
    const proxy = getCurrentProxy();
    return findRouterContext(proxy);
}
 
/**
 * Get the router instance in a Vue component.
 * Must be called within setup() or other composition functions.
 * Use this in Composition API, use getRouter() in Options API.
 *
 * @returns Router instance for navigation and route management
 * @throws {Error} If called outside setup() or router context not found
 *
 * @example
 * ```vue
 * <script setup lang="ts">
 * import { useRouter } from '@esmx/router-vue';
 *
 * const router = useRouter();
 *
 * const navigateToHome = () => {
 *   router.push('/home');
 * };
 *
 * const goBack = () => {
 *   router.back();
 * };
 *
 * const navigateWithQuery = () => {
 *   router.push({
 *     path: '/search',
 *     query: { q: 'vue router', page: '1' }
 *   });
 * };
 * </script>
 * ```
 */
export function useRouter(): Router {
    return useRouterContext().router;
}
 
/**
 * Get the current route information in a Vue component.
 * Returns a reactive reference that automatically updates when the route changes.
 * Must be called within setup() or other composition functions.
 * Use this in Composition API, use getRoute() in Options API.
 *
 * @returns Current route object with path, params, query, etc.
 * @throws {Error} If called outside setup() or router context not found
 *
 * @example
 * ```vue
 * <template>
 *   <div>
 *     <h1>{{ route.meta?.title || 'Page' }}</h1>
 *     <p>Path: {{ route.path }}</p>
 *     <p>Params: {{ JSON.stringify(route.params) }}</p>
 *     <p>Query: {{ JSON.stringify(route.query) }}</p>
 *   </div>
 * </template>
 *
 * <script setup lang="ts">
 * import { useRoute } from '@esmx/router-vue';
 * import { watch } from 'vue';
 *
 * const route = useRoute();
 *
 * watch(() => route.path, (newPath) => {
 *   console.log('Route changed to:', newPath);
 * });
 * </script>
 * ```
 */
export function useRoute(): Route {
    return useRouterContext().route;
}
 
/**
 * Provide router context to child components.
 * This must be called in a parent component to make the router available
 * to child components via useRouter() and useRoute().
 *
 * @param router - Router instance to provide to child components
 * @throws {Error} If called outside setup()
 *
 * @example
 * ```typescript
 * // Vue 3 usage
 * import { createApp } from 'vue';
 * import { Router } from '@esmx/router';
 * import { useProvideRouter } from '@esmx/router-vue';
 *
 * const routes = [
 *   { path: '/', component: () => import('./Home.vue') },
 *   { path: '/about', component: () => import('./About.vue') }
 * ];
 *
 * const router = new Router({ routes });
 * const app = createApp({
 *   setup() {
 *     useProvideRouter(router);
 *   }
 * });
 * app.mount('#app');
 * ```
 */
export function useProvideRouter(router: Router): void {
    const proxy = getCurrentProxy();
 
    const dep = ref(0);
 
    const proxiedRouter = createDependentProxy(router, dep);
    const proxiedRoute = createDependentProxy(router.route, dep);
 
    const context: RouterContext = {
        router: proxiedRouter,
        route: proxiedRoute
    };
 
    provide(ROUTER_INJECT_KEY, context);
    routerContextProperty.set(proxy, context);
 
    if (!isVue2) {
        const app = getCurrentInstance()!.appContext.app;
        defineRouterProperties(
            app.config.globalProperties,
            () => proxiedRouter,
            () => proxiedRoute,
            true
        );
    }
 
    const unwatch = router.afterEach((to: Route) => {
        if (router.route === to) {
            to.syncTo(proxiedRoute);
            dep.value++;
        }
    });
 
    onBeforeUnmount(unwatch);
}
 
/**
 * Get the current RouterView depth in nested routing scenarios.
 * Returns the depth of the current RouterView component in the component tree.
 * Useful for advanced routing scenarios where you need to know the nesting level.
 *
 * @param isRender - Whether this is used in a RouterView component that needs to provide depth for children (default: false)
 * @returns Current RouterView depth (0 for root level, 1 for first nested level, etc.)
 * @throws {Error} If called outside setup()
 *
 * @example
 * ```vue
 * <template>
 *   <div>
 *     <p>Current RouterView depth: {{ depth }}</p>
 *     <RouterView />
 *   </div>
 * </template>
 *
 * <script setup lang="ts">
 * import { useRouterViewDepth } from '@esmx/router-vue';
 *
 * // Get current depth without providing for children
 * const depth = useRouterViewDepth();
 * console.log('Current RouterView depth:', depth); // 0, 1, 2, etc.
 *
 * // Get current depth and provide depth + 1 for children (used in RouterView component)
 * const depth = useRouterViewDepth(true);
 * </script>
 * ```
 */
export function _useRouterViewDepth(isRender?: boolean): number {
    const depth = inject(ROUTER_VIEW_DEPTH_KEY, 0);
 
    if (isRender) {
        provide(ROUTER_VIEW_DEPTH_KEY, depth + 1);
        const proxy = getCurrentProxy();
        routerViewDepthProperty.set(proxy, depth + 1);
    }
 
    return depth;
}
/**
 * Get the current RouterView depth in nested routing scenarios.
 * Returns the depth of the current RouterView component in the component tree.
 * Useful for advanced routing scenarios where you need to know the nesting level.
 *
 * @returns Current RouterView depth (0 for root level, 1 for first nested level, etc.)
 * @throws {Error} If called outside setup()
 *
 * @example
 * ```vue
 * <template>
 *   <div>
 *     <p>Current RouterView depth: {{ depth }}</p>
 *     <RouterView />
 *   </div>
 * </template>
 *
 * <script setup lang="ts">
 * import { useRouterViewDepth } from '@esmx/router-vue';
 *
 * // Get current depth without providing for children
 * const depth = useRouterViewDepth();
 * console.log('Current RouterView depth:', depth); // 0, 1, 2, etc.
 * </script>
 * ```
 */
export function useRouterViewDepth(): number {
    return _useRouterViewDepth();
}
 
/**
 * Get the current RouterView depth in nested routing scenarios.
 * Returns the depth of the current RouterView component in the component tree.
 * Useful for advanced routing scenarios where you need to know the nesting level.
 *
 * @param instance - Vue component instance to start from
 * @returns Current RouterView depth (0 for root level, 1 for first nested level, etc.)
 *
 * @example
 * ```typescript
 * // Options API usage
 * import { defineComponent } from 'vue';
 * import { getRouterViewDepth } from '@esmx/router-vue';
 *
 * export default defineComponent({
 *   mounted() {
 *     const depth = getRouterViewDepth(this);
 *     console.log('Current RouterView depth:', depth); // 0, 1, 2, etc.
 *   }
 * });
 * ```
 */
export function getRouterViewDepth(instance: VueInstance): number {
    let current = instance.$parent;
    while (current) {
        const value = routerViewDepthProperty.get(current);
        if (typeof value === 'number') return value;
        current = current.$parent;
    }
    return 0;
}
 
/**
 * Create reactive link helpers for navigation elements.
 * Returns computed properties for link attributes, classes, and event handlers.
 *
 * @param props - RouterLink properties configuration
 * @returns Computed link resolver with attributes and event handlers
 *
 * @example
 * ```vue
 * <template>
 *   <a
 *     v-bind="link.attributes"
 *     v-on="link.createEventHandlers()"
 *     :class="{ active: link.isActive }"
 *   >
 *     Home
 *   </a>
 * </template>
 *
 * <script setup lang="ts">
 * import { useLink } from '@esmx/router-vue';
 *
 * const link = useLink({
 *   to: '/home',
 *   type: 'push',
 *   exact: 'include'
 * }).value;
 * </script>
 * ```
 */
export function useLink(props: RouterLinkProps) {
    const router = useRouter();
 
    return computed(() => {
        return router.resolveLink(props);
    });
}