Last active
March 10, 2019 15:34
-
-
Save borie88/a056ec9168e1c7095576c7aa7dc50b74 to your computer and use it in GitHub Desktop.
Language handler for multilingual MP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import regeneratorRuntime from '../utils/runtime' | |
import wxp from '../utils/wxp' | |
import store from '../store' | |
// define our default locale here | |
const defaultLanguage = 'en' | |
// get any stored language settings from localStorage | |
const getStoredLanguage = async () => { | |
try { | |
const { data } = await wxp.getStorage({ key: 'language' }) | |
return data | |
} catch (error) { | |
return null | |
} | |
} | |
// get the user's phone language | |
const getPhoneLanguage = async () => { | |
const { language } = await wxp.getSystemInfo() | |
return language | |
} | |
// check if our store's current language is different than what we are passing | |
const storeNeedsUpdate = (language) => { | |
return store.getLanguage() !== language | |
} | |
// attempt to set a new language if it is supported or fallback to the default | |
export const setLanguage = async (newLanguage) => { | |
const allowedLanguages = ['en', 'zh'] | |
let language = defaultLanguage | |
if (allowedLanguages.indexOf(newLanguage) !== -1) { | |
language = newLanguage | |
} | |
if (storeNeedsUpdate(language)) { | |
await store.update({ language }) | |
} | |
await wxp.setStorage({ | |
key: 'language', | |
data: language | |
}) | |
} | |
// automatically get and process the user's phone language and set | |
const setAutoLanguage = async () => { | |
let language = defaultLanguage | |
try { | |
const phoneLanguage = await getPhoneLanguage() | |
language = phoneLanguage.split('_').shift().split('-').shift() | |
} catch (error) { | |
console.error('error auto setting language', error) | |
} finally { | |
await setLanguage(language) | |
} | |
} | |
// automatically retrieve stored language or get user's phone language and set. use this in appLaunch() | |
export const initLanguage = async () => { | |
const storedLanguage = await getStoredLanguage() | |
if (storedLanguage) { | |
await store.update({ language: storedLanguage }) | |
return | |
} | |
await setAutoLanguage() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment