Skip to content
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

[WIP] Add language setting #4112

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

jfdoming
Copy link
Contributor

@jfdoming jfdoming commented Jan 8, 2025

Allows choosing a non-English language for the UI

@actual-github-bot actual-github-bot bot changed the title Add language setting [WIP] Add language setting Jan 8, 2025
Copy link

netlify bot commented Jan 8, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit b1d5d4c
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/678074bc18cbfd00087d23f8
😎 Deploy Preview https://deploy-preview-4112.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Jan 8, 2025

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
18 5.93 MB → 5.94 MB (+2.72 kB) +0.04%
Changeset
File Δ Size
src/components/settings/LanguageSettings.tsx 🆕 +2.08 kB 0 B → 2.08 kB
src/i18n.ts 📈 +558 B (+29.98%) 1.82 kB → 2.36 kB
home/runner/work/actual/actual/packages/loot-core/src/client/actions/prefs.ts 📈 +40 B (+2.46%) 1.59 kB → 1.63 kB
src/components/settings/index.tsx 📈 +69 B (+0.93%) 7.21 kB → 7.27 kB
locale/en.json 📈 +22 B (+0.02%) 93.64 kB → 93.66 kB
locale/uk.json 📉 -38 B (-0.03%) 136.3 kB → 136.27 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/index.js 3.74 MB → 3.74 MB (+2.73 kB) +0.07%
static/js/en.js 93.64 kB → 93.66 kB (+22 B) +0.02%

Smaller

Asset File Size % Changed
static/js/uk.js 136.3 kB → 136.27 kB (-38 B) -0.03%

Unchanged

Asset File Size % Changed
static/js/es.js 3.45 kB 0%
static/js/fr.js 15.49 kB 0%
static/js/ta.js 17 B 0%
static/js/de.js 4.78 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/AppliedFilters.js 10.24 kB 0%
static/js/narrow.js 84.3 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/pl.js 298 B 0%
static/js/zh-Hant.js 10.13 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/wide.js 104.78 kB 0%
static/js/ReportRouter.js 1.58 MB 0%

Copy link
Contributor

github-actions bot commented Jan 8, 2025

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.33 MB → 1.33 MB (+75 B) +0.01%
Changeset
File Δ Size
packages/loot-core/src/server/main.ts 📈 +153 B (+0.22%) 69.32 kB → 69.46 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.33 MB → 1.33 MB (+75 B) +0.01%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

@jfdoming jfdoming force-pushed the jfdoming/language-picker branch from 574a871 to 7015060 Compare January 8, 2025 06:20
@jfdoming
Copy link
Contributor Author

jfdoming commented Jan 8, 2025

/update-vrt

@jfdoming jfdoming changed the title [WIP] Add language setting Add language setting Jan 10, 2025
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces comprehensive language settings functionality across multiple files in the desktop client and core application. A new LanguageSettings React component is added to the settings interface, enabling users to select their preferred language. The changes include creating a language selection dropdown, implementing language availability checks, and modifying preference handling to support language storage and retrieval. The implementation leverages internationalization (i18n) utilities, dynamically generates language options using the Intl.DisplayNames API, and provides user guidance for translation support. The modifications span configuration files, type definitions, and server-side preference management to ensure seamless language preference management.

Possibly related PRs

Suggested labels

sparkles: feature, internationalization, language-support

Suggested reviewers

  • MikesGlitch
  • UnderKoen

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
packages/desktop-client/src/i18n.ts (2)

8-10: Consider using a more robust path parsing approach

The current path parsing logic assumes a specific directory structure. Consider using a more robust approach to handle potential path variations.

-export const availableLanguages = Object.keys(languages).map(
-  path => path.split('/')[2].split('.')[0],
-);
+export const availableLanguages = Object.keys(languages).map(path => {
+  const match = path.match(/\/locale\/([^.]+)\.json$/);
+  return match ? match[1] : '';
+}).filter(Boolean);

43-66: Enhance error handling and logging in language setting logic

