locale-settings.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { STORAGE } from '@/core/constants/storage-keys'
  2. /** @typedef {{ code: string, text: string }} LocaleOption */
  3. /**
  4. * @param {(key: string) => string} t
  5. * @returns {LocaleOption[]}
  6. */
  7. export function buildLocaleOptions(t) {
  8. return [
  9. { code: 'auto', text: t('locale.auto') },
  10. { code: 'en', text: t('locale.en') },
  11. { code: 'en-SG', text: t('locale.en-sg') },
  12. { code: 'en-MY', text: t('locale.en-my') },
  13. { code: 'zh-cn', text: t('locale.zh-hans') },
  14. { code: 'zh-Hant', text: t('locale.zh-hant') }
  15. ]
  16. }
  17. export function getStoredLocaleCode() {
  18. const saved = uni.getStorageSync(STORAGE.language)
  19. if (saved) return saved
  20. const current = uni.getLocale()
  21. return current || 'auto'
  22. }
  23. /**
  24. * @param {LocaleOption[]} options
  25. * @param {string} code
  26. */
  27. export function localeLabelForCode(options, code) {
  28. const hit = options.find((item) => item.code === code)
  29. if (hit) return hit.text
  30. return code
  31. }
  32. /**
  33. * @param {string} storedCode
  34. * @param {object} i18n VueI18n instance
  35. */
  36. export function applyLocaleChange(storedCode, i18n) {
  37. uni.setStorageSync(STORAGE.language, storedCode)
  38. uni.setLocale(storedCode)
  39. if (storedCode === 'auto') {
  40. i18n.locale = uni.getLocale()
  41. } else {
  42. i18n.locale = storedCode
  43. }
  44. }
  45. export function isAndroidPlatform() {
  46. try {
  47. return uni.getSystemInfoSync().platform.toLowerCase() === 'android'
  48. } catch (_) {
  49. return false
  50. }
  51. }