Skip to content

Commit

Permalink
fix: fixes after code review
Browse files Browse the repository at this point in the history
  • Loading branch information
Renhor committed May 12, 2022
1 parent 744d009 commit 275aa9f
Show file tree
Hide file tree
Showing 13 changed files with 45 additions and 71 deletions.
6 changes: 0 additions & 6 deletions docs/content/en/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,12 @@ All [Vue I18n properties and methods](http://kazupon.github.io/vue-i18n/api/#vue

- **Arguments**:
- locale: (type: `string`)
- forcePrefix: (type: `boolean`)
- **Returns**: `string`

Returns path of the current route for specified `locale`.

If `forcePrefix` is set to `true`, it returns the path with the prefix. Useful for `prefix_and_default` strategy.
You can also set global behavior through option prefixAndDefaultRules.

See also [Basic usage - nuxt-link](../basic-usage#nuxt-link).

See more details about [prefixAndDefaultRules](../options-reference#prefixanddefaultrules).

See type definition for [Location](https://github.com/vuejs/vue-router/blob/f40139c27a9736efcbda69ec136cb00d8e00fa97/types/router.d.ts#L125).

### getRouteBaseName()
Expand Down
8 changes: 3 additions & 5 deletions docs/content/en/options-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,16 @@ Set this to `true` when using different domains for each locale. If enabled, no

Whether [custom paths](/routing#custom-paths) are extracted from page files using babel parser.

## `prefixAndDefaultRules`
## `prefixAndDefaultRule`

- type: `object`
- default: `{ routing: 'default', switchLocale: 'default' }`
- default: `'default'`

Modification of the standard behavior of the `prefix_and_default` strategy.

By setting the value `routing = 'prefix'` we are no longer being redirected from prefixed path.
By setting the value `prefixAndDefaultRule = 'prefix'` we are no longer being redirected from prefixed path.
If there is no prefix then the other routers will also have no prefix.

By setting the value `switchLocale = 'prefix'` the `switchLocalePath()` method adds a prefix to the current route.

## `pages`

- type: `object`
Expand Down
2 changes: 1 addition & 1 deletion docs/content/en/strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ With this strategy, all routes will have a locale prefix.

This strategy combines both previous strategies behaviours, meaning that you will get URLs with prefixes for every language, but URLs for the default language will also have a non-prefixed version (though the prefixed version will be preferred when `detectBrowserLanguage` is enabled.)

The behavior of the strategy can be modified, more - [prefixAndDefaultRules](../options-reference#prefixanddefaultrules)
The behavior of the strategy can be modified, more - [prefixAndDefaultRule](../options-reference#prefixanddefaultrule)

### Configuration

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
},
"scripts": {
"dev:basic": "nuxt -c ./test/fixture/basic/nuxt.config.js",
"dev:redirect": "nuxt -c ./test/fixture/disable-redirect/nuxt.config.js",
"dev:basic:generate": "nuxt generate -c ./test/fixture/basic/nuxt.config.js",
"dev:basic:start": "nuxt start -c ./test/fixture/basic/nuxt.config.js",
"start:dist": "jiti ./test/utils/http-server-internal.js --port 8080 -v dist",
Expand Down
5 changes: 1 addition & 4 deletions src/helpers/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ export const DEFAULT_OPTIONS = {
defaultDirection: 'ltr',
routesNameSeparator: '___',
defaultLocaleRouteNameSuffix: 'default',
prefixAndDefaultRules: {
switchLocale: 'default',
routing: 'default'
},
prefixAndDefaultRule: 'default',
sortRoutes: true,
strategy: STRATEGY_PREFIX_EXCEPT_DEFAULT,
lazy: false,
Expand Down
14 changes: 7 additions & 7 deletions src/templates/plugin.main.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
loadLanguageAsync,
resolveBaseUrl,
registerStore,
mergeAdditionalMessages
mergeAdditionalMessages, getHelpers
} from './plugin.utils'
// @ts-ignore
import { joinURL } from '~i18n-ufo'
Expand Down Expand Up @@ -154,8 +154,7 @@ export default async (context) => {

const isStaticGenerate = process.static && process.server
const isDifferentLocale = getLocaleFromRoute(route) !== newLocale
const isPrefixAndDefaultStrategy = options.strategy === Constants.STRATEGIES.PREFIX_AND_DEFAULT
const isDefaultLocale = newLocale === options.defaultLocale
const { isPrefixAndDefault, isDefaultLocale } = getHelpers(newLocale)

// Decide whether we should redirect to a different route.
if (
Expand All @@ -164,11 +163,12 @@ export default async (context) => {
options.strategy !== Constants.STRATEGIES.NO_PREFIX &&
// Skip if already on the new locale unless the strategy is "prefix_and_default" and this is the default
// locale, in which case we might still redirect as we prefer unprefixed route in this case, but let user a
// possibility to disable this behavior by switching disableDefaultRedirect option to true.
(isDifferentLocale || (isPrefixAndDefaultStrategy && isDefaultLocale))
// possibility to disable this behavior by switching prefixAndDefaultRule option to prefix.
(isDifferentLocale || (isPrefixAndDefault && isDefaultLocale && options.prefixAndDefaultRule === 'default'))
) {
const routePath = app.localePath(route.fullPath, newLocale)

// The current route could be 404 in which case attempt to find matching route using the full path since
// "switchLocalePath" can only find routes if the current route exists.
const routePath = app.switchLocalePath(newLocale) || app.localePath(route.fullPath, newLocale)
if (routePath && routePath !== route.fullPath && !routePath.startsWith('//')) {
redirectPath = routePath
}
Expand Down
31 changes: 9 additions & 22 deletions src/templates/plugin.routing.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import './middleware'
import Vue from 'vue'
import { Constants, nuxtOptions, options } from './options'
import { getDomainFromLocale } from './plugin.utils'
import { getDomainFromLocale, getHelpers } from './plugin.utils'
import { removeLocaleFromPath } from './utils-common'
// @ts-ignore
import { withoutTrailingSlash, withTrailingSlash } from '~i18n-ufo'
Expand Down Expand Up @@ -79,11 +79,11 @@ function resolveRoute (route, locale) {
hash: resolvedRoute.hash
}
} else {
const { isDefaultLocale, isPrefixAndDefault } = getHelpers(locale)
const { isDefaultLocale, isPrefixAndDefault, isPrefixExceptDefault } = getHelpers(locale)
// if route has a path defined but no name, resolve full route using the path
const isPrefixed =
// don't prefix default locale, if not forced
!(isDefaultLocale && isPrefixAndDefault && forceDefaultRoute) &&
!(isDefaultLocale && (isPrefixExceptDefault || (isPrefixAndDefault && forceDefaultRoute))) &&
// no prefix for any language
!(options.strategy === Constants.STRATEGIES.NO_PREFIX) &&
// no prefix for different domains
Expand Down Expand Up @@ -120,7 +120,7 @@ function resolveRoute (route, locale) {
* @this {import('../../types/internal').PluginProxy}
* @type {Vue['switchLocalePath']}
*/
function switchLocalePath (locale, forcePrefix = false) {
function switchLocalePath (locale) {
const name = this.getRouteBaseName()
if (!name) {
return ''
Expand All @@ -143,11 +143,11 @@ function switchLocalePath (locale, forcePrefix = false) {
})
let path = this.localePath(baseRoute, locale)

const { prefixAndDefaultRules: { switchLocale } } = options
const { prefixAndDefaultRule } = options
const { isPrefixAndDefault, isDefaultLocale } = getHelpers(locale)
const shouldSwitchToPrefix = switchLocale === 'prefix'
const shouldSwitchToPrefix = prefixAndDefaultRule === 'prefix'

if (isPrefixAndDefault && isDefaultLocale && (shouldSwitchToPrefix || forcePrefix)) {
if (isPrefixAndDefault && isDefaultLocale && shouldSwitchToPrefix) {
const cleanPath = removeLocaleFromPath(path, [locale])
const localizedPath = `/${locale}${cleanPath}`
path = nuxtOptions.trailingSlash ? withTrailingSlash(localizedPath) : withoutTrailingSlash(localizedPath)
Expand Down Expand Up @@ -180,19 +180,6 @@ function getRouteBaseName (givenRoute) {
return route.name.split(options.routesNameSeparator)[0]
}

/**
* @param {string} locale
*/
function getHelpers (locale = '') {
const isDefaultLocale = locale === options.defaultLocale
const isPrefixAndDefault = options.strategy === Constants.STRATEGIES.PREFIX_AND_DEFAULT

return {
isDefaultLocale,
isPrefixAndDefault
}
}

/**
* @param {string | undefined} routeName
* @param {string} locale
Expand All @@ -215,10 +202,10 @@ function getLocaleRouteName (routeName, locale, forceDefaultName = true) {
*/
function shouldForceDefaultRoute (currentPath) {
const { isPrefixAndDefault } = getHelpers()
const { defaultLocale, prefixAndDefaultRules: { routing } } = options
const { defaultLocale, prefixAndDefaultRule } = options
const isPrefixedPath = new RegExp(`^/${defaultLocale}(/|$)`).test(currentPath)

if (!isPrefixAndDefault || routing === 'default') {
if (!isPrefixAndDefault || prefixAndDefaultRule === 'default') {
return true
}

Expand Down
17 changes: 16 additions & 1 deletion src/templates/plugin.utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import isHTTPS from 'is-https'
import { localeMessages, options } from './options'
import { Constants, localeMessages, options } from './options'
import { formatMessage } from './utils-common'
// @ts-ignore
import { hasProtocol } from '~i18n-ufo'
Expand Down Expand Up @@ -216,6 +216,21 @@ export function mergeAdditionalMessages (i18n, additionalMessages, localeCodes,
}
}

/**
* @param {string} locale
*/
export function getHelpers (locale = '') {
const isDefaultLocale = locale === options.defaultLocale
const isPrefixAndDefault = options.strategy === Constants.STRATEGIES.PREFIX_AND_DEFAULT
const isPrefixExceptDefault = options.strategy === Constants.STRATEGIES.PREFIX_EXCEPT_DEFAULT

return {
isDefaultLocale,
isPrefixAndDefault,
isPrefixExceptDefault
}
}

/**
* @param {any} value
* @return {boolean}
Expand Down
13 changes: 1 addition & 12 deletions test/fixture/disable-redirect/components/LangSwitcher.vue
Original file line number Diff line number Diff line change
@@ -1,24 +1,13 @@
<template>
<ul class="lang-switcher">
<li v-for="locale in $i18n.locales" :key="locale.code">
<nuxt-link :to="switchLocalePath(locale.code, forcePrefix)">
<nuxt-link :to="switchLocalePath(locale.code)">
{{ locale.code.toUpperCase() }}
</nuxt-link>
</li>
</ul>
</template>

<script>
export default {
props: {
forcePrefix: {
type: Boolean,
default: false
}
}
}
</script>

<style scoped>
.lang-switcher {
margin: 20px;
Expand Down
2 changes: 0 additions & 2 deletions test/fixture/disable-redirect/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

<hr>

<LangSwitcher force-prefix />

<Nuxt />
</div>
</template>
Expand Down
8 changes: 4 additions & 4 deletions test/fixture/disable-redirect/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import BaseConfig from '../base.config'
/** @type {import('@nuxt/types').NuxtConfig} */
const config = {
...BaseConfig,
router: {
trailingSlash: true
},
i18n: {
prefixAndDefaultRules: {
switchLocale: 'default',
routing: 'prefix'
},
prefixAndDefaultRule: 'default',
strategy: 'prefix_and_default',
locales: [
{
Expand Down
7 changes: 1 addition & 6 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,6 @@ export interface BaseOptions {
onLanguageSwitched?: (oldLocale: string, newLocale: string) => void
}

export interface PrefixAndDefaultRules {
switchLocale: PrefixAndDefaultRule
routing: PrefixAndDefaultRule
}

export interface Options extends BaseOptions {
baseUrl?: string | ((context: NuxtContext) => string)
detectBrowserLanguage?: DetectBrowserLanguageOptions | false
Expand All @@ -69,7 +64,7 @@ export interface Options extends BaseOptions {
}
}
parsePages?: boolean
prefixAndDefaultRules?: PrefixAndDefaultRules
prefixAndDefaultRule?: PrefixAndDefaultRule
rootRedirect?: string | null | RootRedirectOptions
routesNameSeparator?: string
skipSettingLocaleOnNavigate?: boolean,
Expand Down
2 changes: 1 addition & 1 deletion types/vue.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ interface NuxtI18nApi {
localePath(route: RawLocation, locale?: string): string
localeRoute(route: RawLocation, locale?: string): Route | undefined
localeLocation(route: RawLocation, locale?: string): Location | undefined
switchLocalePath(locale: string, forcePrefix?: boolean): string
switchLocalePath(locale: string): string
}

declare module 'vue-i18n' {
Expand Down

0 comments on commit 275aa9f

Please sign in to comment.