Skip to content

Commit

Permalink
refactor: options passing
Browse files Browse the repository at this point in the history
  • Loading branch information
BobbieGoede committed Jan 8, 2024
1 parent a2a883f commit b30c3b4
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 215 deletions.
4 changes: 1 addition & 3 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,8 @@ export default defineNuxtModule<NuxtI18nOptions>({
nuxtI18nOptions,
isServer
}),
NUXT_I18N_MODULE_ID,
localeCodes,
nuxtI18nOptionsDefault: DEFAULT_OPTIONS,
nuxtI18nInternalOptions: { __normalizedLocales: normalizedLocales },
normalizedLocales,
dev: nuxt.options.dev,
isSSG: nuxt.options._generate,
parallelPlugin: options.parallelPlugin
Expand Down
3 changes: 2 additions & 1 deletion src/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const vueI18nConfigs: VueI18nConfig[]
export const localeCodes: string[] = []
export const nuxtI18nOptions: DeepRequired<NuxtI18nOptions<Context>> = {}
export const nuxtI18nOptionsDefault: NuxtI18nOptionsDefault = {}
export const nuxtI18nInternalOptions: DeepRequired<NuxtI18nInternalOptions> = {}
export const normalizedLocales: LocaleObject[] = []
export const NUXT_I18N_MODULE_ID = ''
export const isSSG = false
export const parallelPlugin: boolean
Expand All @@ -30,6 +30,7 @@ export {
NuxtI18nOptions,
NuxtI18nOptionsDefault,
NuxtI18nInternalOptions,
normalizedLocales,
DetectBrowserLanguageOptions,
RootRedirectOptions
} from './types'
25 changes: 12 additions & 13 deletions src/runtime/composables/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useRoute, useRouter, useRequestHeaders, useCookie, useNuxtApp } from '#imports'
import { ref, computed, watch, onUnmounted } from 'vue'
import { parseAcceptLanguage } from '../internal'
import { nuxtI18nInternalOptions, nuxtI18nOptionsDefault, localeCodes as _localeCodes } from '#build/i18n.options.mjs'
import { localeCodes, normalizedLocales, nuxtI18nOptions, nuxtI18nOptionsDefault } from '#build/i18n.options.mjs'
import { getActiveHead } from 'unhead'
import { useI18n } from 'vue-i18n'
import {
Expand All @@ -17,7 +17,6 @@ import {
} from 'vue-i18n-routing'

import type { Ref } from 'vue'
import type { DetectBrowserLanguageOptions } from '#build/i18n.options.mjs'

export * from 'vue-i18n'
export * from './shared'
Expand Down Expand Up @@ -237,7 +236,7 @@ export function useLocaleHead(
*
* @public
*/
export function useBrowserLocale(normalizedLocales = nuxtI18nInternalOptions.__normalizedLocales): string | null {
export function useBrowserLocale(): string | null {
const headers = useRequestHeaders(['accept-language'])
return (
findBrowserLocale(
Expand All @@ -259,17 +258,17 @@ export function useBrowserLocale(normalizedLocales = nuxtI18nInternalOptions.__n
*
* @public
*/
export function useCookieLocale(
options: Required<Pick<DetectBrowserLanguageOptions, 'useCookie' | 'cookieKey'>> & {
localeCodes: readonly string[]
} = {
useCookie: nuxtI18nOptionsDefault.detectBrowserLanguage.useCookie,
cookieKey: nuxtI18nOptionsDefault.detectBrowserLanguage.cookieKey,
localeCodes: _localeCodes
}
): Ref<string> {
export function useCookieLocale(): Ref<string> {
// Support for importing from `#imports` is generated by auto `imports` nuxt module, so `ref` is imported from `vue`
const locale: Ref<string> = ref('')
const options = {
useCookie:
(nuxtI18nOptions.detectBrowserLanguage && nuxtI18nOptions.detectBrowserLanguage.useCookie) ??
nuxtI18nOptionsDefault.detectBrowserLanguage.useCookie,
cookieKey:
(nuxtI18nOptions.detectBrowserLanguage && nuxtI18nOptions.detectBrowserLanguage.cookieKey) ||
nuxtI18nOptionsDefault.detectBrowserLanguage.cookieKey
}

if (options.useCookie) {
let code: string | null = null
Expand All @@ -282,7 +281,7 @@ export function useCookieLocale(
code = (cookie as any)[options.cookieKey]
}

if (code && options.localeCodes.includes(code)) {
if (code && localeCodes.includes(code)) {
locale.value = code
}
}
Expand Down
61 changes: 31 additions & 30 deletions src/runtime/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@ import {
import { hasProtocol } from 'ufo'
import isHTTPS from 'is-https'
import { useRequestHeaders, useRequestEvent, useCookie as useNuxtCookie, useRuntimeConfig, useNuxtApp } from '#imports'
import { nuxtI18nOptionsDefault, NUXT_I18N_MODULE_ID, isSSG } from '#build/i18n.options.mjs'
import {
nuxtI18nOptionsDefault,
NUXT_I18N_MODULE_ID,
isSSG,
localeCodes,
nuxtI18nOptions,
normalizedLocales
} from '#build/i18n.options.mjs'

import type { NuxtApp } from '#app'
import type { I18nOptions, Locale, VueI18n } from 'vue-i18n'
import type { Locale, VueI18n } from 'vue-i18n'
import type { Route, RouteLocationNormalized, RouteLocationNormalizedLoaded, LocaleObject } from 'vue-i18n-routing'
import type { DeepRequired } from 'ts-essentials'
import type { NuxtI18nOptions, NuxtI18nInternalOptions, DetectBrowserLanguageOptions } from '#build/i18n.options.mjs'
import type { DetectBrowserLanguageOptions } from '#build/i18n.options.mjs'

export function formatMessage(message: string) {
return NUXT_I18N_MODULE_ID + ' ' + message
Expand Down Expand Up @@ -85,36 +91,36 @@ export function parseAcceptLanguage(input: string): string[] {
return input.split(',').map(tag => tag.split(';')[0])
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function getBrowserLocale(options: Required<NuxtI18nInternalOptions>): string | undefined {
export function getBrowserLocale(): string | undefined {
let ret: string | undefined

if (process.client) {
if (navigator.languages) {
// get browser language either from navigator if running on client side, or from the headers
ret = findBrowserLocale(options.__normalizedLocales, navigator.languages as string[])
ret = findBrowserLocale(normalizedLocales, navigator.languages as string[])
__DEBUG__ && console.log('getBrowserLocale (navigator.languages, ret) -', navigator.languages, ret)
}
} else if (process.server) {
const header = useRequestHeaders(['accept-language'])
__DEBUG__ && console.log('getBrowserLocale accept-language', header)
const accept = header['accept-language']
if (accept) {
ret = findBrowserLocale(options.__normalizedLocales, parseAcceptLanguage(accept))
ret = findBrowserLocale(normalizedLocales, parseAcceptLanguage(accept))
__DEBUG__ && console.log('getBrowserLocale ret', ret)
}
}

return ret
}

export function getLocaleCookie({
useCookie = nuxtI18nOptionsDefault.detectBrowserLanguage.useCookie,
cookieKey = nuxtI18nOptionsDefault.detectBrowserLanguage.cookieKey,
localeCodes = []
}: Pick<DetectBrowserLanguageOptions, 'useCookie' | 'cookieKey'> & {
localeCodes?: readonly string[]
} = {}): string | undefined {
export function getLocaleCookie(): string | undefined {
const useCookie =
(nuxtI18nOptions.detectBrowserLanguage && nuxtI18nOptions.detectBrowserLanguage.useCookie) ??
nuxtI18nOptionsDefault.detectBrowserLanguage.useCookie
const cookieKey =
(nuxtI18nOptions.detectBrowserLanguage && nuxtI18nOptions.detectBrowserLanguage.cookieKey) ||
nuxtI18nOptionsDefault.detectBrowserLanguage.cookieKey

__DEBUG__ && console.log('getLocaleCookie', { useCookie, cookieKey, localeCodes })
if (!useCookie) {
return
Expand All @@ -129,9 +135,8 @@ export function getLocaleCookie({
}
}

export function setLocaleCookie(
locale: string,
{
export function setLocaleCookie(locale: string) {
const {
useCookie = nuxtI18nOptionsDefault.detectBrowserLanguage.useCookie,
cookieKey = nuxtI18nOptionsDefault.detectBrowserLanguage.cookieKey,
cookieDomain = nuxtI18nOptionsDefault.detectBrowserLanguage.cookieDomain,
Expand All @@ -140,8 +145,7 @@ export function setLocaleCookie(
}: Pick<
DetectBrowserLanguageOptions,
'useCookie' | 'cookieDomain' | 'cookieKey' | 'cookieSecure' | 'cookieCrossOrigin'
> = {}
) {
> = nuxtI18nOptions.detectBrowserLanguage || {}
if (!useCookie) {
return
}
Expand Down Expand Up @@ -191,13 +195,10 @@ export const DefaultDetectBrowserLanguageFromResult: DetectBrowserLanguageFromRe
from: 'unknown'
}

export function detectBrowserLanguage<Context extends NuxtApp = NuxtApp>(
export function detectBrowserLanguage(
route: string | Route | RouteLocationNormalized | RouteLocationNormalizedLoaded,
nuxtI18nOptions: DeepRequired<NuxtI18nOptions<Context>>,
nuxtI18nInternalOptions: DeepRequired<NuxtI18nInternalOptions>,
vueI18nOptions: I18nOptions,
vueI18nOptionsLocale: Locale | undefined,
detectLocaleContext: DetectLocaleContext,
localeCodes: string[] = [],
locale: Locale = ''
): DetectBrowserLanguageFromResult {
const { strategy } = nuxtI18nOptions
Expand Down Expand Up @@ -248,13 +249,13 @@ export function detectBrowserLanguage<Context extends NuxtApp = NuxtApp>(

// get preferred language from cookie if present and enabled
if (useCookie) {
matchedLocale = cookieLocale = getLocaleCookie({ ...nuxtI18nOptions.detectBrowserLanguage, localeCodes })
matchedLocale = cookieLocale = getLocaleCookie()
localeFrom = 'cookie'
__DEBUG__ && console.log('detectBrowserLanguage: cookieLocale', cookieLocale)
}
// try to get locale from either navigator or header detection
if (!matchedLocale) {
matchedLocale = getBrowserLocale(nuxtI18nInternalOptions)
matchedLocale = getBrowserLocale()
localeFrom = 'navigator_or_header'
__DEBUG__ && console.log('detectBrowserLanguage: browserLocale', matchedLocale)
}
Expand All @@ -279,7 +280,7 @@ export function detectBrowserLanguage<Context extends NuxtApp = NuxtApp>(
localeFrom
)

const vueI18nLocale = locale || vueI18nOptions.locale
const vueI18nLocale = locale || vueI18nOptionsLocale
__DEBUG__ && console.log('detectBrowserLanguage: vueI18nLocale', vueI18nLocale)

// handle cookie option to prevent multiple redirects
Expand Down Expand Up @@ -364,12 +365,12 @@ export function getLocaleDomain(locales: LocaleObject[]): string {
return host
}

export function getDomainFromLocale(localeCode: Locale, locales: LocaleObject[]): string | undefined {
export function getDomainFromLocale(localeCode: Locale): string | undefined {
const runtimeConfig = useRuntimeConfig()
const nuxtApp = useNuxtApp()
// lookup the `differentDomain` origin associated with given locale.
const config = runtimeConfig.public.i18n as { locales?: Record<Locale, { domain?: string }> }
const lang = locales.find(locale => locale.code === localeCode)
const lang = normalizedLocales.find(locale => locale.code === localeCode)
const domain = config?.locales?.[localeCode]?.domain ?? lang?.domain

if (domain) {
Expand Down
Loading

0 comments on commit b30c3b4

Please sign in to comment.