align locale theme across sites (#38)

This commit is contained in:
AceDataCloud committed 2024-05-11 09:39:35 +00:00
1 parent 9b8db40440
commit 266f2e8bb2
12 files changed
+124 -91

No files matched your search

@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "align across site for theme and locale",
"packageName": "@acedatacloud/hub",
"email": "cqc@cuiqingcai.com",
"dependentChangeType": "patch"
}
+10 -9
View File
@@ -10,6 +10,8 @@ import { defineComponent } from 'vue';
import { toggleDark } from 'vue-dark-switch'; import { toggleDark } from 'vue-dark-switch';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { ElButton } from 'element-plus'; import { ElButton } from 'element-plus';
import { getCookie, setCookie } from 'typescript-cookie';
import { getDomain } from '@/utils/initializer';
export default defineComponent({ export default defineComponent({
components: { components: {
@@ -19,20 +21,13 @@ export default defineComponent({
emits: ['update:dark'], emits: ['update:dark'],
computed: { computed: {
dark() { dark() {
return this.$store.getters.dark; return getCookie('THEME') === 'dark';
} }
// switchValue() {
// return isDark.value;
// }
}, },
watch: { watch: {
dark(val) { dark(val) {
this.setDark(val); this.setDark(val);
} }
// switchValue(val) {
// console.log('switchValue', val);
// // this.$store.dispatch('setDark', val);
// }
}, },
mounted() { mounted() {
console.log('mounted', this.dark); console.log('mounted', this.dark);
@@ -41,12 +36,18 @@ export default defineComponent({
methods: { methods: {
setDark(flag: boolean) { setDark(flag: boolean) {
toggleDark(flag); toggleDark(flag);
this.$store.dispatch('setDark', flag); this.setCookie(flag);
if (flag === true) { if (flag === true) {
document.documentElement.classList.add('dark'); document.documentElement.classList.add('dark');
} else if (flag === false) { } else if (flag === false) {
document.documentElement.classList.remove('dark'); document.documentElement.classList.remove('dark');
} }
},
setCookie(isDark: boolean) {
setCookie('THEME', isDark ? 'dark' : 'light', {
path: '/',
domain: getDomain()
});
} }
} }
}); });
+12 -2
View File
@@ -22,8 +22,10 @@
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue'; import { defineComponent } from 'vue';
import { ElDropdown, ElDropdownItem, ElDropdownMenu, ElButton } from 'element-plus'; import { ElDropdown, ElDropdownItem, ElDropdownMenu } from 'element-plus';
import { SUPPORTED_LOCALES, setI18nLanguage } from '@/i18n'; import { SUPPORTED_LOCALES, setI18nLanguage } from '@/i18n';
import { setCookie } from 'typescript-cookie';
import { getDomain } from '@/utils/initializer';
export default defineComponent({ export default defineComponent({
name: 'LocaleSelector', name: 'LocaleSelector',
@@ -39,9 +41,17 @@ export default defineComponent({
}, },
methods: { methods: {
async onSelectLocale(locale: string) { async onSelectLocale(locale: string) {
// change router
this.$router.push({ query: { ...this.$route.query, locale: undefined } });
await setI18nLanguage(locale); await setI18nLanguage(locale);
this.$store.dispatch('setLocale', locale); this.setCookie(locale);
window.location.reload(); window.location.reload();
},
setCookie(locale: string) {
setCookie('LOCALE', locale, {
path: '/',
domain: getDomain()
});
} }
} }
}); });
+2 -2
View File
@@ -47,8 +47,8 @@ export const loadLocalResource = async (name: string, locale: string) => {
} }
}; };
export const getLocale = (): string => { export const getLocale = (lang?: string): string => {
const canonicalLang = Intl.getCanonicalLocales(navigator.language)?.[0]; const canonicalLang = Intl.getCanonicalLocales(lang || navigator.language)?.[0];
const supportedLocales = SUPPORTED_LOCALES.map((locale) => locale.value); const supportedLocales = SUPPORTED_LOCALES.map((locale) => locale.value);
// if the canonical language is supported, use it // if the canonical language is supported, use it
if (canonicalLang && supportedLocales.includes(canonicalLang)) { if (canonicalLang && supportedLocales.includes(canonicalLang)) {
+36 -32
View File
@@ -15,39 +15,43 @@ import copyToClipboard from 'copy-to-clipboard';
import { initializeCookies, initializeFavicon, initializeTitle } from './utils/initializer'; import { initializeCookies, initializeFavicon, initializeTitle } from './utils/initializer';
import config from './plugins/config'; import config from './plugins/config';
initializeCookies(); const main = async () => {
initializeTitle(); await initializeCookies();
initializeFavicon(); await initializeTitle();
await initializeFavicon();
const app = createApp(App); const app = createApp(App);
app.use(router); app.use(router);
app.use(store); app.use(store);
app.use(i18n); app.use(i18n);
app.use(dayjs, { app.use(dayjs, {
formatString: 'YYYY-MM-DD HH:mm:ss' formatString: 'YYYY-MM-DD HH:mm:ss'
});
app.use(config);
app.directive('loading', vLoading);
app.mount('#app');
console.debug('app mounted');
app.directive('highlight', async (el) => {
const blocks = el.querySelectorAll('pre code');
blocks.forEach((block: HTMLPreElement) => {
// create the copy button
const copy = document.createElement('button');
copy.innerHTML = i18n.global.t('common.button.copy').toString();
// add the event listener to each click
copy.addEventListener('click', () => {
copyToClipboard(block.innerText);
});
// append the copy button to each code block
block.parentElement?.prepend(copy);
hl.highlightBlock(block);
}); });
}); app.use(config);
app.directive('loading', vLoading);
app.mount('#app');
console.debug('app mounted');
// make app available globally app.directive('highlight', async (el) => {
// @ts-ignore const blocks = el.querySelectorAll('pre code');
window.app = app; blocks.forEach((block: HTMLPreElement) => {
// create the copy button
const copy = document.createElement('button');
copy.innerHTML = i18n.global.t('common.button.copy').toString();
// add the event listener to each click
copy.addEventListener('click', () => {
copyToClipboard(block.innerText);
});
// append the copy button to each code block
block.parentElement?.prepend(copy);
hl.highlightBlock(block);
});
});
// make app available globally
// @ts-ignore
window.app = app;
};
main();
+2 -2
View File
@@ -8,8 +8,8 @@ import chatdoc from './chatdoc';
import qrart from './qrart'; import qrart from './qrart';
import { ROUTE_CHAT_CONVERSATION_NEW, ROUTE_INDEX } from './constants'; import { ROUTE_CHAT_CONVERSATION_NEW, ROUTE_INDEX } from './constants';
import store from '@/store';
import { DEFAULT_LOCALE, setI18nLanguage } from '@/i18n'; import { DEFAULT_LOCALE, setI18nLanguage } from '@/i18n';
import { getCookie } from 'typescript-cookie';
const routes = [ const routes = [
{ {
@@ -34,7 +34,7 @@ const router = createRouter({
}); });
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
const locale = store.state.locale || DEFAULT_LOCALE; const locale = getCookie('LOCALE') || DEFAULT_LOCALE;
await setI18nLanguage(locale); await setI18nLanguage(locale);
return next(); return next();
}); });
-10
View File
@@ -25,14 +25,6 @@ export const setToken = ({ commit }: ActionContext<IRootState, IRootState>, payl
commit('setToken', payload); commit('setToken', payload);
}; };
export const setDark = ({ commit }: ActionContext<IRootState, IRootState>, payload: boolean) => {
commit('setDark', payload);
};
export const setLocale = ({ commit }: ActionContext<IRootState, IRootState>, payload: string) => {
commit('setLocale', payload);
};
export const setUser = ({ commit }: ActionContext<IRootState, IRootState>, payload: IUser) => { export const setUser = ({ commit }: ActionContext<IRootState, IRootState>, payload: IUser) => {
commit('setUser', payload); commit('setUser', payload);
}; };
@@ -61,13 +53,11 @@ export const getToken = async ({ commit }: ActionContext<IRootState, IRootState>
}; };
export default { export default {
setLocale,
resetToken, resetToken,
resetAll, resetAll,
resetUser, resetUser,
resetSetting, resetSetting,
setToken, setToken,
setDark,
setUser, setUser,
getToken, getToken,
getUser getUser
-10
View File
@@ -8,14 +8,6 @@ export const user = (state: IRootState): any => {
return state.user; return state.user;
}; };
export const dark = (state: IRootState): boolean => {
return state.dark;
};
export const locale = (state: IRootState): string => {
return state.locale;
};
export const token = (state: IRootState): any => { export const token = (state: IRootState): any => {
return state.token; return state.token;
}; };
@@ -25,10 +17,8 @@ export const setting = (state: IRootState): any => {
}; };
export default { export default {
locale,
authenticated, authenticated,
user, user,
token, token,
dark,
setting setting
}; };
-2
View File
@@ -12,8 +12,6 @@ export interface ICommonState {
token: IToken; token: IToken;
user?: IUser; user?: IUser;
setting?: ISetting; setting?: ISetting;
locale: string;
dark: boolean;
} }
export interface IRootState extends ICommonState { export interface IRootState extends ICommonState {
-10
View File
@@ -8,14 +8,6 @@ export const setUser = (state: IRootState, payload: IUser): void => {
}; };
}; };
export const setLocale = (state: IRootState, payload: string): void => {
state.locale = payload;
};
export const setDark = (state: IRootState, payload: boolean): void => {
state.dark = payload;
};
export const setToken = (state: IRootState, payload: any): void => { export const setToken = (state: IRootState, payload: any): void => {
state.token = { state.token = {
...state.token, ...state.token,
@@ -43,11 +35,9 @@ export const setSetting = (state: IRootState, payload: any): void => {
}; };
export default { export default {
setLocale,
setUser, setUser,
resetUser, resetUser,
setToken, setToken,
setDark,
resetToken, resetToken,
setSetting, setSetting,
resetSetting resetSetting
+3 -4
View File
@@ -2,13 +2,11 @@ import { IRootState } from './models';
import chatState from '../chat/state'; import chatState from '../chat/state';
import midjourneyState from '../midjourney/state'; import midjourneyState from '../midjourney/state';
import chatdocState from '../chatdoc/state'; import chatdocState from '../chatdoc/state';
import { getLocale } from '@/i18n'; import qrartState from '../qrart/state';
export default (): IRootState => { export default (): IRootState => {
return { return {
user: {}, user: {},
locale: getLocale(),
dark: window.matchMedia('(prefers-color-scheme: dark)').matches,
token: { token: {
access: undefined, access: undefined,
refresh: undefined, refresh: undefined,
@@ -20,6 +18,7 @@ export default (): IRootState => {
}, },
chatdoc: chatdocState(), chatdoc: chatdocState(),
chat: chatState(), chat: chatState(),
midjourney: midjourneyState() midjourney: midjourneyState(),
qrart: qrartState()
}; };
}; };
+52 -8
View File
@@ -1,13 +1,23 @@
import { setCookie } from 'typescript-cookie'; import { getCookie, setCookie } from 'typescript-cookie';
import config from '@/config'; import config from '@/config';
import favicon from '@/assets/images/favicon.ico'; import favicon from '@/assets/images/favicon.ico';
import { getLocale } from '@/i18n';
/** export const getDomain = () => {
* Initialize cookies. const host = window.location.hostname;
*/ // process test env and prod env, for example:
export const initializeCookies = () => { // hub.acedata.cloud -> .acedata.cloud
// hub.test.acedata.cloud -> .acedata.cloud
const domain = host.replace(/^\S+?\.(test\.|local\.)?/, '.');
console.log('cookies domain', domain);
return domain;
};
export const initializeCookies = async () => {
// parse the query string and set to cookies // parse the query string and set to cookies
const query = new URLSearchParams(window.location.search); const query = new URLSearchParams(window.location.search);
// set the inviter id to cookies
const inviterId = query.get('inviter_id'); const inviterId = query.get('inviter_id');
if (inviterId) { if (inviterId) {
// set the cookie to expire in 7 days // set the cookie to expire in 7 days
@@ -16,7 +26,41 @@ export const initializeCookies = () => {
console.log('set INVITER_ID to cookies', inviterId); console.log('set INVITER_ID to cookies', inviterId);
setCookie('INVITER_ID', inviterId, { setCookie('INVITER_ID', inviterId, {
expires: expiration, expires: expiration,
path: '/' path: '/',
domain: getDomain()
});
}
// set the theme to cookies
const theme = query.get('theme');
if (theme) {
console.log('set THEME to cookies', theme);
setCookie('THEME', theme, {
path: '/',
domain: getDomain()
});
} else if (!getCookie('THEME')) {
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log('set THEME to cookies', isDark ? 'dark' : 'light');
setCookie('THEME', isDark ? 'dark' : 'light', {
path: '/',
domain: getDomain()
});
}
// set the locale to cookies
const lang = query.get('lang');
let locale = undefined;
if (lang) {
locale = getLocale(lang);
} else if (!getCookie('LOCALE')) {
locale = getLocale();
}
if (locale) {
console.log('set LOCALE to cookies', locale);
setCookie('LOCALE', locale, {
path: '/',
domain: getDomain()
}); });
} }
}; };
@@ -24,7 +68,7 @@ export const initializeCookies = () => {
/** /**
* Initialize title. * Initialize title.
*/ */
export const initializeTitle = () => { export const initializeTitle = async () => {
// set the title from config.global.title // set the title from config.global.title
const title = config.global.title; const title = config.global.title;
// find the title element or insert a new one // find the title element or insert a new one
@@ -39,7 +83,7 @@ export const initializeTitle = () => {
/** /**
* Initialize favicon. * Initialize favicon.
*/ */
export const initializeFavicon = () => { export const initializeFavicon = async () => {
// by default use favicon which imported // by default use favicon which imported
// if faviconUrl is set in config, use it instead // if faviconUrl is set in config, use it instead
const favIconUrl = config.global.faviconUrl; const favIconUrl = config.global.faviconUrl;