All files / src/locales index.ts

92.3% Statements 12/13
50% Branches 3/6
100% Functions 2/2
100% Lines 12/12

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            1x 1x   1x     1x 1x 1x       1x         1x 1x       1x 1x   1x                  
import { createI18n } from 'vue-i18n'
import zhHant from './zh-Hant'
import zhHans from './zh-Hans'
 
export type AppLocale = 'zh-Hant' | 'zh-Hans'
 
export const LOCALES: readonly AppLocale[] = ['zh-Hant', 'zh-Hans']
export const LOCALE_STORAGE_KEY = 'wb-locale'
 
const DEFAULT_LOCALE: AppLocale = 'zh-Hant'
 
function readSavedLocale(): AppLocale {
  try {
    const saved = localStorage.getItem(LOCALE_STORAGE_KEY)
    Iif (saved && (LOCALES as readonly string[]).includes(saved)) return saved as AppLocale
  } catch {
    // 隐私模式 / 受限 web-view 下 localStorage 可能不可读,退回默认语言而不是白屏
  }
  return DEFAULT_LOCALE
}
 
/** <html lang> 需跟随语言切换,否则读屏与搜索引擎会按 zh-Hant 解析简体内容 */
export function syncDocumentLang(locale: AppLocale): void {
  Eif (typeof document !== 'undefined') {
    document.documentElement.lang = locale
  }
}
 
const locale = readSavedLocale()
syncDocumentLang(locale)
 
export const i18n = createI18n({
  legacy: false,
  locale,
  fallbackLocale: DEFAULT_LOCALE,
  messages: {
    'zh-Hant': zhHant,
    'zh-Hans': zhHans
  }
})