The language setting implementation could benefit from more detailed error logging and user feedback.

 export const setI18NextLanguage = (language: string) => {
+  const logPrefix = '[Language Setting]';
   if (language === 'en' && !isLanguageAvailable(language)) {
-    // English is always ~available since we use natural-language keys.
+    console.debug(`${logPrefix} Using natural-language keys for English`);
     return;
   }

   if (!language) {
-    // System default
+    console.debug(`${logPrefix} No language specified, using system default`);
     setI18NextLanguage(navigator.language || 'en');
     return;
   }

   language = language.toLowerCase();
   if (!availableLanguages.includes(language)) {
     if (language.includes('-')) {
+      console.debug(`${logPrefix} Falling back to primary language code: ${language.split('-')[0]}`);
       setI18NextLanguage(language.split('-')[0]);
       return;
     }

-    console.error(`Unknown locale ${language}`);
+    console.error(`${logPrefix} Unsupported language: ${language}`);
     throw new Error(`Unknown locale ${language}`);
   }
+  console.debug(`${logPrefix} Setting language to: ${language}`);
   i18n.changeLanguage(language || 'en');
 };
packages/loot-core/src/types/prefs.d.ts (1)

80-80: Add JSDoc comment for the language preference

Consider adding documentation for the language property to improve code maintainability.

+  /** The user's preferred display language code (e.g., 'en', 'es', 'fr') */
   language: string;
packages/desktop-client/src/components/settings/LanguageSettings.tsx (2)

13-23: Cache language display names for better performance

The current implementation creates a new Intl.DisplayNames instance for each language. Consider caching the display names.

+const getLanguageDisplayNames = (languages: string[]) => {
+  const cache = new Map<string, string>();
+  return languages.map(lang => {
+    if (!cache.has(lang)) {
+      cache.set(
+        lang,
+        new Intl.DisplayNames([lang], { type: 'language' }).of(lang) || lang
+      );
+    }
+    return [lang, cache.get(lang)];
+  });
+};

 const languageOptions: SelectOption[] = [
   ['', 'System default'] as [string, string],
   Menu.line as typeof Menu.line,
-].concat(
-  availableLanguages.map(lang => [
-    lang,
-    new Intl.DisplayNames([lang], {
-      type: 'language',
-    }).of(lang) || lang,
-  ]),
-);
+].concat(getLanguageDisplayNames(availableLanguages));

46-78: Consider adding loading state for language options

The component should handle the loading state while language options are being initialized.

