Skip to content

feat(i18n): add language preference management functionality - #786

Open
Ang-m4 wants to merge 11 commits into
openedx:masterfrom
eduNEXT:afg/change-user-language-preference
Open

feat(i18n): add language preference management functionality#786
Ang-m4 wants to merge 11 commits into
openedx:masterfrom
eduNEXT:afg/change-user-language-preference

Conversation

@Ang-m4

@Ang-m4 Ang-m4 commented Apr 1, 2025

Copy link
Copy Markdown

Language Management Module

Description

This PR intents to add a new LanguageManager module to standardize language switching functionality. The module provides a new API for handling language changes from any component in the application.

Key Features

  • Unified Language Management: Centralizes all language-related operations into a single module
  • Complete Language Switching Flow: Handles the entire language change process through a single function call
  • User Preference Persistence: Updates both client-side cookies and server-side user preferences
  • Session Management: Integrates with LMS backend to ensure consistent language experience
  • RTL Support: Automatically handles right-to-left language adjustments
  • Event System Integration: Publishes events when locale changes to allow components to react

Implementation Details

New Functions

  • changeUserSessionLanguage(languageCode): Main public function that orchestrates the language change process:

    • Sets the language cookie
    • Updates authenticated user preferences in the backend (if applicable)
    • Updates the session language
    • Publishes a locale change event
    • Handles RTL adjustments
  • updateUserPreferences(username, preferenceData): Updates server-side user language preferences via the API

  • setSessionLanguage(languageCode): Sets the language for the current session using the LMS setlang endpoint

API Usage

Components can now implement language switching with a single function call:

import { changeUserSessionLanguage } from '@edx/frontend-platform/i18n';

// When a user selects a new language
changeUserSessionLanguage('ar'); // Switch to Arabic

Related Work

This functionality is a core dependency for the Language Selector Implementation.

@openedx-webhooks openedx-webhooks added the open-source-contribution PR author is not from Axim or 2U label Apr 1, 2025
@openedx-webhooks

openedx-webhooks commented Apr 1, 2025

Copy link
Copy Markdown

Thanks for the pull request, @Ang-m4!

This repository is currently maintained by @openedx/committers-frontend.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Submit a signed contributor agreement (CLA)

⚠️ We ask all contributors to the Open edX project to submit a signed contributor agreement or indicate their institutional affiliation.
Please see the CONTRIBUTING file for more information.

If you've signed an agreement in the past, you may need to re-sign.
See The New Home of the Open edX Codebase for details.

Once you've signed the CLA, please allow 1 business day for it to be processed.
After this time, you can re-run the CLA check by adding a comment below that you have signed it.
If the CLA check continues to fail, you can tag the @openedx/cla-problems team in a comment for further assistance.

🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

@github-project-automation github-project-automation Bot moved this to Needs Triage in Contributions Apr 1, 2025
@mphilbrick211 mphilbrick211 moved this from Needs Triage to Waiting on Author in Contributions Apr 1, 2025
@Ang-m4
Ang-m4 force-pushed the afg/change-user-language-preference branch from c87194b to a17955e Compare April 2, 2025 14:08
@Ang-m4
Ang-m4 marked this pull request as ready for review April 3, 2025 13:04
@dcoa
dcoa requested a review from arbrandes May 29, 2025 19:51

@arbrandes arbrandes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is a good idea to have this logic be centralized in frontend-platform, instead of implemented as part of language selection dropdowns. I imagine openedx/frontend-component-footer#493 will have to be refactored accordingly, correct?

I have a minor suggested change, but I'm also not approving yet as I'd like to see PRs that use this.

Comment thread src/i18n/LanguageManager.js Outdated
Comment thread src/i18n/LanguageManager.js Outdated
@dcoa

dcoa commented Jun 13, 2025

Copy link
Copy Markdown
Contributor

I was thinking about the list of supported languages to display

I'm thinking as default use an array provided for frontend-platform using the messages object here that is configured during the MFE initialize. So the manager could return a function or variable with the list of locales Object.keys(messages)

@arbrandes what do you thing?

In that way we can get rid of SITE_SUPPORTED_LANGUAGES here, and in any case someone want to pass a more restricted or controlled list, they can do it by the plugin configuration.

