feat(i18n): add language preference management functionality#786
feat(i18n): add language preference management functionality#786Ang-m4 wants to merge 9 commits intoopenedx:masterfrom
Conversation
|
Thanks for the pull request, @Ang-m4! This repository is currently maintained by 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 approvalIf you haven't already, check this list to see if your contribution needs to go through the product review process.
🔘 Provide contextTo 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:
🔘 Get a green buildIf one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green. DetailsWhere 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:
💡 As a result it may take up to several weeks or months to complete a review and merge your PR. |
c87194b to
a17955e
Compare
arbrandes
left a comment
There was a problem hiding this comment.
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.
|
I was thinking about the list of supported languages to display I'm thinking as default use an array provided for @arbrandes what do you thing? In that way we can get rid of |
1e1f82c to
d83e228
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #786 +/- ##
==========================================
+ Coverage 87.13% 87.31% +0.18%
==========================================
Files 48 50 +2
Lines 1407 1435 +28
Branches 297 305 +8
==========================================
+ Hits 1226 1253 +27
- Misses 168 169 +1
Partials 13 13 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
src/i18n/languageManager.js
Outdated
| const formData = new FormData(); | ||
| formData.append('language', languageCode); | ||
|
|
||
| const url = `${getConfig().LMS_BASE_URL}/i18n/setlang/`; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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.
|
Hi @arbrandes, I made some changes to the code as you requested. Please let me know what you think:
and i would like to know your thoughts on @dcoa’s comments!
Thank you so much for your time on this! |
|
@arbrandes friendly tag for reviewing here. Thank you! |
|
@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. |
arbrandes
left a comment
There was a problem hiding this comment.
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!
src/i18n/languageManager.js
Outdated
| cookies.set(cookieName, languageCode); | ||
|
|
||
| try { | ||
| const user = getAuthenticatedUser(); |
There was a problem hiding this comment.
I believe the call to getAuthenticatedUser() would be more at home in languageApi.js. username is only used there, anyway.
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) { |
There was a problem hiding this comment.
As suggested in another review comment, I would change this function like so:
| 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.
| formData.append('language', languageCode); | ||
|
|
||
| return getAuthenticatedHttpClient().post( | ||
| `${getConfig().LMS_BASE_URL}/i18n/setlang/`, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Yes, we should use the update_language API indeed. It touches the database.
src/i18n/languageManager.js
Outdated
| const cookies = getCookies(); | ||
| const cookieName = getConfig().LANGUAGE_PREFERENCE_COOKIE_NAME; | ||
| cookies.set(cookieName, languageCode); |
There was a problem hiding this comment.
As per this other conversation, if we can leverage the update_language endpoint to set the cookie, we should. This is an if, though.
src/i18n/languageManager.js
Outdated
| const formData = new FormData(); | ||
| formData.append('language', languageCode); | ||
|
|
||
| const url = `${getConfig().LMS_BASE_URL}/i18n/setlang/`; |
There was a problem hiding this comment.
@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?
c2d269c to
133b230
Compare
133b230 to
b0b7b34
Compare
|
This LGTM!! thank you, @Ang-m4 . @arbrandes the PR was updated accordingly to the feedback, could you please verify? |
|
We've successfully implemented the language selector feature on our end and everything is working well. The only question we have is regarding the We implemented a client-side workaround in the Is this the intended behavior, or should |
|
Friendly ping on this, @arbrandes |
arbrandes
left a comment
There was a problem hiding this comment.
I can't find anything to object to architecturally, but we might be missing the ability for operators to restrict the list of languages the user can select from. See the inline question below.
| formData.append('language', languageCode); | ||
|
|
||
| return getAuthenticatedHttpClient().post( | ||
| `${getConfig().LMS_BASE_URL}/i18n/setlang/`, |
| * @returns {string[]} Array of supported locale codes | ||
| * @memberof module:Internationalization | ||
| */ | ||
| export function getSupportedLocaleList() { |
There was a problem hiding this comment.
@Asespinel poses a great question: shouldn't we allow the operator to manually define which languages are actually available for use or selection by the end user, independently of the locales derived from messages?
I believe we should. In the pre-MFE world this was possible via a call to released_languages(), which in turn consulted the DarkLangConfig model.
In the header PR that goes along with this one there's a reference to a SITE_SUPPORTED_LANGUAGES config item, but I don't see it implemented anywhere.
What do? 1) a call to released_languages on the backend, or 2) a new frontend-only configuration?
Personally, I think either would be sufficient, but probably 2) is easier to implement and has less potential for UX problems. I can also see a path where 2) is configurable at runtime via MFE_CONFIG.
(Tangent: if we don't go with 1) and don't foresee ever needing the features of DarkLang - such as the ability to test fake/beta languages by adding a ?langPref=english@pirate query to the URL - we should deprecate the DarkLang thing.)
@brian-smith-tcril, @dcoa, @felipemontoya: thoughts?
There was a problem hiding this comment.
Oh, I was just researching some of this recently. The whole thing seems a bit messy. Sounds like you might have some insight to share on openedx/openedx-platform#38036
There was a problem hiding this comment.
In the header PR that goes along with this one there's a reference to a SITE_SUPPORTED_LANGUAGES config item, but I don't see it implemented anywhere.
That was previously implement but we change it to pass the languages as props for the slot refactor.
Here is in the footer PR commit as reference openedx/frontend-component-footer@82bfc97#diff-618acf142786bf7414152d4982d3d647b5ca1f96edaed7385ba0f17b46741b65R63-R64 and the comment that mention the idea #786 (comment)
I think for now, just to keep consistency with the legacy code and the templates that allow to select the language in header and footer there, having a single source of true DarkLang is ideal (I ignore if we have a current endpoint to return the information, I think no, right?). However, looking ahead, once the UI becomes fully client-side rendered, I don’t see much value (at least from the frontend perspective) in keeping DarkLang feature. In that scenario, I would prefer to manage it through a configuration variable instead.
|
@bradenmacdonald, one more area to look at, regarding languages. cc: @shadinaif |
| * @param {string} languageCode - The selected language locale code (e.g., 'en', 'es', 'ar'). | ||
| * Should be a valid ISO language code supported by the platform. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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.
I'm not sure we really need an event for locale changes anymore (or ever did)? Because any react-intl components like 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 |
Language Management Module
Description
This PR intents to add a new
LanguageManagermodule to standardize language switching functionality. The module provides a new API for handling language changes from any component in the application.Key Features
Implementation Details
New Functions
changeUserSessionLanguage(languageCode): Main public function that orchestrates the language change process:updateUserPreferences(username, preferenceData): Updates server-side user language preferences via the APIsetSessionLanguage(languageCode): Sets the language for the current session using the LMS setlang endpointAPI Usage
Components can now implement language switching with a single function call:
Related Work
This functionality is a core dependency for the Language Selector Implementation.