UNPKG

@nuxtjs/i18n

Version:

Internationalization for Nuxt

55 lines (54 loc) 1.56 kB
import { hasProtocol, parsePath, parseQuery } from "ufo"; import { assign, isString } from "@intlify/shared"; export function localePath(ctx, route, locale = ctx.getLocale()) { if (isString(route) && hasProtocol(route, { acceptRelative: true })) { return route; } try { return resolveRoute(ctx, route, locale).fullPath; } catch { return ""; } } export function localeRoute(ctx, route, locale = ctx.getLocale()) { try { return resolveRoute(ctx, route, locale); } catch { return; } } function normalizeRawLocation(route) { if (!isString(route)) { return assign({}, route); } if (route[0] === "/") { const { pathname: path, search, hash } = parsePath(route); return { path, query: parseQuery(search), hash }; } return { name: route }; } function resolveRoute(ctx, route, locale) { const normalized = normalizeRawLocation(route); const resolved = ctx.router.resolve(ctx.resolveLocalizedRouteObject(normalized, locale)); if (resolved.name) { return resolved; } return ctx.router.resolve(route); } export function switchLocalePath(ctx, locale, route = ctx.router.currentRoute.value) { const name = ctx.getRouteBaseName(route); if (!name) { return ""; } const routeCopy = { name, params: assign({}, route.params, ctx.getLocalizedDynamicParams(locale)), fullPath: route.fullPath, query: route.query, hash: route.hash, path: route.path, meta: route.meta }; const path = localePath(ctx, routeCopy, locale); return ctx.afterSwitchLocalePath(path, locale); }