@Ang-m4
Ang-m4 force-pushed the afg/change-user-language-preference branch from 1e1f82c to d83e228 Compare June 18, 2025 19:25
@codecov

codecov Bot commented Jun 18, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.30508% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.36%. Comparing base (cf61627) to head (0abefe9).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/i18n/lib.ts 96.42% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #786      +/-   ##
==========================================
+ Coverage   87.86%   88.36%   +0.50%     
==========================================
  Files          50       52       +2     
  Lines        1483     1556      +73     
  Branches      297      306       +9     
==========================================
+ Hits         1303     1375      +72     
- Misses        169      170       +1     
  Partials       11       11              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread src/i18n/languageManager.js Outdated
const formData = new FormData();
formData.append('language', languageCode);

const url = `${getConfig().LMS_BASE_URL}/i18n/setlang/`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was digging a little bit in edx-platform to see how the mako templates manage the logic and I found this endpoint, it is used for update no-authenticated users as you can see in the mako template.

The endpoint request a CSRF token as you can see here. I just want to make sure the following line of code is correct as a suggested change from the frontend-platform perspective (getAuthenticatedHttpClient is the right service to use? -@arbrandes could you help me with this doubt?-).

getAuthenticatedHttpClient().patch(`${getConfig().LMS_BASE_URL}/lang_pref/update_language`, {"pref-lang": languageCode}, { isPublic: true })

In this way we can avoid setting the language cookie (as currently happen with the lines 81-83 of the this PR), and it will be 100% managed for the backend in both authenticated and unauthenticated users.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I create a sandbox for testing in learning, and the current endpoint can manage the authenticated and unauthenticated case (I have the problem in my dev environment only)

https://app.pr-1741-1395ab.sandboxes.opencraft.hosting/learning/course/course-v1:Demo+CT01+CT01/home

c.c @arbrandes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dcoa, you say the endpoint can manage both authenticated and unauthenticated cases, but then mention a problem. Do you still think we can use the update_language endpoint here instead of Django's setlang?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I update my environment and tested it again and the /i18n/setlang/ endpoint works with the authenticated and unauthenticated users in both production like and dev environments.

So we can set the language using it and make the backend handle the cookie update. For the unauthenticated user will create a session cookie meanwhile for a authenticated user creates a cookie with expiration date.

Then the change is not needed.

@Ang-m4

Ang-m4 commented Jun 25, 2025

Copy link
Copy Markdown
Author

Hi @arbrandes,

I made some changes to the code as you requested. Please let me know what you think:

  • Created a new languageApi module for easier testing.
  • Added an optional flag for reloading the page if needed.
  • Added a unit test.

and i would like to know your thoughts on @dcoa’s comments!

The endpoint request a CSRF token as you can see here. I just want to make sure the following line of code is correct as a suggested change from the frontend-platform perspective (getAuthenticatedHttpClient is the right service to use? -@arbrandes could you help me with this doubt?-).


I'm thinking as default use an array provided for frontend-platform using the messages object here that is configured during the MFE initialize. So the manager could return a function or variable with the list of locales Object.keys(messages)

Thank you so much for your time on this!

@dcoa

dcoa commented Aug 25, 2025

Copy link
Copy Markdown
Contributor

@arbrandes friendly tag for reviewing here. Thank you!

@felipemontoya

Copy link
Copy Markdown
Member

@arbrandes friendly ping again. To not be a constant bother since I know you are deepdiving in the frontendbase stuff, I'd like to ask if you need to pass this to someone else to be a reviewer here.

@mphilbrick211 mphilbrick211 moved this from Waiting on Author to Ready for Review in Contributions Sep 16, 2025

@arbrandes arbrandes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of changes requested, and one pending change based on @dcoa's findings.

As for the list of supported languages, I completely agree that the list should come from the messages array, which can itself be changed by operators by other mechanisms. And it's also a good idea to have a getter function provided by i18n/lib.

Otherwise, this is looking good. Apologies for the delay in getting to the review!

Comment thread src/i18n/languageManager.js Outdated
cookies.set(cookieName, languageCode);

