refactor: global shared state and function (#79)
* refactor: expose i18n instance * feat: add global app utility function * refactor: use global utility function * refactor: avoid undefined when use outside vue refactor: avoid undefined when use outside vue * refactor: remove dup code and use util * refactor: auto fetch option when use store
This commit is contained in:
parent
aa79a4ef7d
commit
b0136bba4d
6 changed files with 136 additions and 216 deletions
72
src/utils/ui.ts
Normal file
72
src/utils/ui.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { Dark } from 'quasar';
|
||||
import { setLocale as setDateTimeLocale } from './datetime';
|
||||
import { i18n } from 'src/boot/i18n';
|
||||
|
||||
export enum Theme {
|
||||
Light = 'light',
|
||||
Dark = 'dark',
|
||||
Auto = 'auto',
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used to detect current theme that set before entering app.
|
||||
*
|
||||
* **Warning:** This must be used after initialize vue and quasar as it use quasar api.
|
||||
*/
|
||||
export function initTheme(): Theme {
|
||||
const current = localStorage.getItem('currentTheme') as Theme | null;
|
||||
if (!current) return setTheme(Theme.Auto);
|
||||
return setTheme(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used to set quasar theme through quasar api.
|
||||
*
|
||||
* **Warning:** Must be called after initialize vue and quasar.
|
||||
*/
|
||||
export function setTheme(theme: Theme): Theme {
|
||||
localStorage.setItem('currentTheme', theme);
|
||||
|
||||
if (theme !== Theme.Auto) {
|
||||
Dark.set(theme === Theme.Dark);
|
||||
}
|
||||
|
||||
if (theme === Theme.Auto) {
|
||||
Dark.set(window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
}
|
||||
|
||||
return theme;
|
||||
}
|
||||
|
||||
export enum Lang {
|
||||
English = 'eng',
|
||||
Thai = 'tha',
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used to get remembered language and use it.
|
||||
*
|
||||
* **Warning:** Must be used after initialize vue and vue-i18n
|
||||
*/
|
||||
export function initLang(): Lang {
|
||||
const { locale } = i18n.global;
|
||||
const current = localStorage.getItem('currentLanguage') as Lang | null;
|
||||
if (!current) return setLang(locale.value as Lang);
|
||||
return setLang(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used to set language and also remember the language set.
|
||||
*
|
||||
* **Warning:** Must be used after initialize vue and vue-i18n
|
||||
*/
|
||||
export function setLang(lang: Lang): Lang {
|
||||
const { locale } = i18n.global;
|
||||
locale.value = lang;
|
||||
localStorage.setItem('currentLanguage', lang);
|
||||
|
||||
// TODO: Make date time get locale from i18n instead of telling it to use specific lang.
|
||||
setDateTimeLocale(lang === Lang.English ? 'en-us' : 'th-th');
|
||||
|
||||
return lang;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue