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

feat(web): google-translate #1763

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Nov 30, 2024

Experimental


PR-Codex overview

This PR introduces a translation feature using Google Translate, enhancing the application's language support. It includes a dropdown for language selection and integrates the translation functionality into the context and layout of the application.

Detailed summary

  • Enabled resolveJsonModule in tsconfig.json.
  • Added DOM to lib in tsconfig.json.
  • Updated global styles in global-style.ts for better layout.
  • Created TranslateDropdown component for language selection.
  • Added TranslateProvider to manage translation context.
  • Integrated translation script injection in TranslateProvider.
  • Wrapped application routes in TranslateProvider for accessibility.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a TranslateProvider for managing language translation across the application.
    • Added a TranslateDropdown component for users to select their preferred language from multiple options.
    • Integrated the TranslateDropdown into the settings menu for easier access.
  • Bug Fixes

    • Improved layout properties in the settings menu for better user experience.
  • Style

    • Updated global styles to enhance element visibility and positioning.
  • Documentation

    • Added TypeScript definitions for the Window object to support Google Translate functionalities.

Copy link
Contributor

coderabbitai bot commented Nov 30, 2024

Walkthrough

The pull request introduces a new TranslateProvider component that wraps the existing SentryRoutes within the App component, enhancing the application's translation capabilities. Additionally, a new TranslateDropdown component is added for language selection, utilizing a context for managing language state. Modifications to the General settings component incorporate this dropdown, while global styles are updated to control the visibility of certain elements. The TypeScript configuration is also adjusted to include the DOM library, and new global type declarations for the Window object are introduced to support Google Translate functionalities.

Changes

File Path Change Summary
web/src/app.tsx Added TranslateProvider component wrapping SentryRoutes.
web/src/components/TranslateDropdown.tsx Introduced TranslateDropdown component for language selection using DropdownSelect.
web/src/context/TranslateProvider.tsx Created TranslateProvider context with language management, including useTranslate hook.
web/src/layout/Header/navbar/Menu/Settings/General.tsx Integrated TranslateDropdown into the General component layout.
web/src/styles/global-style.ts Added CSS rules for body positioning and visibility of specific elements related to translation.
web/tsconfig.json Extended TypeScript configuration to include the "DOM" library.
web/global.d.ts Added interface for Window object with properties for Google Translate integration.

Possibly related PRs

  • feat(web-devtools): custom-context-input #1716: The CustomContextInputs component introduced in this PR is related to the TranslateProvider as both involve managing state and context for user interactions within the application. The TranslateDropdown could potentially be integrated with custom context features for language selection.

Suggested labels

Type: Feature🗿, Package: Web

Suggested reviewers

  • alcercu
  • kemuru

Poem

In the garden of code, where rabbits play,
A dropdown for languages brightens the day.
With translations so sweet, we hop and we cheer,
For every new feature that brings us all near!
So let’s celebrate changes, both big and small,
In the world of our app, there’s magic for all! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e023c06 and b8933ac.

📒 Files selected for processing (1)
  • web/src/styles/global-style.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/styles/global-style.ts

🪧 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 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 or @coderabbitai title 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

netlify bot commented Nov 30, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit b8933ac
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/674df973d8efba0008498886
😎 Deploy Preview https://deploy-preview-1763--kleros-v2-university.netlify.app
📱 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

netlify bot commented Nov 30, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit b8933ac
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/674df973f80dad0008f92a27
😎 Deploy Preview https://deploy-preview-1763--kleros-v2-testnet.netlify.app
📱 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

netlify bot commented Nov 30, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit b8933ac
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/674df9731490f00007669f46
😎 Deploy Preview https://deploy-preview-1763--kleros-v2-neo.netlify.app
📱 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

@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: 6

🧹 Outside diff range and nitpick comments (5)
web/src/context/TranslateProvider.tsx (2)

15-17: Enhance error message for context usage

The error message could be more specific to help developers understand where the TranslateProvider should be placed.

-    throw new Error("Context Provider not found.");
+    throw new Error("useTranslate must be used within a TranslateProvider");

61-63: Consider UI implications of translate element placement

The Google Translate element div might affect layout and styling. Consider:

  1. Adding styling to control visibility
  2. Moving it to a more appropriate location in the DOM
  3. Adding aria attributes for accessibility
+ // Add at the top with other styles
+ const hideTranslateElement = {
+   position: 'absolute',
+   clip: 'rect(0 0 0 0)',
+   height: '1px',
+   width: '1px',
+   margin: '-1px',
+   overflow: 'hidden',
+ };

  return (
    <TranslateContext.Provider value={useMemo(() => ({ currentLang, setLang }), [currentLang, setLang])}>
-     <div id="google_translate_element"></div>
+     <div 
+       id="google_translate_element" 
+       style={hideTranslateElement}
+       aria-hidden="true"
+     ></div>
      {children}
    </TranslateContext.Provider>
  );
web/tsconfig.json (1)

69-70: Consider adding additional TypeScript libraries

While adding "DOM" is necessary, consider also adding:

  1. "DOM.Iterable" for better DOM collection support
  2. "ES2015" or later for modern JavaScript features
  3. "WebWorker" if using web workers
   "lib": [
     "ESNext.Array",
-    "DOM"
+    "DOM",
+    "DOM.Iterable",
+    "ES2020"
   ],
web/src/styles/global-style.ts (1)

20-20: Consider documenting the purpose of the top style.

The !important declaration suggests this is overriding Google Translate's styles. Please add a comment explaining why this override is necessary.

web/src/layout/Header/navbar/Menu/Settings/General.tsx (1)

101-101: Consider adding aria-label for accessibility.

The TranslateDropdown should have appropriate accessibility attributes for screen readers.

- <TranslateDropdown />
+ <TranslateDropdown aria-label="Language selection" />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 49932e2 and 1c20e01.

📒 Files selected for processing (6)
  • web/src/app.tsx (2 hunks)
  • web/src/components/TranslateDropdown.tsx (1 hunks)
  • web/src/context/TranslateProvider.tsx (1 hunks)
  • web/src/layout/Header/navbar/Menu/Settings/General.tsx (3 hunks)
  • web/src/styles/global-style.ts (2 hunks)
  • web/tsconfig.json (1 hunks)
🔇 Additional comments (2)
web/src/app.tsx (1)

37-99: Verify TranslateProvider implementation and error handling.

The provider placement looks good, but we should ensure proper error boundaries and loading states are implemented in the TranslateProvider.

✅ Verification successful

TranslateProvider implementation is adequate but has basic error handling

The TranslateProvider implementation:

  • Correctly manages language state using localStorage
  • Has basic error handling for script injection
  • Provides proper context value memoization
  • Includes error handling in the useTranslate hook

However, a few points to note:

  • Error handling is limited to console logging for script injection failures
  • No loading state is implemented, but it's not critical as Google Translate handles its own loading UI
  • The provider doesn't need error boundaries as translation failures are non-fatal and handled by Google Translate
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if TranslateProvider implements error boundaries and loading states
ast-grep --pattern 'class TranslateProvider extends React.Component {
  $$$
  componentDidCatch($_) {
    $$$
  }
  $$$
}'

# Check for loading state handling
ast-grep --pattern 'const TranslateProvider = $_$ => {
  $$$
  const [isLoading, setIsLoading] = useState($_$);
  $$$
}'

Length of output: 247


Script:

#!/bin/bash
# Let's first locate the TranslateProvider implementation
fd "TranslateProvider" --type f

# Then examine its implementation
rg -l "TranslateProvider" --type tsx --type ts

# Get the content of files containing TranslateProvider
rg "TranslateProvider" -A 10 -B 10 --type tsx --type ts

Length of output: 228


Script:

#!/bin/bash
# Now that we found the file, let's examine its content
cat web/src/context/TranslateProvider.tsx

Length of output: 2355

web/src/layout/Header/navbar/Menu/Settings/General.tsx (1)

62-64: LGTM! Style improvements enhance readability.

The added flex properties and gap improve the vertical spacing and alignment of settings items.

web/src/context/TranslateProvider.tsx Outdated Show resolved Hide resolved
web/src/context/TranslateProvider.tsx Outdated Show resolved Hide resolved
web/src/context/TranslateProvider.tsx Outdated Show resolved Hide resolved
web/src/components/TranslateDropdown.tsx Outdated Show resolved Hide resolved
web/src/components/TranslateDropdown.tsx Outdated Show resolved Hide resolved
web/src/styles/global-style.ts Outdated Show resolved Hide resolved
Copy link

netlify bot commented Nov 30, 2024

Deploy Preview for kleros-v2-testnet-devtools failed. Why did it fail? →

Name Link
🔨 Latest commit b8933ac
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/674df9730ddb2c0008e58084

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 30, 2024
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: 1

🧹 Outside diff range and nitpick comments (1)
web/src/components/TranslateDropdown.tsx (1)

27-27: Use current language from context as the default value

Instead of hardcoding the default value to "en", consider using the current language from context to reflect the user's existing preference.

Apply this diff:

-          defaultValue={"en"}
+          defaultValue={lang}

And update the useTranslate hook to include lang:

       const { setLang } = useTranslate();
+      const { setLang, lang } = useTranslate();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1c20e01 and 1d59d83.

📒 Files selected for processing (4)
  • web/global.d.ts (1 hunks)
  • web/src/components/TranslateDropdown.tsx (1 hunks)
  • web/src/context/TranslateProvider.tsx (1 hunks)
  • web/src/layout/Header/navbar/Menu/index.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
web/global.d.ts

[error] 22-22: void is confusing outside a return type or a type parameter.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments (5)
web/src/components/TranslateDropdown.tsx (1)

28-30: 🛠️ Refactor suggestion

Improve type safety by typing the callback parameter

Instead of casting val to SupportedLangs, you can directly type the val parameter to avoid unnecessary casting and enhance type safety.

Apply this diff:

           callback={(val) => {
-            setLang(val as SupportedLangs);
+            setLang(val);
           }}

Change it to:

          callback={(val: SupportedLangs) => {
            setLang(val);
          }}
web/src/layout/Header/navbar/Menu/index.tsx (1)

94-94: Integration of TranslateDropdown looks good

The addition of TranslateDropdown to the Menu component enhances the user interface and is well-implemented.

web/src/context/TranslateProvider.tsx (3)

29-29: Use HTTPS explicitly in script URL for security

The script URL should use HTTPS explicitly to ensure secure communication and avoid potential security risks.

Apply this diff to update the script URL:

-addScript.setAttribute("src", "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
+addScript.setAttribute("src", "https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");

32-41: Declare TypeScript types for window properties

To prevent TypeScript errors and improve code maintainability, declare the types for window.google and window.googleTranslateElementInit.

Add the following global declaration at the top of the file:

declare global {
  interface Window {
    google: {
      translate: {
        TranslateElement: new (config: {
          pageLanguage: string;
          includedLanguages: string;
        }, elementId: string) => void;
      };
    };
    googleTranslateElementInit: () => void;
  }
}

51-51: Set secure attributes for the googtrans cookie

Enhance security by setting appropriate attributes on the googtrans cookie, such as secure and samesite.

Apply this diff to update the cookie settings:

-document.cookie = "googtrans" + "=" + `/en/${cValue}` + ";" + "Session" + ";path=/";
+document.cookie = `googtrans=/en/${cValue}; path=/; secure; samesite=strict`;

web/global.d.ts Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 30, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 2, 2024
Copy link

codeclimate bot commented Dec 2, 2024

Code Climate has analyzed commit b8933ac and detected 2 issues on this pull request.

Here's the issue category breakdown:

Category Count
Duplication 1
Style 1

View more on Code Climate.

Copy link

sonarcloud bot commented Dec 2, 2024

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

Successfully merging this pull request may close these issues.

1 participant