try {
const user = getAuthenticatedUser();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe the call to getAuthenticatedUser() would be more at home in languageApi.js. username is only used there, anyway.

Comment thread src/i18n/languageApi.js Outdated
* @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 updateUserPreferences(username, preferenceData) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As suggested in another review comment, I would change this function like so:

Suggested change
export async function updateUserPreferences(username, preferenceData) {
export async function updateAuthenticatedUserPreferences(preferenceData) {

And then get the authenticated username inside the function. Unless, of course, you can imagine a situation where we'd need this function to change the preference of some user other than the currently logged in one - but I find that to be unlikely.

Comment thread src/i18n/languageApi.js Outdated
formData.append('language', languageCode);

return getAuthenticatedHttpClient().post(
`${getConfig().LMS_BASE_URL}/i18n/setlang/`,

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we should use the update_language API indeed. It touches the database.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Ang-m4, any objections to implementing this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sadly @Ang-m4 has recently left our team. @dcoa, do you think this work is something you could continue?

@dcoa dcoa Jul 2, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: after reviewing more carefully the Django templates for comparison and considering the message above I updated the endpoint to use update_language

My apologize if took me some time to implement this change. I look forward to any comment.

Comment thread src/i18n/languageManager.js Outdated
Comment on lines +27 to +29
const cookies = getCookies();
const cookieName = getConfig().LANGUAGE_PREFERENCE_COOKIE_NAME;
cookies.set(cookieName, languageCode);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per this other conversation, if we can leverage the update_language endpoint to set the cookie, we should. This is an if, though.

Comment thread src/i18n/languageManager.js Outdated
const formData = new FormData();
formData.append('language', languageCode);

const url = `${getConfig().LMS_BASE_URL}/i18n/setlang/`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dcoa, you say the endpoint can manage both authenticated and unauthenticated cases, but then mention a problem. Do you still think we can use the update_language endpoint here instead of Django's setlang?

@Ang-m4
Ang-m4 force-pushed the afg/change-user-language-preference branch 2 times, most recently from 133b230 to b0b7b34 Compare October 6, 2025 02:01
@Ang-m4
Ang-m4 requested a review from dcoa October 6, 2025 14:02
@dcoa

dcoa commented Oct 8, 2025

Copy link
Copy Markdown
Contributor

This LGTM!! thank you, @Ang-m4 .

@arbrandes the PR was updated accordingly to the feedback, could you please verify?

@dcoa
dcoa requested a review from arbrandes October 8, 2025 12:53
Comment thread src/i18n/languageManager.js Outdated
Comment on lines +15 to +16
* @param {string} languageCode - The selected language locale code (e.g., 'en', 'es', 'ar').
* Should be a valid ISO language code supported by the platform.

@bradenmacdonald bradenmacdonald Feb 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please give more specific examples of what these locale codes are like (e.g. fr-ca ?) because the platform has at least two separate lists of locale codes, with different formats, and browsers/react-intl tend to use yet a third format (fr-CA part lowercase, part uppercase) that's different than either of the platform's two backend formats.

Also, since this is a brand new file, can you not use TypeScript?

@dcoa dcoa Mar 2, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing out the different formats available in the platform, I check in Django docs (https://docs.djangoproject.com/en/6.0/topics/i18n/translation/) to understand which format apply in this case, it says should work with LANGUAGES, so I will update the example taking that in consideration.

since this is a brand new file, can you not use TypeScript?

I'm not sure what do you refer here, could you help me with a more context?. I understand the comment is JSDoc format.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what do you refer here, could you help me with a more context?. I understand the comment is JSDoc format.

I mean rename this file to languageManager.ts (not .js) and change it like this:

export async function changeUserSessionLanguage(
-   languageCode,
-   forceReload = false,
- ) {
+   languageCode: string,
+   forceReload = false,
+ ) -> Promise<void> {

etc.

@dcoa dcoa Mar 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just want to confirm, it is TypeScript supported in frontend-platform? I don't see any reference in main so I wonder if might need that first.

[Update]: I create this PR #868 to add minimal configuration for babel, could you help me with the review? :)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a review with a change request with what seems like a minor oversight.

@bradenmacdonald

Copy link
Copy Markdown
Contributor

Architecturally, it makes total sense to me to encapsulate all this functionality into a cohesive API. As for the details of which languages etc, I'll leave that to the others who are discussing it.

Event System Integration: Publishes events when locale changes to allow components to react

I'm not sure we really need an event for locale changes anymore (or ever did)? Because any react-intl components like <FormattedMessage /> will get re-rendered when the locale changes, and any components that use the useIntl() hook will also get re-rendered when the locale changes. If you want to "listen for a locale change event", you essentially only need this code in a component:

const intl = useIntl();
useEffect(() => {
  // This runs after the component first mounts and anytime the locale changes.
}, [intl.locale]);

So, I think it makes sense to continue emitting our custom LOCALE_CHANGED event for backwards compatibility, but maybe we should mark it as deprecated while we're at it, and just use the standard react-intl APIs for achieving the same thing. Or is there some use case I'm missing?

@mphilbrick211 mphilbrick211 added the waiting on author PR author needs to resolve review requests, answer questions, fix tests, etc. label Apr 6, 2026
@dcoa
dcoa force-pushed the afg/change-user-language-preference branch 2 times, most recently from 82ff56c to 4fb83f9 Compare April 9, 2026 04:54
@mphilbrick211 mphilbrick211 removed the waiting on author PR author needs to resolve review requests, answer questions, fix tests, etc. label Apr 9, 2026
@gabrieldamours

Copy link
Copy Markdown

Hi @arbrandes! Quick check-in here — what are the next steps?

@itsjeyd itsjeyd added the waiting for eng review PR is ready for review. Review and merge it, or suggest changes. label Jun 25, 2026
@dcoa
dcoa force-pushed the afg/change-user-language-preference branch from 4fb83f9 to 633d5b6 Compare July 2, 2026 01:56
@dcoa
dcoa force-pushed the afg/change-user-language-preference branch from 29b4d94 to 0abefe9 Compare July 2, 2026 06:13
@dcoa
dcoa requested a review from arbrandes July 2, 2026 06:15

@arbrandes arbrandes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I just mentioned to @bradenmacdonald in another issue, I think that at this point, anything major such as this should land in frontend-base first. I'm marking this review as "request changes" precisely so we can do this before merging anything here.

Why? Because frontend-base is the future, and we'll have to decide what the right path is there first. Once we know what the future looks like (do we depend on an edx-platform API or not? What can users do? What can sysadmins do?), we can then decide to backport it, or not.

So, @gabrieldamours, and @dcoa, the next step is: let's get this - and the accompanying UI - merged into frontend-base before anything else.

@arbrandes

arbrandes commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

This is the new epic:

openedx/public-engineering#558

TLDR: frontend-base already has most of the functionality. We just need to agree on everything (such as moving or copying the selector to the header - it's currently in the footer - or what the selector looks like, and of course, finally, if we're doing away with Darklang entirely).

@felipemontoya

felipemontoya commented Aug 7, 2026

Copy link
Copy Markdown
Member

Hey Adolfo, while I understand the tech story I'd like to highlight the product story. 3 years ago a customer asked for this. We told them it's better to go through the community. After 2 major refactors and building this as a second PR that supposedly contained all the learnings from the first 2 years of discussion, the result is that this no longer will be accepted as is and instead requires to go through a third major refactor.

It's difficult to sustain to this costumer that going through the community is a better option. And they have told me so. 3 years still no solution for a language selector through the community. That is the message they got.

Sorry to publish my frustrations specificly to you, but this issue had been a hard one.

The original pr author even left our company in the meantime.

@arbrandes

Copy link
Copy Markdown
Contributor

@felipemontoya, I hear you. We're trying to get better at addressing these ideas. I'm open to having a retro-style discussion about this one in particular, so we can try to avoid whatever issues it ran into.

In such a discussion, I think I'd pin it on uncertainties about a) UX, and b) implementation. These uncertainties are, to this day, not resolved. It is hard to approve PRs if we can't agree on what the end result should be.

@arbrandes

Copy link
Copy Markdown
Contributor

The good news is that I personally want to get this resolved/approved/merged for Willow. I'd love your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open-source-contribution PR author is not from Axim or 2U waiting for eng review PR is ready for review. Review and merge it, or suggest changes.

Projects

Status: In Eng Review

Development

Successfully merging this pull request may close these issues.