All files router-link.ts

100% Statements 166/166
100% Branches 57/57
100% Functions 9/9
100% Lines 166/166

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                  2x 2x 2x 2x 2x       93x 93x 3x 3x       3x 3x 3x 93x 93x         93x 93x 93x 93x 93x 93x 93x 93x                     31x 31x 31x 26x 26x 26x   31x   31x 31x         24x 24x 24x 24x 24x 24x   24x 24x 16x 15x 24x 1x 1x 24x 1x 1x 24x 1x 1x 24x 4x 4x 3x 1x 2x 1x 4x 4x 24x 1x 1x 1x         118x 118x 118x 118x 118x 118x 31x 24x 23x 31x 118x         93x 93x 93x 93x 93x 93x 93x 93x   93x     93x 93x 17x 17x 93x 14x 14x   93x 93x 93x 93x     93x 7x 7x     93x 93x 7x 7x 93x 6x 6x 93x 10x 10x   93x 93x         93x 93x 93x 93x 93x 93x 93x 25x 25x   25x 139x 139x 8x 8x 8x 25x   25x 25x 93x                 2x 93x 93x 93x 93x 93x 93x   93x 93x 93x   93x 93x 93x 93x 93x 93x 93x 93x   93x 93x 93x 93x 93x 93x 93x   93x   93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x  
import type { Router } from './router';
import type {
    RouterLinkAttributes,
    RouterLinkProps,
    RouterLinkResolved,
    RouterLinkType
} from './types';
 
// Constants definition
const CSS_CLASSES = {
    BASE: 'router-link',
    ACTIVE: 'router-link-active',
    EXACT_ACTIVE: 'router-link-exact-active'
} satisfies Record<string, string>;
/**
 * Normalize navigation type with backward compatibility for deprecated replace property
 */
function normalizeNavigationType(props: RouterLinkProps): RouterLinkType {
    if (props.replace) {
        console.warn(
            '[RouterLink] The `replace` property is deprecated and will be removed in a future version.\n' +
                'Please use `type="replace"` instead.\n' +
                'Before: <RouterLink replace={true} />\n' +
                'After:  <RouterLink type="replace" />'
        );
        return 'replace';
    }
    return props.type || 'push';
}
 
/**
 * Get event type list - normalize and validate event types
 */
function getEventTypeList(eventType: unknown | unknown[]): string[] {
    const events = Array.isArray(eventType) ? eventType : [eventType];
    const validEvents = events
        .filter((type): type is string => typeof type === 'string')
        .map((type) => type.trim())
        .filter(Boolean);
    return validEvents.length ? validEvents : ['click'];
}
 
/**
 * Navigation event handler called before navigation - determines if the router should handle the navigation
 *
 * Returns false: Let browser handle default behavior (normal link navigation)
 * Returns true: Router takes over navigation, prevents default browser behavior
 *
 * This function intelligently decides when to let the browser handle clicks
 * (like Ctrl+click for new tabs) vs when to use SPA routing
 */
function shouldHandleNavigation(e: Event): boolean {
    if (e.defaultPrevented) return false;
    if (e instanceof MouseEvent) {
        if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return false;
        if (e.button !== undefined && e.button !== 0) return false;
    }
 
    e.preventDefault?.();
 
    return true;
}
 
/**
 * Execute route navigation
 */
async function executeNavigation(
    router: Router,
    props: RouterLinkProps,
    linkType: RouterLinkType
): Promise<void> {
    const { to, layerOptions } = props;
 
    switch (linkType) {
        case 'push':
            await router.push(to);
            break;
        case 'replace':
            await router.replace(to);
            break;
        case 'pushWindow':
            await router.pushWindow(to);
            break;
        case 'replaceWindow':
            await router.replaceWindow(to);
            break;
        case 'pushLayer':
            await router.pushLayer(
                layerOptions
                    ? typeof to === 'string'
                        ? { path: to, layer: layerOptions }
                        : { ...to, layer: layerOptions }
                    : to
            );
            break;
        default:
            await router.push(to);
    }
}
 
/**
 * Create navigation function
 */
function createNavigateFunction(
    router: Router,
    props: RouterLinkProps,
    navigationType: RouterLinkType
): RouterLinkResolved['navigate'] {
    return async (e: Event): Promise<void> => {
        if (shouldHandleNavigation(e)) {
            await executeNavigation(router, props, navigationType);
        }
    };
}
 
/**
 * Compute HTML attributes
 */
function computeAttributes(
    href: string,
    navigationType: RouterLinkType,
    isExternal: boolean,
    isActive: boolean,
    isExactActive: boolean,
    activeClass?: string
): RouterLinkAttributes {
    // Only pushWindow opens in a new window, replaceWindow replaces current window
    const isNewWindow = navigationType === 'pushWindow';
 
    // Build CSS classes
    const classes: string[] = [CSS_CLASSES.BASE];
    if (isActive) {
        classes.push(activeClass || CSS_CLASSES.ACTIVE);
    }
    if (isExactActive) {
        classes.push(CSS_CLASSES.EXACT_ACTIVE);
    }
 
    const attributes: RouterLinkAttributes = {
        href,
        class: classes.join(' ')
    };
 
    // Set target for new window
    if (isNewWindow) {
        attributes.target = '_blank';
    }
 
    // Build rel attribute
    const relParts: string[] = [];
    if (isNewWindow) {
        relParts.push('noopener', 'noreferrer');
    }
    if (isExternal) {
        relParts.push('external', 'nofollow');
    }
    if (relParts.length > 0) {
        attributes.rel = relParts.join(' ');
    }
 
    return attributes;
}
 
/**
 * Create event handlers generator function
 */
function createEventHandlersGenerator(
    router: Router,
    props: RouterLinkProps,
    navigationType: RouterLinkType,
    eventTypes: string[]
): RouterLinkResolved['createEventHandlers'] {
    return (format?: (eventType: string) => string) => {
        const handlers: Record<string, (e: Event) => Promise<void>> = {};
        const navigate = createNavigateFunction(router, props, navigationType);
 
        eventTypes.forEach((eventType) => {
            const eventName = format?.(eventType) ?? eventType.toLowerCase();
            handlers[eventName] = (event) => {
                props.beforeNavigate?.(event, eventType);
                return navigate(event);
            };
        });
 
        return handlers;
    };
}
 
/**
 * Framework-agnostic link resolver
 *
 * @param router Router instance
 * @param props Link configuration
 * @returns Resolution result
 */
export function createLinkResolver(
    router: Router,
    props: RouterLinkProps
): RouterLinkResolved {
    const route = router.resolve(props.to);
    const type = normalizeNavigationType(props);
    const href = route.url.href;
 
    const isActive = router.isRouteMatched(route, props.exact);
    const isExactActive = router.isRouteMatched(route, 'exact');
    const isExternal = route.url.origin !== router.route.url.origin;
 
    const attributes = computeAttributes(
        href,
        type,
        isExternal,
        isActive,
        isExactActive,
        props.activeClass
    );
 
    const eventTypes = getEventTypeList(props.event || 'click');
    const createEventHandlers = createEventHandlersGenerator(
        router,
        props,
        type,
        eventTypes
    );
 
    const navigate = createNavigateFunction(router, props, type);
 
    return {
        route,
        type,
        isActive,
        isExactActive,
        isExternal,
        tag: props.tag || 'a',
        attributes,
        navigate,
        createEventHandlers
    };
}