Skip to content

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
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Ang-m4
Copy link

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

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
Copy link

openedx-webhooks commented Apr 1, 2025

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
🔘 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.


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
@dcoa dcoa requested a review from arbrandes May 29, 2025 19:51
Copy link
Contributor

@arbrandes arbrandes left a comment

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.

@dcoa
Copy link
Contributor

dcoa commented Jun 13, 2025

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
Copy link

codecov bot commented Jun 18, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 87.33%. Comparing base (e0656d1) to head (c2d269c).
Report is 21 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #786      +/-   ##
==========================================
+ Coverage   86.71%   87.33%   +0.61%     
==========================================
  Files          48       50       +2     
  Lines        1393     1429      +36     
  Branches      293      303      +10     
==========================================
+ Hits         1208     1248      +40     
+ Misses        172      168       -4     
  Partials       13       13              

☔ View full report in Codecov by Sentry.
📢 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.

const formData = new FormData();
formData.append('language', languageCode);

const url = `${getConfig().LMS_BASE_URL}/i18n/setlang/`;
Copy link
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
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

@Ang-m4
Copy link
Author

Ang-m4 commented Jun 25, 2025

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!

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
Projects
Status: Waiting on Author
Development

Successfully merging this pull request may close these issues.

4 participants