charludo / ycms

Apache License 2.0
0 stars 0 forks source link

Feature/language switcher #113

Closed noworneverev closed 8 months ago

noworneverev commented 8 months ago

Short description

User now is able to change languages based on their selection of language.

Proposed changes

Add a switch button in sidebar to let user switch between German and English.

Side effects

Resolved issues

Fixes: #108

noworneverev commented 8 months ago

Cool, this works perfectly! 🎉

My only issue is that when you visit the page from a new device for the first time, no language option is selected. This might confuse users a little, esp. if we're going to host a public instance for the presentation, where they will be able to use their own devices.

Maybe something like this could fix this, by just setting the cookie based on the browser settings if it is not yet set?

const getUserBrowserLanguage = (): string => {
    const userLanguage = navigator.language.split('-')[0];
    return ['de', 'en'].includes(userLanguage) ? userLanguage : 'en';
};

const checkLanguageCookie = (): boolean => !!document.cookie.split('; ').find((cookie) => cookie.startsWith('django_language='));

const setLanguageCookie = (language: string): void => {
    document.cookie = `django_language=${language}; path=/;`;
};

const addClassesToElement = (elementId: string, classes: string): void => {
    const element = document.getElementById(elementId);
    if (element) {
        element.classList.add(...classes.split(' '));
    }
};

const handleLanguageSwitch = (): void => {
    if (!checkLanguageCookie()) {
        const userLanguage = getUserBrowserLanguage();
        setLanguageCookie(userLanguage);

        const elementId = `lang-switch-${userLanguage}`;
        const classesToAdd = 'underline pointer-events-none text-gray-300 dark:text-gray-500';

        addClassesToElement(elementId, classesToAdd);
    }
};

handleLanguageSwitch();

Not tested tbh, this is just chatgpt output 😂

It works. 🎉