+  const [isLoading, setIsLoading] = React.useState(true);
+  
+  React.useEffect(() => {
+    // Simulate checking language availability
+    setIsLoading(false);
+  }, []);

   return (
     <Setting
       primaryAction={
         <Select
           options={languageOptions}
           value={isEnabled ? (language ?? '') : 'not-available'}
           defaultLabel={
-            isEnabled ? 'Select language' : 'No languages available'
+            isLoading
+              ? 'Loading languages...'
+              : isEnabled
+              ? 'Select language'
+              : 'No languages available'
           }
           onChange={value => {
             setLanguage(value);
             setI18NextLanguage(value);
           }}
-          disabled={!isEnabled}
+          disabled={!isEnabled || isLoading}
         />
       }
     >
packages/loot-core/src/server/main.ts (1)

1376-1376: Consider adding type validation for the language value.

The language value is loaded and returned without any validation. Consider adding type checking or sanitization to ensure the value is a valid language code.

 return {
   floatingSidebar: floatingSidebar === 'true' ? true : false,
   maxMonths: stringToInteger(maxMonths || ''),
   documentDir: documentDir || getDefaultDocumentDir(),
   keyId: encryptKey && JSON.parse(encryptKey).id,
-  language,
+  language: typeof language === 'string' && language.match(/^[a-z]{2}(-[A-Z]{2})?$/) ? language : 'en',
   theme:
     theme === 'light' ||
     theme === 'dark' ||

Also applies to: 1385-1385, 1395-1395

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a34c06 and b1d5d4c.

⛔ Files ignored due to path filters (7)
  • packages/desktop-client/e2e/settings.mobile.test.js-snapshots/Mobile-Settings-checks-that-settings-page-can-be-opened-4-chromium-linux.png is excluded by !**/*.png
  • packages/desktop-client/e2e/settings.mobile.test.js-snapshots/Mobile-Settings-checks-that-settings-page-can-be-opened-5-chromium-linux.png is excluded by !**/*.png
  • packages/desktop-client/e2e/settings.mobile.test.js-snapshots/Mobile-Settings-checks-that-settings-page-can-be-opened-6-chromium-linux.png is excluded by !**/*.png
  • packages/desktop-client/e2e/settings.test.js-snapshots/Settings-checks-the-page-visuals-1-chromium-linux.png is excluded by !**/*.png
  • packages/desktop-client/e2e/settings.test.js-snapshots/Settings-checks-the-page-visuals-2-chromium-linux.png is excluded by !**/*.png
  • packages/desktop-client/e2e/settings.test.js-snapshots/Settings-checks-the-page-visuals-3-chromium-linux.png is excluded by !**/*.png
  • upcoming-release-notes/4112.md is excluded by !**/*.md
📒 Files selected for processing (6)
  • packages/desktop-client/src/components/settings/LanguageSettings.tsx (1 hunks)
  • packages/desktop-client/src/components/settings/index.tsx (2 hunks)
  • packages/desktop-client/src/i18n.ts (2 hunks)
  • packages/loot-core/src/client/actions/prefs.ts (2 hunks)
  • packages/loot-core/src/server/main.ts (4 hunks)
  • packages/loot-core/src/types/prefs.d.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Functional
  • GitHub Check: Visual regression
🔇 Additional comments (2)
packages/desktop-client/src/components/settings/index.tsx (1)

35-35: LGTM! The language settings integration looks good.

The LanguageSettings component is properly imported and placed in a logical position within the settings interface, between format and authentication settings.

Also applies to: 199-199

packages/loot-core/src/server/main.ts (1)

1349-1351: LGTM! Language preference persistence is properly implemented.

The language preference is correctly saved to async storage when present in the prefs object.

Comment on lines +45 to +47
// We need to load translations before the app renders
setI18NextLanguage(prefs.language);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling potential errors in language initialization

The language initialization should handle potential errors to prevent app crashes.

-    // We need to load translations before the app renders
-    setI18NextLanguage(prefs.language);
+    try {
+      // We need to load translations before the app renders
+      setI18NextLanguage(prefs.language);
+    } catch (error) {
+      console.error('[Preferences] Failed to set language:', error);
+      // Fallback to English
+      setI18NextLanguage('en');
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// We need to load translations before the app renders
setI18NextLanguage(prefs.language);
try {
// We need to load translations before the app renders
setI18NextLanguage(prefs.language);
} catch (error) {
console.error('[Preferences] Failed to set language:', error);
// Fallback to English
setI18NextLanguage('en');
}

Comment on lines +32 to +44
<Select
options={languageOptions}
value={isEnabled ? (language ?? '') : 'not-available'}
defaultLabel={
isEnabled ? 'Select language' : 'No languages available'
}
onChange={value => {
setLanguage(value);
setI18NextLanguage(value);
}}
disabled={!isEnabled}
/>
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add ARIA labels for better accessibility

The language selector should have appropriate ARIA labels for better accessibility.

 <Select
   options={languageOptions}
   value={isEnabled ? (language ?? '') : 'not-available'}
+  aria-label="Select display language"
   defaultLabel={
     isEnabled ? 'Select language' : 'No languages available'
   }
   onChange={value => {
     setLanguage(value);
     setI18NextLanguage(value);
   }}
   disabled={!isEnabled}
 />
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<Select
options={languageOptions}
value={isEnabled ? (language ?? '') : 'not-available'}
defaultLabel={
isEnabled ? 'Select language' : 'No languages available'
}
onChange={value => {
setLanguage(value);
setI18NextLanguage(value);
}}
disabled={!isEnabled}
/>
}
<Select
options={languageOptions}
value={isEnabled ? (language ?? '') : 'not-available'}
aria-label="Select display language"
defaultLabel={
isEnabled ? 'Select language' : 'No languages available'
}
onChange={value => {
setLanguage(value);
setI18NextLanguage(value);
}}
disabled={!isEnabled}
/>
}

@jfdoming jfdoming changed the title Add language setting [WIP] Add language setting Jan 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant