Skip to content

feat: add language selector component to header #586

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ $rounded-pill: 50rem !default;

@import './Menu/menu.scss';
@import './studio-header/StudioHeader.scss';
@import './language-selector/LanguageSelector.scss';

.dropdown-item a {
text-decoration: none;
Expand Down
99 changes: 99 additions & 0 deletions src/language-selector/LanguageSelector.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import PropTypes from 'prop-types';
import React, { useContext, useState } from 'react';

import { changeUserSessionLanguage, getPrimaryLanguageSubtag, injectIntl } from '@edx/frontend-platform/i18n';
import { getLocale } from '@edx/frontend-platform/i18n/lib';
import { AppContext } from '@edx/frontend-platform/react';
import { Dropdown } from '@openedx/paragon';
import { Language } from '@openedx/paragon/icons';

/**
* Gets the localized display name of a language in its own language.
*
* @function getDisplayName
* @param {string} locale - The locale code (e.g., 'en', 'es', 'ar')
* @returns {string} The capitalized display name of the language in its native form
* @example
*/
const getDisplayName = (locale) => {
const langName = new Intl.DisplayNames([locale], { type: 'language', languageDisplay: 'standard' }).of(locale);
return langName.charAt(0).toUpperCase() + langName.slice(1);
};

/**
* Language Selector component that displays a dropdown allowing users to change the site language.
*
* The component is responsive and adapts to different screen sizes:
* - On large screens: Shows the full language name (e.g., "English")
* - On medium screens: Shows the language code (e.g., "EN")
* - On small screens: Shows only the language icon
*
* @component
* @param {Object} props - Component props
* @param {string} [props.className=''] - Additional CSS class names to apply to the component
* @returns {React.Element|null} The rendered component or null if disabled or no supported languages
*
* @requires config.SITE_SUPPORTED_LANGUAGES - Must be a non-empty array of locale codes
* @requires config.LANGUAGE_PREFERENCE_COOKIE_NAME - Cookie name for storing language preference
*/
const LanguageSelector = ({ className }) => {
const { config } = useContext(AppContext);

const languageOptions = config.SITE_SUPPORTED_LANGUAGES;
const [currentLocale, setCurrentLocale] = useState(getLocale());

/**
* Handles the selection of a language from the dropdown.
* Only triggers language change if the selected language is different from the current one.
*
* @param {string} selectedLocale - The locale code selected by the user
*/
const handleSelect = (selectedLocale) => {
if (currentLocale !== selectedLocale) {
changeUserSessionLanguage(selectedLocale);
setCurrentLocale(selectedLocale);
}
};

const currentLangCode = getPrimaryLanguageSubtag(currentLocale).toUpperCase();
const currentlangDisplayName = getDisplayName(currentLocale);

// Don't render the component if there are no language options
if (!Array.isArray(languageOptions)
|| languageOptions.length === 0) {
return null;

Check warning on line 64 in src/language-selector/LanguageSelector.jsx

View check run for this annotation

Codecov / codecov/patch

src/language-selector/LanguageSelector.jsx#L64

Added line #L64 was not covered by tests
}

return (
<div className={`${className} language-selector`} id="language-selector">
<Dropdown onSelect={handleSelect}>
<Dropdown.Toggle
id="lang-selector-dropdown"
iconBefore={Language}
variant="outline-primary"
size="sm"
>
<span className="lang-label-medium">{currentLangCode}</span>
<span className="lang-label-large">{currentlangDisplayName}</span>
</Dropdown.Toggle>
<Dropdown.Menu>
{languageOptions.map((locale) => (
<Dropdown.Item key={`lang-selector-${locale}`} eventKey={locale}>
{getDisplayName(locale)}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
</div>
);
};

LanguageSelector.propTypes = {
className: PropTypes.string,
};

LanguageSelector.defaultProps = {
className: '',
};

export default injectIntl(LanguageSelector);
22 changes: 22 additions & 0 deletions src/language-selector/LanguageSelector.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.language-selector {
padding: .75rem;

.dropdown-toggle {
.lang-label-medium,
.lang-label-large {
display: none;
}

@media (min-width: 576px) and (max-width: 767px) {
.lang-label-medium {
display: inline;
}
}

@media (min-width: 768px) {
.lang-label-large {
display: inline;
}
}
}
}
131 changes: 131 additions & 0 deletions src/language-selector/LanguageSelector.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import React from 'react';
import { mergeConfig } from '@edx/frontend-platform';
import { getLocale } from '@edx/frontend-platform/i18n/lib';
import { changeUserSessionLanguage } from '@edx/frontend-platform/i18n';
import {
act, fireEvent, initializeMockApp, render, screen,
} from '../setupTest';
import LanguageSelector from './LanguageSelector';

jest.mock('@edx/frontend-platform/i18n', () => ({
...jest.requireActual('@edx/frontend-platform/i18n'),
changeUserSessionLanguage: jest.fn().mockResolvedValue({}),
}));

jest.mock('@edx/frontend-platform/i18n/lib', () => ({
...jest.requireActual('@edx/frontend-platform/i18n/lib'),
getLocale: jest.fn(),
}));

jest.mock('@openedx/paragon/icons', () => ({
Language: () => <div>LanguageIcon</div>,
}));

jest.mock('@openedx/paragon', () => ({
...jest.requireActual('@openedx/paragon'),
useWindowSize: () => ({ width: global.innerWidth }),
}));

const LANGUAGE_PREFERENCE_COOKIE_NAME = 'language-preference';

describe('LanguageSelector', () => {
let mockReload;

beforeEach(() => {
jest.clearAllMocks();

mergeConfig({
ENABLE_HEADER_LANG_SELECTOR: true,
LANGUAGE_PREFERENCE_COOKIE_NAME,
SITE_SUPPORTED_LANGUAGES: ['es', 'en'],
});

initializeMockApp();

mockReload = jest.fn();
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { reload: mockReload },
});

global.innerWidth = 1200;
});

it('should not render when no supported languages are available', () => {
mergeConfig({
SITE_SUPPORTED_LANGUAGES: [],
});

const { container } = render(<LanguageSelector />);
// expect(container).toMatchSnapshot('no-supported-languages');
expect(container.querySelector('#language-selector')).toBeNull();
});

it('should change the language when different language is selected', async () => {
getLocale.mockReturnValue('en');

const { container } = render(<LanguageSelector />);
expect(container).toMatchSnapshot('before-language-change');

const langDropdown = screen.getByRole('button', { id: 'lang-selector-dropdown' });
fireEvent.click(langDropdown);

const spanishOption = screen.getByRole('button', { name: 'Español' });

await act(async () => {
fireEvent.click(spanishOption);
});

expect(container).toMatchSnapshot('after-language-change');
expect(changeUserSessionLanguage).toHaveBeenCalledWith('es');
});

it('should not change language if the same language is selected', async () => {
getLocale.mockReturnValue('en');

const { container } = render(<LanguageSelector />);
expect(container).toMatchSnapshot('before-same-language-selection');

const langDropdown = screen.getByRole('button', { id: 'lang-selector-dropdown' });
fireEvent.click(langDropdown);

const englishOption = screen.getByRole('button', { name: 'English' });
await act(async () => {
fireEvent.click(englishOption);
});

expect(container).toMatchSnapshot('after-same-language-selection');
expect(changeUserSessionLanguage).not.toHaveBeenCalled();
});

it('should display full language name on large screens', () => {
getLocale.mockReturnValue('en');

global.innerWidth = 1200;
render(<LanguageSelector />);

const button = screen.getByRole('button', { id: 'lang-selector-dropdown' });
expect(button).toMatchSnapshot('large-screen-button');
});

it('should display language code on medium screens', () => {
getLocale.mockReturnValue('en');

global.innerWidth = 700;
render(<LanguageSelector />);

const button = screen.getByRole('button', { id: 'lang-selector-dropdown' });
expect(button).toMatchSnapshot('medium-screen-button');
});

it('should display only icon on small screens', () => {
getLocale.mockReturnValue('en');

global.innerWidth = 500;
render(<LanguageSelector />);

const button = screen.getByRole('button', { id: 'lang-selector-dropdown' });
expect(button).toMatchSnapshot('small-screen-button');
});
});
Loading