-
Notifications
You must be signed in to change notification settings - Fork 79
feat(i18n): add language preference management functionality #786
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
Ang-m4
wants to merge
9
commits into
openedx:master
Choose a base branch
from
eduNEXT:afg/change-user-language-preference
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
42fca2f
feat(i18n): add language preference management functionality
Ang-m4 f0814f7
fix: force page reload to ensure complete translation application
Ang-m4 a5c70f5
feat: conditional page reloading and module rename
Ang-m4 2a3be05
refactor(i18n): move language preference functions to languageApi module
Ang-m4 b63d4ee
test(i18n): add unit tests for languageApi and languageManager functions
Ang-m4 837ef56
feat(i18n): add getSupportedLocales function
Ang-m4 d6d1cd7
feat(i18n): update user preferences function
Ang-m4 b0b7b34
feat(i18n): update getSupportedLocaleList function
Ang-m4 729b314
fix: remove client-side cookie setting to prevent duplication
Ang-m4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { getConfig } from '../config'; | ||
| import { getAuthenticatedHttpClient, getAuthenticatedUser } from '../auth'; | ||
| import { convertKeyNames, snakeCaseObject } from '../utils'; | ||
|
|
||
| /** | ||
| * Updates user language preferences via the preferences API. | ||
| * | ||
| * This function gets the authenticated user, converts preference data to snake_case | ||
| * and formats specific keys according to backend requirements before sending the PATCH request. | ||
| * If no user is authenticated, the function returns early without making the API call. | ||
| * | ||
| * @param {Object} preferenceData - The preference parameters to update (e.g., { prefLang: 'en' }). | ||
| * @returns {Promise} - A promise that resolves when the API call completes successfully, | ||
| * or rejects if there's an error with the request. Returns early if no user is authenticated. | ||
| */ | ||
| export async function updateAuthenticatedUserPreferences(preferenceData) { | ||
| const user = getAuthenticatedUser(); | ||
| if (!user) { | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| const snakeCaseData = snakeCaseObject(preferenceData); | ||
| const formattedData = convertKeyNames(snakeCaseData, { | ||
| pref_lang: 'pref-lang', | ||
| }); | ||
|
|
||
| return getAuthenticatedHttpClient().patch( | ||
| `${getConfig().LMS_BASE_URL}/api/user/v1/preferences/${user.username}`, | ||
| formattedData, | ||
| { headers: { 'Content-Type': 'application/merge-patch+json' } }, | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Sets the language for the current session using the setlang endpoint. | ||
| * | ||
| * This function sends a POST request to the LMS setlang endpoint to change | ||
| * the language for the current user session. | ||
| * | ||
| * @param {string} languageCode - The language code to set (e.g., 'en', 'es', 'ar'). | ||
| * Should be a valid ISO language code supported by the platform. | ||
| * @returns {Promise} - A promise that resolves when the API call completes successfully, | ||
| * or rejects if there's an error with the request. | ||
| */ | ||
| export async function setSessionLanguage(languageCode) { | ||
| const formData = new FormData(); | ||
| formData.append('language', languageCode); | ||
|
|
||
| return getAuthenticatedHttpClient().post( | ||
| `${getConfig().LMS_BASE_URL}/i18n/setlang/`, | ||
| formData, | ||
| { | ||
| headers: { | ||
| Accept: 'application/json', | ||
| 'X-Requested-With': 'XMLHttpRequest', | ||
| }, | ||
| }, | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { updateAuthenticatedUserPreferences, setSessionLanguage } from './languageApi'; | ||
| import { getConfig } from '../config'; | ||
| import { getAuthenticatedHttpClient, getAuthenticatedUser } from '../auth'; | ||
|
|
||
| jest.mock('../config'); | ||
| jest.mock('../auth'); | ||
|
|
||
| const LMS_BASE_URL = 'http://test.lms'; | ||
|
|
||
| describe('languageApi', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| getConfig.mockReturnValue({ LMS_BASE_URL }); | ||
| getAuthenticatedUser.mockReturnValue({ username: 'testuser', userId: '123' }); | ||
| }); | ||
|
|
||
| describe('updateAuthenticatedUserPreferences', () => { | ||
| it('should send a PATCH request with correct data', async () => { | ||
| const patchMock = jest.fn().mockResolvedValue({}); | ||
| getAuthenticatedHttpClient.mockReturnValue({ patch: patchMock }); | ||
|
|
||
| await updateAuthenticatedUserPreferences({ prefLang: 'es' }); | ||
|
|
||
| expect(patchMock).toHaveBeenCalledWith( | ||
| `${LMS_BASE_URL}/api/user/v1/preferences/testuser`, | ||
| expect.any(Object), | ||
| expect.objectContaining({ headers: expect.any(Object) }), | ||
| ); | ||
| }); | ||
|
|
||
| it('should return early if no authenticated user', async () => { | ||
| const patchMock = jest.fn().mockResolvedValue({}); | ||
| getAuthenticatedHttpClient.mockReturnValue({ patch: patchMock }); | ||
| getAuthenticatedUser.mockReturnValue(null); | ||
|
|
||
| await updateAuthenticatedUserPreferences({ prefLang: 'es' }); | ||
|
|
||
| expect(patchMock).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('setSessionLanguage', () => { | ||
| it('should send a POST request to setlang endpoint', async () => { | ||
| const postMock = jest.fn().mockResolvedValue({}); | ||
| getAuthenticatedHttpClient.mockReturnValue({ post: postMock }); | ||
|
|
||
| await setSessionLanguage('ar'); | ||
|
|
||
| expect(postMock).toHaveBeenCalledWith( | ||
| `${LMS_BASE_URL}/i18n/setlang/`, | ||
| expect.any(FormData), | ||
| expect.objectContaining({ headers: expect.any(Object) }), | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { handleRtl, LOCALE_CHANGED } from './lib'; | ||
| import { publish } from '../pubSub'; | ||
| import { logError } from '../logging'; | ||
| import { updateAuthenticatedUserPreferences, setSessionLanguage } from './languageApi'; | ||
|
|
||
| /** | ||
| * Changes the user's language preference and applies it to the current session. | ||
| * | ||
| * This comprehensive function handles the complete language change process: | ||
| * 1. Sets the language cookie with the selected language code | ||
| * 2. If a user is authenticated, updates their server-side preference in the backend | ||
| * 3. Updates the session language through the setlang endpoint | ||
| * 4. Publishes a locale change event to notify other parts of the application | ||
| * | ||
| * @param {string} languageCode - The selected language locale code (e.g., 'en', 'es', 'ar'). | ||
| * Should be a valid ISO language code supported by the platform. | ||
| * @param {boolean} [forceReload=false] - Whether to force a page reload after changing the language. | ||
| * @returns {Promise} - A promise that resolves when all operations complete. | ||
| * | ||
| */ | ||
| export async function changeUserSessionLanguage( | ||
| languageCode, | ||
| forceReload = false, | ||
| ) { | ||
| try { | ||
| await updateAuthenticatedUserPreferences({ prefLang: languageCode }); | ||
| await setSessionLanguage(languageCode); | ||
| handleRtl(languageCode); | ||
| publish(LOCALE_CHANGED, languageCode); | ||
| } catch (error) { | ||
| logError(error); | ||
| } | ||
|
|
||
| if (forceReload) { | ||
| window.location.reload(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { changeUserSessionLanguage } from './languageManager'; | ||
| import { handleRtl, LOCALE_CHANGED } from './lib'; | ||
| import { logError } from '../logging'; | ||
| import { publish } from '../pubSub'; | ||
| import { updateAuthenticatedUserPreferences, setSessionLanguage } from './languageApi'; | ||
|
|
||
| jest.mock('./lib'); | ||
| jest.mock('../logging'); | ||
| jest.mock('../pubSub'); | ||
| jest.mock('./languageApi'); | ||
|
|
||
| describe('languageManager', () => { | ||
| let mockReload; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
|
|
||
| mockReload = jest.fn(); | ||
| Object.defineProperty(window, 'location', { | ||
| configurable: true, | ||
| writable: true, | ||
| value: { reload: mockReload }, | ||
| }); | ||
|
|
||
| updateAuthenticatedUserPreferences.mockResolvedValue({}); | ||
| setSessionLanguage.mockResolvedValue({}); | ||
| }); | ||
|
|
||
| describe('changeUserSessionLanguage', () => { | ||
| it('should perform complete language change process', async () => { | ||
| await changeUserSessionLanguage('fr'); | ||
| expect(updateAuthenticatedUserPreferences).toHaveBeenCalledWith({ | ||
| prefLang: 'fr', | ||
| }); | ||
| expect(setSessionLanguage).toHaveBeenCalledWith('fr'); | ||
| expect(handleRtl).toHaveBeenCalledWith('fr'); | ||
| expect(publish).toHaveBeenCalledWith(LOCALE_CHANGED, 'fr'); | ||
| expect(mockReload).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should handle errors gracefully', async () => { | ||
| updateAuthenticatedUserPreferences.mockRejectedValue(new Error('fail')); | ||
| await changeUserSessionLanguage('es', true); | ||
| expect(logError).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should call updateAuthenticatedUserPreferences even when user is not authenticated', async () => { | ||
| await changeUserSessionLanguage('en', true); | ||
| expect(updateAuthenticatedUserPreferences).toHaveBeenCalledWith({ | ||
| prefLang: 'en', | ||
| }); | ||
| }); | ||
|
|
||
| it('should reload if forceReload is true', async () => { | ||
| await changeUserSessionLanguage('de', true); | ||
| expect(mockReload).toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm adding a "pending" note here regarding @dcoa's findings on this other conversation. If the update_language endpoint works, we should probably use it.