schon/storefront/app/composables/languages/useLanguageSwitch.ts
Alexandr SaVBaD Waltz 2ea18eb8a6 feat(storefront): refactor i18n and cart/wishlist handling for improved user experience
Refactored i18n configuration, replacing `DEFAULT_LOCALE` with `DEFAULT_LOCALE_FALLBACK` and enhancing environment-based locale validation. Improved cookie persistence for cart and wishlist, ensuring fallback handling for unauthenticated users.

Enhancements:
- Added `createProjectKey` utility for consistent project key generation.
- Reworked cart and wishlist composables (`useOrderOverwrite`, `useWishlistOverwrite`) to decouple product identifier and handle cookies robustly.
- Centralized `DEFAULT_LOCALE` logic for better maintainability.
- Refined `useOrderSync` and `useWishlistSync` for clean synchronization across auth states.
- Updated SCSS in hero and header styles for alignment corrections.

Breaking Changes: `DEFAULT_LOCALE` constant removed; replaced with runtime config and fallback logic. Consumers must adapt to `DEFAULT_LOCALE_FALLBACK` and `$appHelpers.DEFAULT_LOCALE`.
2026-02-28 22:38:45 +03:00

70 lines
1.6 KiB
TypeScript

import { SWITCH_LANGUAGE } from '@graphql/mutations/languages.js';
import type { IUserResponse, LocaleDefinition } from '@types';
export function useLanguageSwitch() {
const userStore = useUserStore();
const router = useRouter();
const { $apollo } = useNuxtApp();
const { $appHelpers } = useNuxtApp();
const switchLocalePath = useSwitchLocalePath();
const cookieLocale = useCookie($appHelpers.COOKIES_LOCALE_KEY, {
default: () => $appHelpers.DEFAULT_LOCALE,
path: '/',
});
const isAuthenticated = computed(() => userStore.isAuthenticated);
const userUuid = computed(() => userStore.user?.uuid);
const { mutate, loading, error } = useMutation<IUserResponse>(SWITCH_LANGUAGE);
let isSwitching = false;
async function switchLanguage(locale: string) {
if (isSwitching || cookieLocale.value === locale) return;
try {
isSwitching = true;
cookieLocale.value = locale;
await $apollo.defaultClient.clearStore();
await router.push({
path: switchLocalePath(cookieLocale.value as LocaleDefinition['code']),
});
if (isAuthenticated.value) {
const result = await mutate({
uuid: userUuid.value,
language: locale,
});
if (result?.data?.updateUser) {
userStore.setUser(result.data.updateUser.user);
}
}
await new Promise((resolve) => setTimeout(resolve, 100));
await $apollo.defaultClient.refetchQueries({
include: 'active',
});
} catch (error) {
console.error('Error switching language:', error);
} finally {
isSwitching = false;
}
}
watch(error, (err) => {
if (err) {
console.error('useLanguageSwitch error:', err);
}
});
return {
switchLanguage,
loading,
};
}