Skip to content

style: minimal dark theme #1636

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

Merged
merged 40 commits into from
Nov 14, 2024
Merged

style: minimal dark theme #1636

merged 40 commits into from
Nov 14, 2024

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Nov 10, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new localization keys for NFT and governance functionalities.
    • Added a new QuickActionButton component for enhanced modularity.
  • Improvements

    • Adjusted font sizes across various components for a more cohesive visual appearance.
    • Updated button and grid styles to align with the new theme specifications.
    • Enhanced the visual representation of various UI elements, including borders and colors.
    • Simplified translation function calls for consistency.
    • Improved styling for popover and button components to enhance user experience.
    • Updated the AccountLabel component to use borders instead of background colors for profile labels.
    • Modified icon sizes and styles across multiple components for better visual consistency.
    • Enhanced the AccountBrief component with theme-based image styling.
    • Refined display logic for balance information in the AccountDetails component.
    • Introduced an animated success icon in the FailSuccessIcon component for improved visual feedback.
    • Replaced the HideNumbers component with HideBalance for better UI integration.
    • Updated the HideBalance component to toggle visibility based on theme and user interaction.
    • Added a new optional prop inHeading to the AddressDropdown component for enhanced styling flexibility.
    • Adjusted the visual presentation of the Currency and FavoriteChains components to improve consistency with the theme.
    • Removed the hideNumbers prop from several components to streamline state management.
    • Enhanced resource management in hooks by implementing unsubscribe mechanisms for storage watchers.
  • Version Updates

    • Updated package version to 0.29.0.

Copy link
Contributor

coderabbitai bot commented Nov 10, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request includes multiple changes across various components within the PolkaGate extension. The updates primarily focus on visual styling adjustments, including modifications to button colors, font sizes, and border properties. Notably, the TwoButtons component's secondary button styling is refined, while other components like AccountBodyFs, HomeMenu, and ShowValidator receive similar aesthetic enhancements. Additionally, the Filters component sees improvements in UI consistency and code organization. Overall, the changes are cosmetic, maintaining existing functionality while updating the visual presentation.

Changes

File Path Change Summary
packages/extension-polkagate/src/components/TwoButtons.tsx Updated borderColor and color properties of the secondary button's sx prop.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountBodyFs.tsx Adjusted fontSize of Identity component to 22px and added iconWidth prop to OptionalCopyButton.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountItem.tsx Added opacity: 0.5 style to DragIndicatorIcon.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/HomeMenu.tsx Changed icon sizes from 30px to 25px for multiple buttons and adjusted minHeight of Grid.
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx Updated borderRightColor and maxWidth of Grid components.
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ValidatorsTableFS.tsx Changed border color of Grid for validator items from secondary.main to secondary.light.
packages/extension-polkagate/src/partials/Asset.tsx Altered borderColor of Grid from primary.main to primary.light.
packages/extension-polkagate/src/partials/QuickAction.tsx Changed background color of Grid for dark mode.
packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx Introduced QuickActionButton component and updated goToGovernance function for type consistency.
packages/extension-polkagate/src/popup/staking/partial/Filters.tsx Simplified Typography rendering and updated Divider background color.
packages/extension-polkagate/src/popup/staking/partial/ShowPool.tsx Modified border colors for Grid elements and simplified t function calls.
packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx Updated border colors for Grid components in ValidatorInformation section.
packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx Adjusted import statements and simplified Checkbox2 labels.
packages/extension-polkagate/src/themes/dark.ts Modified light value of secondary color in darkTheme.
packages/extension/package.json Updated version from 0.27.0 to 0.29.0.
packages/extension/public/locales/en/translation.json Added new localization keys for NFT functionalities and modified existing ones.
packages/extension/src/packageInfo.ts Updated version property from '0.27.0' to '0.29.0'.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FullScreenAccountMenu.tsx Changed borderColor in Popover component's PaperProps styling.
packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountInformationForDetails.tsx Adjusted font sizes for Price and BalanceRow components to 21px.
packages/extension-polkagate/src/fullscreen/accountDetails/components/TotalChart.tsx Reduced font sizes for "Total" label and FormatPrice component.
packages/extension-polkagate/src/fullscreen/governance/SupportUs.tsx Updated STORAGE_LABEL constant for simplified format.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx Changed font size for FormatPrice component to 21px.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx Adjusted font sizes for portfolio title and amount.
packages/extension-polkagate/src/components/FormatPrice.tsx Modified Skeleton component's sx prop and added variant='text'.
packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx Updated Typography color property for "Assets" label and adjusted border width for AssetsBoxes.
packages/extension-polkagate/src/fullscreen/accountDetails/components/LockedInReferendaFS.tsx Removed conditional margin-top from FormatPrice component.
packages/extension-polkagate/src/popup/home/AccountLabel.tsx Changed profile label styling from background color to border and adjusted font size.
packages/extension-polkagate/src/popup/staking/partial/ShowRoles.tsx Added optional chaining for pool properties and updated borderColor in styling.
packages/extension-polkagate/src/popup/account/AccountBrief.tsx Added useTheme hook for grayscale filter based on theme mode and updated Divider background color.
packages/extension-polkagate/src/popup/account/index.tsx Updated Divider and bottom Grid background color to secondary.light.
packages/extension-polkagate/src/popup/staking/solo/index.tsx Updated color properties to secondary.light and refined logic for displaying ToBeReleased.
packages/extension-polkagate/src/popup/home/YouHave.tsx Replaced previous toggle mechanism with HideBalance component for improved UI.
packages/extension-polkagate/src/components/SVG/HideBalance.tsx Introduced HideBalance component with ClosedEye and OpenEye SVG icons for balance visibility toggle.
packages/extension-polkagate/src/themes/baseTheme.ts Changed import statement for ThemeOptions to a type-only import.
packages/extension-polkagate/src/popup/history/partials/FailSuccessIcon.tsx Introduced AnimatedCheckIcon for animated success representation.
packages/extension-polkagate/src/fullscreen/governance/FullScreenHeader.tsx Changed borderBottomColor in Grid header styling.
packages/extension-polkagate/src/fullscreen/governance/partials/ThemeChanger.tsx Updated borderColor in Grid styling.
packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx Replaced HideNumbers component with HideBalance and adjusted layout.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/Currency.tsx Updated borderColor in Grid styling.
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FavoriteChains.tsx Introduced color variable for theme-based icon coloring and updated borderColor in Grid.
packages/extension-polkagate/src/partials/FullScreenChainSwitch.tsx Updated borderColor in button styling.
packages/extension-polkagate/src/partials/RemoteNodeSelectorWithSignals.tsx Changed borderColor in Grid styling for list indicators.

Possibly related PRs

  • refactor: utilize React memo to decrease unneeded re-renders #1554 - This PR focuses on refactoring the codebase to utilize React's memo functionality to decrease unnecessary re-renders. The changes in this PR could be related to the main PR, as they both aim to optimize rendering performance.
  • refactor: use FormatPrice component #1565 - This PR introduces refactoring to utilize the FormatPrice component, which is also used in the main PR. The changes in this PR could be related to the main PR's modifications to the TwoButtons component.
  • fix: user added chains price id #1571 - This PR addresses an issue with user-added chains and their price IDs, which could be related to the main PR's changes in the TwoButtons component, as it involves handling chain-specific data.

Suggested labels

new feature

🐰 In the land of code where changes bloom,
Buttons and colors find their room.
With sizes adjusted, the visuals align,
PolkaGate shines, oh how divine!
From fonts to borders, all in a dance,
A whimsical update, give it a chance! 🌼

Warning

Rate limit exceeded

@Nick-1979 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8f2cab2 and 2d6c9da.


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 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: 0

🧹 Outside diff range and nitpick comments (11)
packages/extension-polkagate/src/components/TwoButtons.tsx (1)

Line range hint 1-89: Consider these architectural improvements.

  1. The absolute positioning (position: 'absolute') by default could cause layout issues. Consider making it optional or using a more flexible positioning strategy.
  2. For consistency with Material-UI, consider using CircularProgress instead of the third-party Circle component from 'better-react-spinkit'.
  3. The TODO comment about replacing ButtonWithCancel should be addressed to reduce technical debt.

Would you like me to help implement any of these suggestions?

packages/extension-polkagate/src/popup/home/ProfileTab.tsx (1)

93-94: Consider accessibility implications of low opacity in dark mode

While the opacity adjustment provides visual hierarchy, the 0.3 opacity value in dark mode might affect readability for some users. Consider:

  1. Using a higher opacity value (e.g., 0.5 or 0.6) to maintain better contrast
  2. Adding a transition property for smooth opacity changes
 my: '2px',
-opacity: isDarkMode ? (isContainerHovered || isSelected ? 1 : 0.3) : undefined
+opacity: isDarkMode ? (isContainerHovered || isSelected ? 1 : 0.5) : undefined,
+transition: 'opacity 0.2s ease-in-out'
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (2)

Line range hint 112-116: Consider improving dark mode opacity transition.

The opacity change in dark mode (0.3 to 1) could benefit from a smooth transition to match the existing transform transition.

Consider adding opacity to the transition property:

-          transition: 'transform 0.2s, box-shadow 0.2s',
+          transition: 'transform 0.2s, box-shadow 0.2s, opacity 0.2s',

This would create a more polished user experience by smoothly fading the opacity changes when hovering or selecting tabs in dark mode.


112-112: Consider consistent opacity behavior across themes.

Currently, the reduced opacity (0.3) for non-visible content only applies in dark mode. Consider applying a similar visual hierarchy in light mode for consistency, perhaps with a different opacity value that works better with the light theme.

-          opacity: isDarkMode && (visibleContent ? 1 : 0.3),
+          opacity: visibleContent ? 1 : (isDarkMode ? 0.3 : 0.6),
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (1)

68-68: Consider extracting width calculations into constants

The width calculations use multiple nested conditions which could impact maintainability. Consider extracting these values into named constants for better readability.

+const GRID_WIDTHS = {
+  WITH_CHECKBOX: '29%',
+  ONE_ROW: '50%',
+  FULL: '100%'
+} as const;
+
 <Grid container fontSize='14px' item 
-  maxWidth={showCheckbox ? '29%' : allInOneRow ? '50%' : '100%'}
+  maxWidth={showCheckbox ? GRID_WIDTHS.WITH_CHECKBOX : allInOneRow ? GRID_WIDTHS.ONE_ROW : GRID_WIDTHS.FULL}
   textAlign='left' 
   width={allInOneRow ? 'fit-content' : '100%'}>
packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx (2)

41-63: Consider adding ARIA labels for accessibility

The QuickActionButton component is well-structured and follows good practices for component composition. However, consider enhancing accessibility by adding aria-labels.

 <Grid alignItems='center' container direction='column' display='flex' item justifyContent='center' 
-  onClick={!disabled ? onClick : noop} 
+  onClick={!disabled ? onClick : noop}
+  role="button"
+  aria-disabled={disabled}
+  aria-label={title}
   sx={{ '&:hover': { bgcolor: disabled ? 'transparent' : 'divider' }, borderRadius: '5px', cursor: disabled ? 'default' : 'pointer', minWidth: '80px', p: '0 5px', width: 'fit-content' }}>

100-100: Consider using theme variables for border color

The hardcoded color value '#74747475' might break theme consistency. Consider using theme variables for better maintainability and consistency with the theme system.

-borderColor: '#74747475',
+borderColor: theme.palette.mode === 'dark' ? 'rgba(116, 116, 116, 0.46)' : theme.palette.divider,
packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx (1)

Line range hint 36-275: Consider theme-specific style adjustments

While the component uses MUI theming which supports dark mode, consider adding theme-specific style adjustments for better contrast and readability in dark mode, especially for:

  • Input fields background and text colors
  • Checkbox contrast and hover states
  • Modal backdrop opacity

Consider extracting theme-specific styles into a separate theme configuration file for better maintainability and consistency across the application.

packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx (1)

193-194: Consider using theme-aware colors for row highlighting

The selected row background color is currently hard-coded to rgba(153, 0, 79, 0.4). Consider using MUI's theme system for better dark theme support.

-              <Grid container item key={index} sx={{ '> :last-child': { border: 'none' }, bgcolor: index === myIndex ? 'rgba(153, 0, 79, 0.4)' : 'transparent', borderBottom: '1px solid', borderBottomColor: 'secondary.light', lineHeight: '40px' }}>
+              <Grid container item key={index} sx={{ '> :last-child': { border: 'none' }, bgcolor: index === myIndex ? 'action.selected' : 'transparent', borderBottom: '1px solid', borderBottomColor: 'secondary.light', lineHeight: '40px' }}>

Also applies to: 197-197

packages/extension/public/locales/en/translation.json (2)

1427-1429: Maintain consistent terminology between NFT and Unique.

The translations alternate between using "NFT" and "Unique" in the keys. While this might be intentional to support different blockchain terminology, consider adding a comment or documentation to explain the distinction to future maintainers.


1443-1445: Consider adding tooltips for action buttons.

While the basic actions are translated, consider adding tooltip translations to provide more context for actions like "View in Full Screen" or "View on".

Example addition:

+"View in Full Screen tooltip": "Click to view the NFT in full screen mode",
+"View on tooltip": "Click to view the NFT on the blockchain explorer"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 860e98f and 27e4ed3.

⛔ Files ignored due to path filters (2)
  • packages/extension-polkagate/src/assets/icons/stars5White.svg is excluded by !**/*.svg
  • packages/extension-polkagate/src/assets/icons/stars6White.svg is excluded by !**/*.svg
📒 Files selected for processing (19)
  • packages/extension-polkagate/src/components/TwoButtons.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountBodyFs.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountItem.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/HomeMenu.tsx (5 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/partials/ValidatorsTableFS.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/Asset.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/QuickAction.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/home/ProfileTab.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/staking/partial/Filters.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/staking/partial/ShowPool.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx (6 hunks)
  • packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx (7 hunks)
  • packages/extension-polkagate/src/themes/dark.ts (1 hunks)
  • packages/extension/package.json (1 hunks)
  • packages/extension/public/locales/en/translation.json (1 hunks)
  • packages/extension/src/packageInfo.ts (1 hunks)
✅ Files skipped from review due to trivial changes (8)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountItem.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/HomeMenu.tsx
  • packages/extension-polkagate/src/fullscreen/stake/solo/partials/ValidatorsTableFS.tsx
  • packages/extension-polkagate/src/partials/Asset.tsx
  • packages/extension-polkagate/src/partials/QuickAction.tsx
  • packages/extension-polkagate/src/popup/staking/partial/ShowPool.tsx
  • packages/extension/package.json
  • packages/extension/src/packageInfo.ts
🔇 Additional comments (26)
packages/extension-polkagate/src/themes/dark.ts (2)

Line range hint 11-23: LGTM! Well-structured palette interface extensions.

The new palette properties are well-organized with clear, semantic naming and consistent typing patterns. The separation between required (Palette) and optional (PaletteOptions) properties is properly maintained.


35-35: Verify contrast ratios for the new secondary.light color.

The new color #8D94A4 appears to align well with the minimal dark theme aesthetic. However, please ensure it meets WCAG accessibility guidelines for contrast ratios, especially when used with text or important UI elements.

Run this script to analyze the color contrast:

packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountBodyFs.tsx (2)

23-23: LGTM: Icon size adjustment aligns with theme updates

The reduction in icon height contributes to a more minimal visual design while maintaining the component's functionality.


69-72: LGTM: Consistent icon sizing implementation

The addition of the iconWidth prop with a value of 15 maintains visual consistency with other icon size adjustments in the theme update.

packages/extension-polkagate/src/components/TwoButtons.tsx (1)

42-43: LGTM! Style changes align with dark theme implementation.

The changes to the secondary button's styling create better visual hierarchy:

  • Using secondary.light for border color provides softer emphasis
  • Conditional text color for text variant maintains button's visibility in dark mode
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (1)

58-58: LGTM: Theme-consistent border color update

The border color change from secondary.main to secondary.light aligns well with the minimal dark theme objectives. The conditional styling maintains the component's adaptability.

packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx (3)

14-15: LGTM: Clean import of noop utility

Good practice using noop for handling disabled button states.


90-90: LGTM: Improved type safety

Good addition of explicit String conversion for consistent URL handling.


185-187: LGTM: Proper theme-aware styling

Good implementation of theme-aware styling with proper dark/light mode handling.

packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx (4)

148-148: LGTM: Appropriate color adjustment for dark theme

The change from secondary.main to secondary.light for the Divider's background color is appropriate for dark theme implementation, providing better visibility while maintaining visual hierarchy.


270-270: Verify padding removal impact

Setting px={0} removes horizontal padding from the modal. While this might be intentional for the dark theme, consider if this affects content readability and spacing aesthetics.

Consider using a small padding value (e.g., px={1}) to maintain content breathing room while achieving the minimal look.

✅ Verification successful

The previous command failed because tsx extension wasn't recognized. Let's try a broader search to understand the DraggableModal usage patterns and its component definition to verify if zero padding is consistent with its design.


Setting px={0} is consistent with other modal instances

The DraggableModal component has a default padding of px={4}, but there's a consistent pattern of using px={0} in similar filter and validator info modals across the codebase:

  • packages/extension-polkagate/src/popup/staking/partial/Filters.tsx
  • packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx
  • packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx

This appears to be an intentional design choice for these specific modal types rather than a dark theme consideration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent padding usage in other DraggableModal instances
rg "DraggableModal.*px\s*=\s*{0}" --type tsx

Length of output: 74


Script:

#!/bin/bash
# Search for DraggableModal usage patterns with px prop
rg "DraggableModal.*px.*=" -A 2

# Also check the DraggableModal component definition to understand default padding
fd -e tsx -e ts DraggableModal --exec cat {}

Length of output: 7619


6-6: Verify type imports usage

The import statement has been moved from comments to active code. While this is good practice, let's verify these types are being used properly in the component.

✅ Verification successful

Types are correctly used in the component

The imported types PoolFilter, PoolInfo, and StakingConsts are actively used throughout the component:

  • PoolInfo is used in props for pools array and filtered pools state
  • PoolFilter is used for filters state and in onFilters callback
  • StakingConsts is used in props for staking constants

The import statement is necessary and properly utilized, not just commented code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these types are used properly in the component
ast-grep --pattern 'type { PoolFilter, PoolInfo, StakingConsts }'

Length of output: 76816


Script:

#!/bin/bash
# Check if these types are used in the component
rg "PoolFilter|PoolInfo|StakingConsts" "packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx"

Length of output: 647


144-144: LGTM: Clean type assertions removal

The removal of explicit t<string> type assertions is a good cleanup, though unrelated to the dark theme implementation. TypeScript can correctly infer these types.

Also applies to: 152-152, 160-160, 185-185, 210-210, 245-245, 246-246

✅ Verification successful

Based on the rg search results, I can see that there are still many instances of t<string> type assertions throughout the codebase. However, the review comment specifically refers to removing these assertions from the file packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx and related lines.

Let me verify if those specific assertions were actually removed from the target file:


Looking at the file content, I can confirm that there are no t<string> type assertions in the code. All translations are using the t() function without explicit type assertions, which matches the review comment's observation about their removal.

LGTM: Type assertions removal verified

The code shows clean usage of the translation function without explicit t<string> type assertions, allowing TypeScript to correctly infer the return types. This change improves code cleanliness while maintaining type safety.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining t<string> type assertions that could be cleaned up
rg "t<string>" --type ts

Length of output: 76816


Script:

#!/bin/bash
# Check the specific file for t<string> assertions
cat packages/extension-polkagate/src/popup/staking/pool/stake/joinPool/partials/Filters.tsx

Length of output: 10336

packages/extension-polkagate/src/popup/staking/partial/Filters.tsx (6)

151-151: LGTM!

The translation function update is safe and maintains the component's functionality.


155-155: LGTM!

The divider color change to secondary.light aligns with the dark theme implementation and maintains visual consistency with other components.


158-158: LGTM!

The translation function updates across checkbox labels maintain consistency and functionality.

Also applies to: 164-164, 170-170, 177-177, 183-183, 206-206


242-243: LGTM!

The button text translation updates maintain consistency with other translation changes.


256-256: LGTM!

The CloseIcon size reduction maintains visual consistency with other components in the dark theme.


263-263: Verify the modal padding in fullscreen mode.

Setting px={0} removes horizontal padding in fullscreen mode. Please ensure this doesn't cause the content to look cramped or touch the screen edges.

Consider adding a small padding (e.g., px={1}) if the content appears too close to the edges in fullscreen mode.

packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx (3)

76-77: LGTM: Proper theme integration for validator information container

The border color change to secondary.light is consistent with the dark theme styling approach and properly uses MUI theming variables.


172-181: LGTM: Consistent table header styling

The border color changes maintain visual consistency throughout the table header section, properly utilizing MUI's Grid system and theme variables.


222-222: LGTM: Refined header styling and close button adjustments

The changes to the title border color and close button (position and size) improve the visual balance while maintaining theme consistency.

Also applies to: 235-235, 238-238

packages/extension/public/locales/en/translation.json (4)

1430-1439: LGTM: NFT metadata fields are well-structured.

The metadata fields cover all essential NFT information including collection details, identifiers, ownership, and network information.


1439-1443: LGTM: Media type translations are comprehensive.

The translations properly cover various media types (Image, Animation, Audio, Media) that NFTs might contain.


1446-1448: LGTM: Status messages are user-friendly.

The empty state and loading state messages are clear and informative.


1449-1452: LGTM: Feature support and instructions are well explained.

The translations provide clear messaging about blockchain support and user instructions. The error message for failed fetching is also properly included.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF November 10, 2024 10:00
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3db58c8 and 32bf859.

📒 Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FullScreenAccountMenu.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/WatchList.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FullScreenAccountMenu.tsx
🔇 Additional comments (2)
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/WatchList.tsx (2)

26-26: LGTM: Improved price change handling

Good improvement in handling the absence of price data by using undefined instead of defaulting to 0. This change more accurately represents the state when price data is unavailable and enables better conditional rendering.


58-58: LGTM: Minor stylistic change

The function declaration style change is consistent with modern React patterns while maintaining the same functionality.

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: 0

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/fullscreen/governance/SupportUs.tsx (1)

Line range hint 91-117: Consider improving error handling and code organization.

The address calculation logic could benefit from several improvements:

  1. Extract the max voting power calculation into a separate utility function
  2. Add proper error handling instead of just logging to console
  3. Add loading states while calculating voting power
  4. Handle edge cases where voting power calculation fails

Consider refactoring the effect like this:

+ const calculateMaxVotingPowerAddress = (balances: Record<string, any>): string | undefined => {
+   let addressWithMaxVotingPower: string | undefined;
+   let max = BN_ZERO;
+
+   Object.keys(balances).forEach((address) => {
+     const maybeAsset = balances[address]?.[POLKADOT_GENESIS_HASH];
+     if (!maybeAsset) {
+       return;
+     }
+     const votingBalance = maybeAsset[0].votingBalance ? new BN(maybeAsset[0].votingBalance) : BN_ZERO;
+     if (votingBalance.gt(max)) {
+       max = votingBalance;
+       addressWithMaxVotingPower = address;
+     }
+   });
+
+   return addressWithMaxVotingPower;
+ };

  useEffect(() => {
+   const [isLoading, setIsLoading] = useState(false);
+   const [error, setError] = useState<Error>();

    if (!accountsAssets) {
      return;
    }

+   setIsLoading(true);
+   setError(undefined);

    const balances = accountsAssets.balances;
-   let addressWithMaxVotingPower: string | undefined;
-   let max = BN_ZERO;
-
-   Object.keys(balances).forEach((address) => {
-     const maybeAsset = balances[address]?.[POLKADOT_GENESIS_HASH];
-     if (!maybeAsset) {
-       return;
-     }
-     const votingBalance = maybeAsset[0].votingBalance ? new BN(maybeAsset[0].votingBalance) : BN_ZERO;
-     if (votingBalance.gt(max)) {
-       max = votingBalance;
-       addressWithMaxVotingPower = address;
-     }
-   });
+   const addressWithMaxVotingPower = calculateMaxVotingPowerAddress(balances);

    addressWithMaxVotingPower && tieAccount(addressWithMaxVotingPower, POLKADOT_GENESIS_HASH)
      .then(() => {
        setAddress(addressWithMaxVotingPower);
+       setIsLoading(false);
      })
      .catch((error) => {
-       console.error(error);
+       setError(error);
+       setIsLoading(false);
      });
  }, [accountsAssets]);

Then handle the loading and error states in the UI:

{isLoading && <CircularProgress />}
{error && (
  <Typography color="error">
    Failed to calculate voting power: {error.message}
  </Typography>
)}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9ad1c74 and a06d4fe.

📒 Files selected for processing (9)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountInformationForDetails.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/TotalChart.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/SupportUs.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountBodyFs.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (2 hunks)
  • packages/extension/package.json (1 hunks)
  • packages/extension/public/locales/en/translation.json (1 hunks)
  • packages/extension/src/packageInfo.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/TotalChart.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountBodyFs.tsx
  • packages/extension/package.json
  • packages/extension/public/locales/en/translation.json
  • packages/extension/src/packageInfo.ts
🔇 Additional comments (5)
packages/extension-polkagate/src/fullscreen/governance/SupportUs.tsx (1)

22-22: Verify the storage key format change impact.

The storage key format has been simplified from supportUs0000_${PROPOSAL_NO} to supportUs_${PROPOSAL_NO}. This change will cause the support modal to reappear for users who have previously dismissed it.

Run the following script to check for any other usages of the old storage key format:

✅ Verification successful

Storage key format change verified successfully.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other occurrences of the old storage key format
# to ensure consistent updates across the codebase

rg -l "supportUs0000_" 

Length of output: 22

packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountInformationForDetails.tsx (2)

35-35: LGTM: Font size adjustment aligns with theme standardization.

The reduction in font size from '28px' to '21px' helps create a more consistent visual hierarchy across the dark theme implementation.


81-81: LGTM: Consistent font size standardization.

The font size adjustment to '21px' maintains visual consistency with the Price component, creating a harmonious balance between price and balance displays.

packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (2)

214-216: LGTM: Font size adjustment maintains readability

The font size reduction from 22px to 21px for the portfolio title maintains readability while contributing to the visual consistency across components.


Line range hint 227-231: LGTM: Portfolio amount styling preserves visual hierarchy

The font size adjustment from 30px to 28px for the portfolio amount maintains proper visual hierarchy while aligning with the overall theme standardization.

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: 0

🧹 Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/components/FormatPrice.tsx (1)

111-112: LGTM! Consider minor improvements for consistency.

The Skeleton styling changes look good and align with the dark theme implementation. Consider these optional improvements:

 <Skeleton
   animation='wave'
   height={skeletonHeight}
-  sx={{ fontWeight: 'bold', transform: 'none', width }}
+  sx={{ fontWeight: 'bold', transform: 'none', width, display: 'block' }}
   variant='text'
 />

Additionally, consider making the animation configurable via props for more flexibility:

interface Props {
  // ... existing props
  skeletonAnimation?: 'pulse' | 'wave' | false;
}
packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (1)

Line range hint 89-93: Consider enhancing theme consistency for shadows and typography.

While the current implementation works well, consider these future improvements for better dark theme support:

  1. Make box shadow color theme-aware instead of using fixed #00000040
  2. Explicitly set theme colors for typography elements to ensure consistent contrast

Example improvement:

 boxShadow: isAssetSelected
-  ? '0px 2px 5px 2px #00000040'
+  ? `0px 2px 5px 2px ${alpha(theme.palette.common.black, 0.25)}`
   : 'none',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a06d4fe and ca23d50.

📒 Files selected for processing (4)
  • packages/extension-polkagate/src/components/FormatPrice.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountInformationForDetails.tsx (3 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountInformationForDetails.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx
🔇 Additional comments (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (1)

142-142: LGTM! Color change aligns with dark theme implementation.

The addition of color='secondary.contrastText' to the Typography component follows Material-UI theming best practices by using theme palette colors, ensuring proper contrast in both light and dark modes.

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: 0

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/popup/home/AccountLabel.tsx (1)

Line range hint 122-129: Consider standardizing font sizes for better consistency.

The scroll container uses fontSize: '10px' while the profile labels use fontSize: '11px'. Consider standardizing these values for better maintainability.

- fontSize: '11px',
+ fontSize: '10px', // Match the container's font size
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0cf02d7 and 1cadcbb.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/popup/home/AccountLabel.tsx (1 hunks)
🔇 Additional comments (1)
packages/extension-polkagate/src/popup/home/AccountLabel.tsx (1)

122-123: LGTM! Border styling aligns with dark theme objectives.

The change from background color to border styling provides a more subtle and elegant visual representation of profile labels, which aligns well with a minimal dark theme approach.

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

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/popup/staking/partial/ShowRoles.tsx (1)

Line range hint 48-52: LGTM! Improved null safety with optional chaining.

The addition of optional chaining and null coalescing operators makes the code more robust against undefined values.

Consider extracting the 'N/A' string to a constant or i18n translation:

- { address: maybeCommissionAddress?.toString() ?? 'N/A', label: t<string>('Com. id') }
+ { address: maybeCommissionAddress?.toString() ?? t<string>('N/A'), label: t<string>('Com. id') }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1cadcbb and c397b68.

📒 Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/staking/partial/ShowRoles.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AOC.tsx
🔇 Additional comments (2)
packages/extension-polkagate/src/popup/staking/partial/ShowRoles.tsx (2)

30-30: LGTM! Props interface and function signature are well-defined.

The function signature is properly typed with a clear Props interface.


72-72: LGTM! Identity component props are well-defined.

The Identity component usage is properly configured with appropriate styling and required props.

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: 0

🧹 Outside diff range and nitpick comments (26)
packages/extension-polkagate/src/popup/import/importLedger/LedgerOptions.tsx (3)

13-13: Consider relocating the Title component to a shared components directory.

The Title component is currently imported from a SendFund feature directory but appears to be a generic UI component. Consider moving it to a shared/common components directory for better modularity and reusability.


38-44: Consider using responsive height for the Title component.

The fixed height of '85px' might not scale well across different screen sizes. Consider using relative units (rem/em) or making the height responsive based on content.

-          height='85px'
+          height='auto'
+          minHeight='5.3rem'

Line range hint 45-59: Consider adding security attributes to the external link.

The link to the Metadata Dashboard should include security-related attributes to protect against potential security vulnerabilities.

             <a
               href={METADATA_DASHBOARD}
               rel='noreferrer'
+              rel='noreferrer noopener'
               target='_blank'
             >
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (1)

Line range hint 1-150: Consider future architectural improvements.

While outside the scope of this styling PR, here are some suggestions for future improvements:

  1. Consider extracting the visibility logic into a custom hook
  2. Move inline styles to the sx prop for consistency
  3. Consider breaking down the component into smaller, more focused sub-components

These changes would improve maintainability while preserving the current functionality and styling.

packages/extension-polkagate/src/fullscreen/stake/solo/partials/ActiveValidators.tsx (2)

Line range hint 115-124: Consider improving skeleton loading implementation.

The skeleton loading implementation could benefit from some refinements:

  1. Extract the width calculation logic
  2. Add accessibility attributes

Consider applying these improvements:

+ const getSkeletonWidth = (index: number): string => `${100 / (SKELETON_COUNT - index)}%`;

  Array.from({ length: SKELETON_COUNT }, (_, index) => (
    <Grid container key={index}>
      <Skeleton
        animation='wave'
        height='20px'
        sx={{ display: 'inline-block', fontWeight: 'bold', my: '5px', transform: 'none', 
-         width: `${100 / (SKELETON_COUNT - index)}%` }}
+         width: getSkeletonWidth(index) }}
+       aria-label={`Loading validator ${index + 1} of ${SKELETON_COUNT}`}
      />
    </Grid>
  ))

Line range hint 26-33: Consider component composition for better maintainability.

While the current implementation is functional, the component handles multiple responsibilities (active validators, non-active validators, loading states). Consider splitting this into smaller, focused components:

  • ValidatorsList - Core list rendering
  • ValidatorsLoadingState - Skeleton loading
  • NonActiveValidatorsSection - Collapsible section

This would improve maintainability and testing without sacrificing the current functionality.

packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (2)

16-16: Consider relocating the Title component to a shared UI components directory.

The Title component is currently imported from a feature-specific path (sendFund/InputPage). Since it's being reused across different features, consider moving it to a shared UI components directory for better maintainability and component discovery.


106-112: Consider making the Title component height responsive.

The fixed height of '85px' might not adapt well to different screen sizes. Consider using relative units or making the height responsive based on viewport size.

-            height='85px'
+            height='min(85px, 10vh)'
packages/extension-polkagate/src/popup/newAccount/createAccountFullScreen/index.tsx (3)

10-10: Consider relocating shared components to a common directory.

The Title component is imported from the sendFund module but appears to be a generic UI component. Consider moving it to a shared components directory for better maintainability and reusability.


113-119: Consider using theme-based or relative units for height.

The hardcoded height of '85px' might not scale well across different screen sizes or themes. Consider using theme-based spacing units or relative units for better responsiveness.

 <Title
-  height='85px'
+  height='auto'
+  sx={{ minHeight: theme.spacing(10) }}
   logo={
     <VaadinIcon icon='vaadin:plus-circle' style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }} />
   }
   text={t('Create a new account')}
 />

Enhance password validation in createAccountFullScreen/index.tsx.

The reviewed component does not implement robust password validation. Please ensure that passwords meet security requirements, such as minimum length, complexity, and protection against common vulnerabilities.

🔗 Analysis chain

Line range hint 41-119: Enhance security measures for sensitive operations.

The component handles critical security operations. Consider implementing these security enhancements:

  1. Clear sensitive data (seed, password) from state when component unmounts
  2. Strengthen password requirements (currently only checks for length > 5)
  3. Add a warning about secure environment when displaying seed phrase

Let's verify the password validation implementation across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for password validation patterns
rg -A 3 'password.*length|password.*validation|password.*check' --type typescript

Length of output: 118


Script:

#!/bin/bash
# Search for password validation patterns in TypeScript files
rg -A 3 'password.*length|password.*validation|password.*check' --type ts --type tsx

Length of output: 114


Script:

#!/bin/bash
# Search for password validation patterns in .ts and .tsx files
rg -A 3 'password.*length|password.*validation|password.*check' -g '*.ts' -g '*.tsx'

Length of output: 2004

packages/extension-polkagate/src/popup/import/importLedger/MigrationApp.tsx (2)

14-14: Consider relocating the Title component to a shared components directory.

The Title component appears to be a reusable UI element, but it's currently imported from a feature-specific path (sendFund/InputPage). Consider moving it to a shared/common UI components directory to improve maintainability and reusability.


103-109: Consider making the Title component more responsive.

The Title component implementation looks clean, but the hardcoded height of '85px' might affect responsiveness on different screen sizes. Consider:

  • Using relative units (rem/em) or theme-based spacing
  • Making the height responsive based on viewport size
 <Title
-  height='85px'
+  height='auto'
+  sx={{ minHeight: { xs: '60px', sm: '85px' } }}
   logo={
     <VaadinIcon icon='vaadin:automation' style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }} />
   }
   text={t('Ledger Account Migration')}
 />
packages/extension-polkagate/src/popup/import/attachQrFullScreen/index.tsx (2)

125-131: Consider making dimensions more responsive and maintainable

The Title component implementation looks good, but consider these improvements:

  1. The fixed height of '85px' could be responsive for better adaptability across screen sizes
  2. The icon size ('25px') could be defined in theme constants for consistency

Consider this refactor:

 <Title
-  height='85px'
+  height='min(85px, 10vh)'
   logo={
     <VaadinIcon
-      icon='vaadin:qrcode'
-      style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }}
+      icon='vaadin:qrcode'
+      style={{
+        color: theme.palette.text.primary,
+        height: theme.spacing(3),
+        width: theme.spacing(3)
+      }}
     />
   }
   text={t('Attach QR-signer')}
 />

Line range hint 1-199: Consider enhancing error handling and user feedback

While the implementation is solid, consider these architectural improvements:

  1. Add loading state feedback during QR scanning
  2. Implement more detailed error messages for different failure scenarios
  3. Add retry mechanism for failed QR scans

Consider implementing a custom hook for QR scanning that includes these enhancements:

// useQrScanner.ts
interface QrScannerState {
  isScanning: boolean;
  error: Error | null;
  retryCount: number;
}

const useQrScanner = (onScan: (data: ScanType) => void) => {
  const [state, setState] = useState<QrScannerState>({
    isScanning: false,
    error: null,
    retryCount: 0
  });

  const handleScan = useCallback((data: ScanType) => {
    setState(prev => ({ ...prev, isScanning: false }));
    onScan(data);
  }, [onScan]);

  const handleError = useCallback((error: Error) => {
    setState(prev => ({
      ...prev,
      error,
      isScanning: false,
      retryCount: prev.retryCount + 1
    }));
  }, []);

  return { ...state, handleScan, handleError };
};
packages/extension-polkagate/src/popup/import/importLedger/LegacyApps.tsx (2)

16-16: Consider moving the Title component to a shared components directory.

The Title component is imported from a feature-specific path (sendFund/InputPage) but is being reused across different features. Consider moving it to a shared/common components directory to improve code organization and maintainability.


97-103: LGTM! Consider extracting icon size to theme constants.

The Title component usage improves code modularity and maintains consistent styling. However, the icon dimensions (25px) could be moved to theme constants for better maintainability.

Consider extracting the icon size to theme constants:

-<VaadinIcon icon='vaadin:form' style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }} />
+<VaadinIcon icon='vaadin:form' style={{ color: `${theme.palette.text.primary}`, height: theme.spacing(3.125), width: theme.spacing(3.125) }} />
packages/extension-polkagate/src/popup/import/importRawSeedFullScreen/index.tsx (3)

15-15: Consider relocating the Title component to a shared components directory.

The Title component is currently imported from the sendFund/InputPage directory, which suggests it's a reusable component. Consider moving it to a shared components directory for better code organization and reusability.


154-160: Consider using theme-based spacing and consistent icon sizing.

While the Title component implementation is clean, consider:

  1. Using theme-based spacing instead of hardcoded '100px' height
  2. Moving icon dimensions to a constants file or theme for consistency across the application
 <Title
-  height='100px'
+  height={theme.spacing(12.5)} // or use a theme-based variable
   logo={
     <VaadinIcon
-      icon='vaadin:book-dollar'
-      style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }}
+      icon='vaadin:book-dollar'
+      style={{ color: theme.palette.text.primary, height: theme.iconSizes.medium, width: theme.iconSizes.medium }}
     />
   }
   text={t('Import from raw seed')}
 />

Line range hint 137-141: Enhance security for sensitive data handling.

The pasteSeed function handles sensitive cryptographic material through the clipboard, which poses security risks:

  1. The clipboard content remains accessible to other applications
  2. No warning is shown about clipboard security risks
  3. No automatic clipboard clearing

Consider implementing these security enhancements:

 const pasteSeed = useCallback(() => {
+  const warningText = t('Warning: Using clipboard for sensitive data poses security risks. Clear your clipboard after pasting.');
+  if (!window.confirm(warningText)) return;
+
   navigator.clipboard.readText().then((clipText) => {
     setSeed(clipText);
+    // Clear clipboard after a delay
+    setTimeout(() => {
+      navigator.clipboard.writeText('').catch(console.error);
+    }, 1000);
   }).catch(console.error);
 }, []);

Also consider adding a visible warning message about clipboard security risks near the paste button.

packages/extension-polkagate/src/popup/import/importSeedFullScreen/index.tsx (2)

Line range hint 171-182: Enhance security for seed phrase handling

The clipboard paste functionality for seed phrases could benefit from additional security measures:

  1. Add a warning about clipboard security risks
  2. Clear clipboard after successful paste
  3. Add input sanitization before processing the seed phrase

Consider implementing these security enhancements:

 const pasteSeed = useCallback(() => {
+  const sanitizeSeed = (input: string) => input.trim().replace(/\s+/g, ' ');
   navigator.clipboard.readText().then((clipText) => {
-    setSeed(clipText);
+    const sanitizedSeed = sanitizeSeed(clipText);
+    setSeed(sanitizedSeed);
+    // Clear clipboard after short delay
+    setTimeout(() => {
+      navigator.clipboard.writeText('').catch(console.error);
+    }, 1000);
   }).catch(console.error);
 }, []);

Also, consider adding a warning message:

 <TextAreaWithLabel
   fontSize='18px'
   height='70px'
   isError={!!error}
   isFocused
   label={t<string>('Existing 12 or 24-word recovery phrase')}
+  helperText={t<string>('Warning: Using clipboard for seed phrases may expose them to security risks')}
   onChange={setSeed}
   rowsCount={2}
   style={{ width: '100%' }}
   value={seed || ''}
 />

Line range hint 248-253: Strengthen password requirements

The current password validation only requires more than 5 characters, which may be insufficient for securing sensitive wallet data. Consider implementing stronger password requirements.

Enhance password validation by requiring:

  • Minimum length of 8 characters
  • At least one uppercase letter
  • At least one number
  • At least one special character

Example implementation:

 <Passwords2
   firstPassStyle={{ marginBlock: '10px' }}
-  label={t<string>('Password for this account (more than 5 characters)')}
+  label={t<string>('Password for this account (min 8 chars, including uppercase, number, and special char)')}
   onChange={onPassChange}
+  validatePassword={(pass) => {
+    if (pass.length < 8) return t('Password must be at least 8 characters');
+    if (!/[A-Z]/.test(pass)) return t('Include at least one uppercase letter');
+    if (!/[0-9]/.test(pass)) return t('Include at least one number');
+    if (!/[!@#$%^&*]/.test(pass)) return t('Include at least one special character');
+    return null;
+  }}
   onEnter={password && name && !error && !!seed ? onCreate : () => null}
 />
packages/extension-polkagate/src/popup/import/importLedger/GenericApp.tsx (2)

13-13: Consider relocating the Title component to a shared UI components directory.

The Title component seems to be a generic UI component, but it's currently located in the sendFund/InputPage directory. Consider moving it to a more appropriate location like src/components/common or src/components/ui to improve code organization and reusability.


205-211: Consider making the Title component height more flexible.

The height is hardcoded to '85px'. Consider making it more flexible by:

  1. Making the height prop optional with a default value
  2. Using min-height instead of fixed height
  3. Allowing the component to adapt to its content

This would make the component more reusable across different contexts.

 <Title
-  height='85px'
+  height='min-content'
   logo={
     <VaadinIcon icon='vaadin:file-tree' style={{ color: `${theme.palette.text.primary}`, height: '25px', width: '25px' }} />
   }
   text={t('Ledger Polkadot Generic')}
 />
packages/extension-polkagate/src/popup/import/restoreJSONFullScreen/index.tsx (1)

196-202: Verify theme compatibility and user experience.

Since this is part of a dark theme implementation and handles critical account restoration functionality:

  1. The icon color uses theme.palette.text.primary which is good for theme compatibility
  2. Consider adding a tooltip or aria-label to the icon for better accessibility
  3. Ensure the title remains clearly visible in both light and dark themes

Consider enhancing the Title component to include:

interface TitleProps {
  height: string;
  logo: React.ReactNode;
  text: string;
  tooltip?: string;  // For better UX
  'aria-label'?: string;  // For accessibility
}
packages/extension-polkagate/src/fullscreen/sendFund/InputPage.tsx (1)

Line range hint 103-600: Consider breaking down the component for better maintainability

While the current implementation works well, the component handles multiple complex responsibilities. Consider these architectural improvements:

  1. Extract fee calculation logic into a custom hook (e.g., useTransferFee)
  2. Move transfer type handling into a separate component
  3. Create a dedicated validation hook for balance and address checks

This would improve code organization, testability, and maintainability.

Example structure:

// hooks/useTransferFee.ts
export function useTransferFee(params: TransferFeeParams) {
  // Extract fee calculation logic here
}

// components/TransferTypeSelector.tsx
export function TransferTypeSelector(props: TransferTypeSelectorProps) {
  // Extract transfer type UI and logic here
}

// hooks/useTransferValidation.ts
export function useTransferValidation(params: ValidationParams) {
  // Extract validation logic here
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c397b68 and 6d1d608.

📒 Files selected for processing (30)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/addNewChain/index.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ImportAccSubMenuFullScreen.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/manageProxies/Manage.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/manageProxies/Review.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/sendFund/InputPage.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/index.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/pool/PoolStaked.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/pool/commonTasks/manageValidators/index.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/pool/index.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/pool/partials/PoolCommonTasks.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/StakedSolo.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/index.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/partials/ActiveValidators.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/ImportAccSubMenu.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/home/ProfileTab.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/attachQrFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/importLedger/GenericApp.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/importLedger/LedgerOptions.tsx (3 hunks)
  • packages/extension-polkagate/src/popup/import/importLedger/LegacyApps.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/importLedger/MigrationApp.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/importProxiedFullScreen/index.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/import/importRawSeedFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/importSeedFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/import/restoreJSONFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/newAccount/createAccountFullScreen/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/newAccount/deriveFromAccountsFullscreen/index.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/staking/pool/index.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (13)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx
  • packages/extension-polkagate/src/fullscreen/addNewChain/index.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ImportAccSubMenuFullScreen.tsx
  • packages/extension-polkagate/src/fullscreen/manageProxies/Review.tsx
  • packages/extension-polkagate/src/fullscreen/stake/index.tsx
  • packages/extension-polkagate/src/fullscreen/stake/pool/PoolStaked.tsx
  • packages/extension-polkagate/src/fullscreen/stake/pool/commonTasks/manageValidators/index.tsx
  • packages/extension-polkagate/src/fullscreen/stake/pool/index.tsx
  • packages/extension-polkagate/src/fullscreen/stake/solo/StakedSolo.tsx
  • packages/extension-polkagate/src/fullscreen/stake/solo/index.tsx
  • packages/extension-polkagate/src/partials/ImportAccSubMenu.tsx
  • packages/extension-polkagate/src/popup/import/importProxiedFullScreen/index.tsx
  • packages/extension-polkagate/src/popup/newAccount/deriveFromAccountsFullscreen/index.tsx
🔇 Additional comments (17)
packages/extension-polkagate/src/popup/import/importLedger/LedgerOptions.tsx (1)

60-60: LGTM! Consistent icon styling and semantic choices.

The icon implementations show good consistency in:

  • Size (30px)
  • Theme integration
  • Semantic meaning (file-tree for Generic, automation for Migration, form for Legacy)

Also applies to: 66-66, 72-72

packages/extension-polkagate/src/popup/home/ProfileTab.tsx (2)

88-88: LGTM: Consistent style formatting

The border property formatting follows standard CSS conventions.


99-99: Verify text readability with static font weight

Changing from a dynamic font weight (500 when selected) to a static weight of 400 might impact visual hierarchy and readability, especially in dark mode.

packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (1)

124-124: LGTM: Typography weight adjustment aligns with minimal theme.

The change from conditional to fixed font weight (400) contributes to a more consistent and minimal visual appearance, which aligns well with the dark theme objectives. The regular weight maintains good readability while reducing visual noise.

packages/extension-polkagate/src/fullscreen/stake/solo/partials/ActiveValidators.tsx (1)

34-34: LGTM! The SKELETON_COUNT adjustment improves the loading state visualization.

The increase to 5 skeletons provides a better progressive width distribution for the loading placeholders, creating a more visually appealing loading state.

packages/extension-polkagate/src/popup/import/addWatchOnlyFullScreen/index.tsx (1)

106-112: Changes align well with the dark theme objectives.

The replacement of the Grid/Typography structure with the new Title component improves UI consistency while maintaining the component's functionality. The implementation is clean and doesn't introduce any breaking changes.

Also applies to: 16-16

packages/extension-polkagate/src/popup/newAccount/createAccountFullScreen/index.tsx (1)

Line range hint 1-119: Overall implementation looks good with room for improvements.

The component demonstrates good practices:

  • Proper error handling
  • Effective use of React hooks
  • Internationalization support
  • Clean UI organization with the new Title component

The suggested improvements above would further enhance security and maintainability.

packages/extension-polkagate/src/fullscreen/manageProxies/Manage.tsx (1)

122-122: LGTM: Font size adjustment maintains visual consistency.

The reduction in icon size from 23px to 20px aligns with similar adjustments made in other components, contributing to a more consistent visual hierarchy across the application.

packages/extension-polkagate/src/popup/import/attachQrFullScreen/index.tsx (1)

20-20: LGTM: Clean import statement

The Title component import is properly structured and follows the project's import conventions.

packages/extension-polkagate/src/popup/import/importSeedFullScreen/index.tsx (1)

16-16: LGTM: Improved component consistency

The refactoring to use the shared Title component and the adjusted icon sizing aligns with the application's visual hierarchy standards.

Also applies to: 151-157

packages/extension-polkagate/src/fullscreen/stake/pool/partials/PoolCommonTasks.tsx (2)

154-154: LGTM: Icon change aligns with styling objectives

The change from faHand to faHandDots is implemented consistently with the component's existing styling patterns and maintains proper state-based rendering.


6-6: LGTM: Import statement is properly organized

The faHandDots icon import is correctly added to the existing FontAwesome imports while maintaining proper organization.

packages/extension-polkagate/src/popup/import/importLedger/GenericApp.tsx (1)

Line range hint 1-300: Overall implementation looks solid!

The changes maintain the existing functionality while improving UI structure. The code demonstrates:

  • Proper error handling
  • Well-organized state management
  • Comprehensive TypeScript typing
  • Clear separation of concerns

The integration of the Title component is clean and maintains the existing functionality.

packages/extension-polkagate/src/popup/import/restoreJSONFullScreen/index.tsx (2)

15-15: LGTM: Good move towards component reusability.

The addition of the shared Title component import aligns with DRY principles and promotes consistent UI across the application.


196-202: Verify accessibility of the new Title component.

While the implementation looks clean, ensure that:

  1. The reduced icon size (25px) meets minimum touch target size requirements for mobile devices
  2. The color contrast ratio between the icon and background meets WCAG standards
packages/extension-polkagate/src/popup/staking/pool/index.tsx (1)

9-9: LGTM: Icon update is consistent with the dark theme changes

The replacement of faHand with faHandDots and its implementation are aligned with the visual updates across the application.

Also applies to: 359-359

packages/extension-polkagate/src/fullscreen/sendFund/InputPage.tsx (1)

80-80: LGTM: Visual refinements align with minimal theme

The reduction in icon and font sizes contributes to a more minimal visual presentation while maintaining readability.

Also applies to: 87-87

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: 0

🧹 Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/popup/account/AccountBrief.tsx (1)

86-86: Consider moving theme-specific styles to theme configuration

While the conditional styling works, consider moving the grayscale filter value to the theme configuration for better maintainability and consistency.

- sx={{ filter: theme.palette.mode === 'dark' ? 'grayscale(50)' : 'none' }}
+ sx={{ filter: theme.palette.mode === 'dark' ? theme.palette.icon.grayscale : 'none' }}

Add to your theme configuration:

declare module '@mui/material/styles' {
  interface Palette {
    icon: {
      grayscale: string;
    }
  }
}

// In theme configuration
palette: {
  icon: {
    grayscale: 'grayscale(50)'
  }
}
packages/extension-polkagate/src/popup/account/index.tsx (1)

249-249: LGTM: Consider extracting styles to a theme constant

The styling updates for the bottom navigation bar are consistent with the dark theme implementation. However, to improve maintainability and reusability, consider extracting these commonly used style values (like border colors and widths) into theme constants.

Example approach:

// In your theme configuration
const theme = {
  components: {
    NavigationBar: {
      styles: {
        container: {
          bgcolor: 'background.default',
          borderTop: '2px solid',
          borderTopColor: 'secondary.light',
          // ... other styles
        }
      }
    }
  }
}

Then in the component:

-<Grid container justifyContent='space-around' sx={{ bgcolor: 'background.default', borderTop: '2px solid', borderTopColor: 'secondary.light', bottom: 0, height: '62px', left: '4%', position: 'absolute', pt: '7px', pb: '5px', width: '92%' }}>
+<Grid container justifyContent='space-around' sx={(theme) => ({ ...theme.components.NavigationBar.styles.container, bottom: 0, height: '62px', left: '4%', position: 'absolute', pt: '7px', pb: '5px', width: '92%' })}>
packages/extension-polkagate/src/popup/staking/pool/index.tsx (1)

339-347: Consider standardizing icon dimensions

The icons have varying dimensions and styling approaches:

  • First icon: height 34px, width 40px with stroke
  • Second icon: using size='lg' property
  • Third and fourth icons: height 28px (from VaadinIcon)

Consider standardizing the icon sizes and styling approach across all menu items for better visual consistency.

- style={{ height: '34px', marginBottom: '-4px', stroke: `${theme.palette.text.primary}`, strokeWidth: 30, width: '40px' }}
+ style={{ height: '28px', marginBottom: '-4px', stroke: `${theme.palette.text.primary}`, strokeWidth: 30, width: '28px' }}

- size='lg'
+ style={{ height: '28px', width: '28px' }}

Also applies to: 359-359

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d1d608 and 2624c17.

📒 Files selected for processing (5)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/account/AccountBrief.tsx (3 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/staking/pool/index.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/staking/solo/index.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/extension-polkagate/src/popup/staking/solo/index.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx
🔇 Additional comments (5)
packages/extension-polkagate/src/popup/account/AccountBrief.tsx (3)

15-15: LGTM: Clean import addition

The useTheme hook import is properly grouped with other Material-UI imports.


32-33: LGTM: Proper theme hook initialization

The useTheme hook is correctly initialized at the component level, following React hooks best practices.


92-92: LGTM: Proper theme color usage

The Divider color change to secondary.light aligns with the dark theme requirements and properly utilizes the theme system.

packages/extension-polkagate/src/popup/account/index.tsx (1)

201-201: LGTM: Consistent theme styling update

The change to use secondary.light for the divider's background color aligns with the dark theme implementation and maintains visual consistency across components.

packages/extension-polkagate/src/popup/staking/pool/index.tsx (1)

203-203: LGTM: Consistent theme update

The border color change to secondary.light aligns with the minimal dark theme styling approach.

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 (2)
packages/extension-polkagate/src/popup/history/partials/FailSuccessIcon.tsx (2)

80-81: Ensure fontSize prop is a string

The fontSize prop is being cast to a string using as string, but style.fontSize can be a string or number according to React.CSSProperties. This may lead to unexpected behavior if fontSize is a number.

Consider enforcing style.fontSize to be a string or updating the AnimatedCheckIcon to accept fontSize: string | number:

 export function AnimatedCheckIcon ({ fontSize, initial = true, isVisible = true }: { initial?: boolean; isVisible?: boolean, fontSize: string }) {
+// Change the type of fontSize to accept string or number
+export function AnimatedCheckIcon ({ fontSize, initial = true, isVisible = true }: { initial?: boolean; isVisible?: boolean, fontSize: string | number }) {

This ensures type compatibility and prevents potential runtime issues.


37-45: Reevaluate flex properties on the svg element

Applying display: 'flex', alignItems, and justifyContent directly to an svg element may not have the desired effect and can lead to inconsistent rendering across browsers.

Consider removing these styles or wrapping the svg element in a Box or div if alignment is necessary:

-<svg
-  style={{
-    display: 'flex',
-    alignItems: 'center',
-    justifyContent: 'center',
-    // other styles
-  }}
->
+<Box
+  display='flex'
+  alignItems='center'
+  justifyContent='center'
+  sx={{
+    height: iconStyles.fontSize,
+    width: iconStyles.fontSize,
+    backgroundColor: iconStyles.bgcolor,
+    borderRadius: iconStyles.borderRadius,
+  }}
+>
+  <svg
+    // svg attributes
+  >
     {/* SVG content */}
   </svg>
+</Box>

This approach provides better control over layout and ensures consistent styling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2624c17 and 1e1afbc.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • packages/extension-polkagate/src/popup/history/partials/FailSuccessIcon.tsx (4 hunks)
🔇 Additional comments (2)
package.json (1)

80-80: Verify compatibility with major version update of framer-motion

The update from v7.5.1 to v11.11.13 is a significant version jump that may include breaking changes. Since this library is crucial for animations in your UI components:

  1. Please verify that all existing animations still work as expected
  2. Review the framer-motion migration guide for any breaking changes
  3. Test the animations in both light and dark themes
packages/extension-polkagate/src/popup/history/partials/FailSuccessIcon.tsx (1)

69-69: ⚠️ Potential issue

Replace invalid mt style property with marginTop

The style object uses mt, which is not a valid CSS property. To apply a top margin, use marginTop instead.

Apply this diff to fix the issue:

 export default function FailSuccessIcon ({ showLabel = true, style = { fontSize: '54px', mt: '20px' }, success }: Props) {
+  style = { fontSize: '54px', marginTop: '20px', ...style };

Alternatively, update the default style object:

 export default function FailSuccessIcon ({ showLabel = true, style = { fontSize: '54px', mt: '20px' }, success }: Props) {
-  style = { fontSize: '54px', mt: '20px', ...style };
+  style = { fontSize: '54px', marginTop: '20px', ...style };

Likely invalid or redundant comment.

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: 0

🧹 Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/fullscreen/governance/partials/ThemeChanger.tsx (1)

64-64: Good use of MUI's semantic color token!

The change from secondary.light to divider for the border color is a better choice as it:

  • Uses MUI's semantic color token that automatically adapts to theme changes
  • Provides better visual consistency across light and dark modes
  • Follows Material Design best practices for component boundaries

Consider extracting the Grid's sx styles into a separate const or styled component to improve readability, especially given the number of style properties:

const themeChangerStyles = {
  border: (props) => props.noBorder ? undefined : '1px solid',
  borderColor: 'divider',
  borderRadius: '5px',
  cursor: 'pointer',
  height: '42px',
  overflow: 'hidden',
  position: 'relative',
  width: '42px'
} as const;
packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (1)

Line range hint 24-32: Consider using theme colors instead of hardcoded values

While the border color now uses the theme-aware 'divider' token, there are still hardcoded color values ('#fff') for the icon and text. To maintain consistent theming, consider using MUI's theme colors.

- <ShowIcon color='#fff' height={18} scale={1.2} width={40} />
+ <ShowIcon color='primary.contrastText' height={18} scale={1.2} width={40} />
- <HideIcon color='#fff' height={18} scale={1.2} width={40} />
+ <HideIcon color='primary.contrastText' height={18} scale={1.2} width={40} />
- <Typography sx={{ color: '#fff', fontSize: '12px', fontWeight: 500, textWrap: 'nowrap', userSelect: 'none' }}>
+ <Typography sx={{ color: 'primary.contrastText', fontSize: '12px', fontWeight: 500, textWrap: 'nowrap', userSelect: 'none' }}>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1e1afbc and 249ceec.

📒 Files selected for processing (7)
  • packages/extension-polkagate/src/fullscreen/governance/FullScreenHeader.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/partials/ThemeChanger.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/Currency.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FavoriteChains.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/FullScreenChainSwitch.tsx (1 hunks)
  • packages/extension-polkagate/src/partials/RemoteNodeSelectorWithSignals.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/extension-polkagate/src/fullscreen/governance/FullScreenHeader.tsx
  • packages/extension-polkagate/src/partials/RemoteNodeSelectorWithSignals.tsx
🔇 Additional comments (4)
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FavoriteChains.tsx (1)

32-32: LGTM! Consider verifying contrast ratios.

The change to use the semantic 'divider' color is a good choice for dark theme support as it automatically adapts to the theme mode. However, ensure that the border provides sufficient contrast in both light and dark modes for accessibility.

Let's verify the contrast ratios:

packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (1)

Line range hint 66-75: LGTM! Verify layout spacing

The reduced padding aligns with the minimal theme objective. The Grid layout structure is well-organized and properly memoized.

Please verify that the reduced left padding (5px) provides enough spacing in all viewport sizes:

✅ Verification successful

Padding-left adjustment to 5px is consistent across header components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other header components to ensure consistent padding
rg -t tsx -t jsx "pl=['\"]5px" 

Length of output: 62


Script:

#!/bin/bash
# Search for other header components to ensure consistent padding
rg "pl=['\"]5px" --glob "*.tsx" --glob "*.jsx"

Length of output: 22159

packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/Currency.tsx (1)

50-50: LGTM! Theme styling change aligns with Material-UI standards.

The change from secondary.light to divider for the border color is appropriate, as it leverages Material-UI's semantic color system for better theme consistency.

Let's verify theme consistency across similar components:

packages/extension-polkagate/src/partials/FullScreenChainSwitch.tsx (1)

128-128: LGTM! Verify color contrast in both themes.

The change to use the theme's divider color for the button border aligns well with the minimal dark theme objective and promotes consistent color usage across components.

Let's verify the color contrast for accessibility:

✅ Verification successful

Color contrast verified in both light and dark themes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for other usages of the divider color to ensure consistent application
# and verify there are no contrast issues reported elsewhere

# Look for other divider color usage patterns
rg "borderColor.*divider" -A 2 -B 2

# Look for any contrast-related comments or issues
rg -i "contrast|accessibility|a11y|wcag" 

Length of output: 35088

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 (3)
packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (1)

55-59: Clean component replacement with improved props API

The replacement of HideNumbers with HideBalance component improves the API with more intuitive prop names and adds size control. The change maintains the existing functionality while aligning with the dark theme objectives.

Consider adding a tooltip to improve UX by indicating the button's purpose:

 <HideBalance
   hide={hideNumbers}
   onClick={onHideClick}
   size={28}
+  title={hideNumbers ? "Show Balance" : "Hide Balance"}
 />
packages/extension-polkagate/src/components/SVG/HideBalance.tsx (2)

7-16: Add JSDoc documentation for interfaces

Consider adding JSDoc documentation to describe the purpose and usage of each interface and its properties.

Example documentation:

+/**
+ * Props for the HideBalance component
+ * @property {boolean} hide - Whether to show the closed eye icon
+ * @property {number} size - Size of the icon in pixels
+ * @property {() => void} onClick - Click handler for toggling visibility
+ */
 interface Props {
   hide?: boolean;
   size?: number;
   onClick: () => void
 }

+/**
+ * Props for the eye icon SVG components
+ * @property {string} color - Color of the icon
+ * @property {number} size - Size of the icon in pixels
+ */
 interface IconProps {
   color: string
   size?: number;
 }

18-31: Optimize SVG components and improve consistency

Consider the following improvements:

  1. Memoize components to prevent unnecessary re-renders
  2. Make SVG attribute usage consistent between components (e.g., fill property)

Apply these changes:

-const ClosedEye = ({ color, size = 20 }: IconProps) => (
+const ClosedEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
     fill='none'
     height={`${size}px`}
     viewBox='0 -5 24 24'
     width={`${size}px`}
     xmlns='http://www.w3.org/2000/svg'
   >
     <path
       d='M2.68936 6.70456C2.52619...'
       fill={color}
     />
   </svg>
-);
+));

-const OpenEye = ({ color, size = 20 }: IconProps) => (
+const OpenEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
-    fill={color}
+    fill='none'
     height={`${size}px`}
     id='Capa_1'
     version='1.1'
     viewBox='0 0 448.004 448.004'
     width={`${size}px`}
     xmlSpace='preserve'
     xmlns='http://www.w3.org/2000/svg'
   >
     <g>
-      <path d='M46.139,217.607...'/>
+      <path
+        d='M46.139,217.607...'
+        fill={color}
+      />
     </g>
   </svg>
-);
+));

Also applies to: 33-60

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 249ceec and a35afa7.

📒 Files selected for processing (5)
  • packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FavoriteChains.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (1 hunks)
  • packages/extension-polkagate/src/themes/baseTheme.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/FavoriteChains.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx
🔇 Additional comments (4)
packages/extension-polkagate/src/themes/baseTheme.ts (2)

6-6: LGTM: Type-only import optimization

Converting to a type-only import is a good optimization as it helps reduce bundle size by excluding runtime code.


8-9: ⚠️ Potential issue

Critical: Empty theme object doesn't implement dark theme

The PR is titled "style: minimal dark theme" but the baseTheme object is empty. This seems inconsistent with the PR's purpose. The theme object should define the basic dark theme properties like:

  • Color palette (primary, secondary, background, text colors)
  • Typography settings
  • Component-specific dark theme overrides

Let's check if dark theme properties are defined elsewhere:

packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (1)

50-50: Verify the padding reduction impact

The left padding has been significantly reduced from 18px to 5px. While this might be intentional for the dark theme, please ensure this doesn't create visual imbalance or alignment issues with adjacent components.

✅ Verification successful

Padding change appears intentional and consistent

The padding change to 5px appears to be a deliberate styling decision that maintains proper layout with the adjacent components. The Grid component is used in a header context with other elements (Currency, Badge with FavoriteChains, and HideBalance), and the columnGap='18px' property ensures proper spacing between these elements. The reduced left padding (5px) helps achieve a balanced layout without excessive indentation from the edge.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other Grid components with similar padding patterns
rg -l "pl=['\"]18px" | while read -r file; do
  echo "=== $file ==="
  rg "Grid.*pl=['\"]18px" "$file"
done

Length of output: 39


Script:

#!/bin/bash
# Let's try a broader search for Grid components with padding-left
rg "Grid.*pl=[\'\"]" -A 2 -B 2

Length of output: 125


Script:

#!/bin/bash
# Also search for similar Grid components in this specific component
rg "Grid.*container.*item" packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx -A 2 -B 2

Length of output: 288


Script:

#!/bin/bash
# Check if there are any design system constants or theme files that might define spacing
fd "theme|spacing|constants" --type f

Length of output: 491


Script:

#!/bin/bash
# Let's check the base theme file for spacing definitions
cat packages/extension-polkagate/src/themes/baseTheme.ts

# Let's also check for other Grid components in the same file with different padding
rg "Grid.*pl=.{1,20}['\"]" packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx

# And let's see the surrounding context of this component to understand the layout
rg -A 10 -B 10 "Grid.*container.*item.*pl='5px'" packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx

Length of output: 1195

packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1)

1-6: LGTM: Clean imports and proper licensing

The file has appropriate copyright notice, license declaration, and minimal necessary imports.

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: 0

🧹 Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/popup/home/YouHave.tsx (1)

71-77: Consider using theme-based spacing and relative positioning

While the implementation works, there are a few suggestions to improve maintainability and consistency:

  1. Use theme spacing units instead of hardcoded pixel values
  2. Consider using relative positioning if possible to maintain layout flexibility
  3. Consider extracting the size value to a constant or theme variable

Here's a suggested improvement:

-        <Grid alignItems='center' item sx={{ position: 'absolute', right: '14px', top: '25px' }}>
+        <Grid alignItems='center' item sx={(theme) => ({
+          position: 'absolute',
+          right: theme.spacing(1.75), // 14px -> 1.75 spacing units
+          top: theme.spacing(3.125), // 25px -> 3.125 spacing units
+        })}>
           <HideBalance
             border={false}
             hide={hideNumbers}
             onClick={onHideClick}
-            size={22}
+            size={theme.spacing(2.75)} // 22px -> 2.75 spacing units
           />
         </Grid>
packages/extension-polkagate/src/components/SVG/HideBalance.tsx (2)

7-17: Add JSDoc documentation to interfaces

Consider adding JSDoc documentation to describe the purpose of each interface and its properties, especially the onClick handler's purpose for toggling balance visibility.

+/**
+ * Props for the HideBalance component
+ */
 interface Props {
+  /** Whether to show border around the button */
   border?: boolean;
+  /** Current visibility state of the balance */
   hide?: boolean;
+  /** Size of the eye icon in pixels */
   size?: number;
+  /** Handler for toggling balance visibility */
   onClick: () => void
 }

+/**
+ * Props for eye icon SVG components
+ */
 interface IconProps {
+  /** Color of the SVG icon */
   color: string
+  /** Size of the icon in pixels */
   size?: number;
 }

19-61: Enhance SVG accessibility and performance

The SVG components should include accessibility attributes and be memoized to prevent unnecessary re-renders.

+const ClosedEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
     fill='none'
     height= {`${size}px`}
     viewBox='0 -5 24 24'
     width={`${size}px`}
     xmlns='http://www.w3.org/2000/svg'
+    role="img"
+    aria-label="Hide balance"
   >
     <path
       d='M2.68936 6.70456C2.52619...'
       fill={color}
     />
   </svg>
-));
+));
+ClosedEye.displayName = 'ClosedEye';

+const OpenEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
     fill={color}
     height={`${size}px`}
     id='Capa_1'
     version='1.1'
     viewBox='0 0 448.004 448.004'
     width={`${size}px`}
     xmlSpace='preserve'
     xmlns='http://www.w3.org/2000/svg'
+    role="img"
+    aria-label="Show balance"
   >
     <g>
       <path d='M46.139,217.607...' />
     </g>
   </svg>
-));
+));
+OpenEye.displayName = 'OpenEye';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a35afa7 and 74eee81.

📒 Files selected for processing (2)
  • packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/home/YouHave.tsx (2 hunks)
🔇 Additional comments (2)
packages/extension-polkagate/src/popup/home/YouHave.tsx (1)

13-13: LGTM: Clean import organization

The new import follows the project's organization pattern and is properly grouped with other component imports.

packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1)

63-91: 🛠️ Refactor suggestion

Implement remaining accessibility and maintainability improvements

The past review comments about extracting styles and adding accessibility attributes are still valid. Additionally:

  1. The Grid component used as a button needs proper button attributes
  2. The component should be memoized
+const buttonStyles = {
+  bgcolor: 'transparent',
+  border: (border: boolean) => border ? '1px solid' : 'none',
+  borderColor: 'divider',
+  borderRadius: '5px',
+  cursor: 'pointer',
+  height: '42px',
+  minWidth: '42px',
+  p: '2px 6px',
+  position: 'relative',
+  width: 'fit-content'
+} as const;

-const HideBalance = ({ border = true, hide = false, onClick, size = 20 }: Props) => {
+const HideBalance = React.memo(({ border = true, hide = false, onClick, size = 20 }: Props) => {
   const theme = useTheme();
   const color = theme.palette.mode === 'dark' ? theme.palette.text.primary : theme.palette.text.secondary;

   return (
     <Grid
       alignItems='center'
       component='button'
+      type="button"
+      aria-label={hide ? 'Show balance' : 'Hide balance'}
+      aria-pressed={!hide}
       container
       direction='column'
       item
       justifyContent='center'
       onClick={onClick}
-      sx={{ bgcolor: 'transparent', border: border ? '1px solid' : 'none', borderColor: 'divider', borderRadius: '5px', cursor: 'pointer', height: '42px', minWidth: '42px', p: '2px 6px', position: 'relative', width: 'fit-content' }}
+      sx={theme => ({
+        ...buttonStyles,
+        border: buttonStyles.border(border)
+      })}
     >
       {hide
         ? <ClosedEye
           color={color}
           size={size}
         />
         : <OpenEye
           color={color}
           size={size}
         />
       }
     </Grid>
   );
-};
+});
+
+HideBalance.displayName = 'HideBalance';

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: 0

🧹 Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/components/SVG/HideBalance.tsx (2)

7-19: Add JSDoc documentation for interfaces

Consider adding JSDoc comments to document the purpose and usage of each prop in both interfaces.

Example:

/**
 * Props for the HideBalance component
 * @property {boolean} border - Whether to show border around the button
 * @property {boolean} hide - Current visibility state
 * @property {number} size - Size of the icon in pixels
 * @property {string} darkColor - Custom color for dark theme
 * @property {string} lightColor - Custom color for light theme
 * @property {() => void} onClick - Click handler for toggling visibility
 */
interface Props {
  // ... existing props
}

21-63: Enhance SVG components for performance and accessibility

The SVG components could be improved in several ways:

  1. Memoize components to prevent unnecessary re-renders
  2. Add ARIA labels and roles for accessibility

Apply these changes:

-const ClosedEye = ({ color, size = 20 }: IconProps) => (
+const ClosedEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
+    role="img"
+    aria-label="Hide balance"
     // ... existing props
   />
-);
+));

-const OpenEye = ({ color, size = 20 }: IconProps) => (
+const OpenEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
+    role="img"
+    aria-label="Show balance"
     // ... existing props
   />
-);
+));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 74eee81 and bace269.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/home/YouHave.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/home/index.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/popup/home/YouHave.tsx
🔇 Additional comments (2)
packages/extension-polkagate/src/popup/home/index.tsx (1)

100-100: LGTM! Simplified theme-related prop.

The change simplifies the noBorder prop by making it a static value, which aligns with the minimal dark theme implementation.

Let's verify other theme-related changes in the codebase:

✅ Verification successful

LGTM! The noBorder prop change is safe and consistent.

The verification confirms that:

  • noBorder is an optional boolean prop with a default value of false
  • It's used consistently in the styling logic where it affects the bottom border rendering
  • The change to make it a static value in the home component aligns with the component's design and doesn't impact other usages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar theme-related changes in HeaderBrand usage
# Expected: Find other HeaderBrand components that might need similar updates

# Search for HeaderBrand usage with theme-related props
rg -l "HeaderBrand.*noBorder" | while read -r file; do
  echo "=== $file ==="
  rg -A 5 "HeaderBrand.*noBorder" "$file"
done

Length of output: 792


Script:

#!/bin/bash
# Let's check the actual implementation of HeaderBrand to understand the noBorder prop usage
ast-grep --pattern 'interface Props {
  $$$
  noBorder$$$
  $$$
}'

# Also check how noBorder affects the styling
rg -A 5 -B 5 "noBorder" packages/extension-polkagate/src/partials/HeaderBrand.tsx

Length of output: 1432

packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1)

65-93: 🛠️ Refactor suggestion

Improve component maintainability and accessibility

The component needs several improvements:

  1. Extract styles to a constant
  2. Add proper button type and aria attributes
  3. Memoize the component

The previous review comment suggesting these improvements is still valid. Additionally, consider adding proper aria-pressed attribute to indicate the toggle state:

-const HideBalance = ({ border = true, darkColor, hide = false, lightColor, onClick, size = 20 }: Props) => {
+const buttonStyles = {
+  bgcolor: 'transparent',
+  border: (border: boolean) => border ? '1px solid' : 'none',
+  borderColor: 'divider',
+  borderRadius: '5px',
+  cursor: 'pointer',
+  height: '42px',
+  minWidth: '42px',
+  p: '2px 6px',
+  position: 'relative',
+  width: 'fit-content'
+} as const;

+const HideBalance = React.memo(({ border = true, darkColor, hide = false, lightColor, onClick, size = 20 }: Props) => {
   // ... theme logic

   return (
     <Grid
       alignItems='center'
       component='button'
+      type='button'
+      aria-pressed={hide}
+      aria-label={hide ? 'Show balance' : 'Hide balance'}
       // ... other props
-      sx={{ bgcolor: 'transparent', border: border ? '1px solid' : 'none', borderColor: 'divider', borderRadius: '5px', cursor: 'pointer', height: '42px', minWidth: '42px', p: '2px 6px', position: 'relative', width: 'fit-content' }}
+      sx={theme => ({
+        ...buttonStyles,
+        border: buttonStyles.border(border)
+      })}
     >
       {/* ... existing children */}
     </Grid>
   );
-};
+});

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: 0

🧹 Outside diff range and nitpick comments (2)
packages/extension-polkagate/src/fullscreen/governance/components/AddressDropdown.tsx (2)

47-47: Consider using theme constants for border widths and colors.

While the conditional styling is clean, consider extracting the border width values and colors to theme constants for better maintainability and consistency across the application.

Example approach:

// In your theme configuration
const theme = createTheme({
  components: {
    AddressDropdown: {
      borderWidth: {
        default: 1,
        heading: 2
      }
    }
  }
});

// In component
sx={{ 
  border: inHeading ? theme.components.AddressDropdown.borderWidth.heading : theme.components.AddressDropdown.borderWidth.default,
  // ... rest of the styling
}}

67-67: Consider extracting duplicated border styling logic.

The border styling logic is duplicated between the main container and the toggle button. Consider extracting this into a shared style object or theme constant.

Example approach:

const getBorderStyle = (inHeading: boolean) => ({
  borderWidth: inHeading ? 2 : 1,
  borderColor: inHeading ? 'divider' : 'secondary.light'
});

// Then in JSX
<Grid 
  // ... other props
  sx={{ 
    ...getBorderStyle(inHeading),
    // ... other styles
  }}
/>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bace269 and dae6c3c.

📒 Files selected for processing (9)
  • packages/extension-polkagate/src/fullscreen/governance/FullScreenHeader.tsx (3 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/components/AddressDropdown.tsx (3 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/partials/ThemeChanger.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (2 hunks)
  • packages/extension-polkagate/src/partials/FullScreenChainSwitch.tsx (3 hunks)
  • packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx (5 hunks)
  • packages/extension-polkagate/src/partials/RemoteNodeSelectorWithSignals.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/home/AccountLabel.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/home/ProfileTab.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/extension-polkagate/src/fullscreen/governance/FullScreenHeader.tsx
  • packages/extension-polkagate/src/fullscreen/governance/partials/ThemeChanger.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx
  • packages/extension-polkagate/src/partials/FullScreenChainSwitch.tsx
  • packages/extension-polkagate/src/partials/QuickActionFullScreen.tsx
  • packages/extension-polkagate/src/partials/RemoteNodeSelectorWithSignals.tsx
  • packages/extension-polkagate/src/popup/home/AccountLabel.tsx
  • packages/extension-polkagate/src/popup/home/ProfileTab.tsx
🔇 Additional comments (2)
packages/extension-polkagate/src/fullscreen/governance/components/AddressDropdown.tsx (2)

23-23: LGTM! Clean prop interface addition.

The new optional inHeading prop is well-typed and follows TypeScript best practices.


26-26: LGTM! Function signature properly updated.

The component signature correctly incorporates the new prop while maintaining existing parameter patterns and type safety.

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

🧹 Outside diff range and nitpick comments (12)
packages/extension-polkagate/src/hooks/useIsHideNumbers.ts (3)

6-6: Consider relocating storage utilities

The storage utilities (getStorage and watchStorage) are currently imported from a Loading component. This seems architecturally misplaced as storage operations are typically part of a dedicated storage or utilities module rather than a UI component.

Consider moving these utilities to a dedicated storage service module (e.g., services/storage.ts or utils/storage.ts).


8-8: Add JSDoc documentation

Consider adding documentation to explain the hook's purpose, return value, and usage examples.

Add documentation like this:

+/**
+ * A hook that manages the visibility state of numbers throughout the application.
+ * This state is persisted in storage and can be updated globally.
+ *
+ * @returns {boolean | undefined} Current visibility state of numbers.
+ *         Returns `undefined` while loading, `true` if numbers should be hidden,
+ *         `false` if numbers should be shown.
+ *
+ * @example
+ * function MyComponent() {
+ *   const hideNumbers = useIsHideNumbers();
+ *   
+ *   return hideNumbers ? '***' : '123';
+ * }
+ */
 export default function useIsHideNumbers(): boolean | undefined {

12-14: Consider more robust error handling

The current error handling only logs to console. Consider providing a fallback value or error state for better user experience.

Apply this diff to enhance error handling:

-    getStorage('hide_numbers').then((isHide) => {
-      setHideNumbers(!!isHide);
-    }).catch(console.error);
+    getStorage('hide_numbers')
+      .then((isHide) => {
+        setHideNumbers(!!isHide);
+      })
+      .catch((error) => {
+        console.error('Failed to load number visibility setting:', error);
+        setHideNumbers(false); // Provide a safe default
+      });
packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (2)

16-19: Good improvement in state management!

The removal of props in favor of the useIsHideNumbers hook reduces prop drilling and improves component maintainability.


21-23: Consider enhancing error handling.

While the basic error handling is present, consider providing more specific error handling or user feedback when storage operations fail.

-    setStorage('hide_numbers', !isHideNumbers).catch(console.error);
+    setStorage('hide_numbers', !isHideNumbers).catch((error: Error) => {
+      console.error('Failed to update visibility setting:', error);
+      // Consider showing a user-friendly notification here
+    });
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/DraggableAccountList.tsx (2)

Line range hint 20-24: Consider enhancing error handling and performance.

The saveNewOrder function could benefit from the following improvements:

  1. More robust error handling with user feedback
  2. Memoization when used within the component

Consider applying these changes:

-export const saveNewOrder = (newOrder: AccountsOrder[]) => {
+export const saveNewOrder = async (newOrder: AccountsOrder[]) => {
   const addressOrder = newOrder.map(({ account }) => account.address);
 
-  chrome.storage.local.set({ addressOrder }).catch(console.error);
+  try {
+    await chrome.storage.local.set({ addressOrder });
+  } catch (error) {
+    console.error('Failed to save account order:', error);
+    // Consider adding a toast notification or other user feedback
+    throw error;
+  }
 };

Then in the component:

+const memoizedSaveNewOrder = useCallback(saveNewOrder, []);

 const handleDrag = useCallback((event: DragEndEvent) => {
   // ...
-  saveNewOrder(newOrder);
+  memoizedSaveNewOrder(newOrder).catch((error) => {
+    // Handle error appropriately
+  });
   setAccountsOrder(newOrder);
 }, [accountsOrder, getItemPos]);

27-28: Consider improving quickActionOpen state type.

The quickActionOpen state uses a mixed type of string | boolean which could lead to confusing behavior. Consider using a more specific type that better represents its purpose.

Example improvement:

-const [quickActionOpen, setQuickActionOpen] = useState<string | boolean>();
+type QuickActionState = {
+  isOpen: boolean;
+  accountId?: string;
+};
+const [quickActionOpen, setQuickActionOpen] = useState<QuickActionState>({ isOpen: false });
packages/extension-polkagate/src/popup/home/YouHave.tsx (2)

26-30: Consider enhancing error handling

While the implementation is correct, the error handling could be more robust than just logging to console.

Consider implementing a more user-friendly error handling approach:

 const onHideClick = useCallback(() => {
-  setStorage('hide_numbers', !isHideNumbers).catch(console.error);
+  setStorage('hide_numbers', !isHideNumbers).catch((error) => {
+    console.error('Failed to update visibility preference:', error);
+    // Consider showing a user-friendly notification or toast
+  });
 }, [isHideNumbers]);

57-64: Consider using flex layout instead of absolute positioning

The current implementation uses absolute positioning for the HideBalance component, which might be less maintainable. Consider using a flex layout for better responsiveness and maintainability.

-<Grid container item justifyContent='center' xs={12}>
+<Grid container item alignItems='center' justifyContent='center' position='relative' xs={12}>
   {/* ... */}
-  <Grid alignItems='center' item sx={{ position: 'absolute', right: '14px', top: '25px' }}>
+  <Grid item sx={{ ml: 'auto', mr: '14px' }}>
     <HideBalance
       border={false}
       hide={isHideNumbers}
       lightColor={theme.palette.secondary.light}
       onClick={onHideClick}
       size={22}
     />
   </Grid>
 </Grid>
packages/extension-polkagate/src/popup/passwordManagement/Login.tsx (2)

28-29: Consider enhancing error handling in the onHideClick callback.

The state management changes look good, transitioning from direct state to hooks. However, the error handling in onHideClick could be improved.

Consider this enhancement:

  const onHideClick = useCallback(() => {
-   setStorage('hide_numbers', !isHideNumbers).catch(console.error);
+   setStorage('hide_numbers', !isHideNumbers).catch((error) => {
+     console.error('Failed to update hide numbers setting:', error);
+     // Consider showing a user-friendly error notification here
+   });
  }, [isHideNumbers]);

Also applies to: 41-42


48-56: Consider adding ARIA labels for better accessibility.

The UI changes look good, with proper implementation of the new HideBalance component and text toggle. However, accessibility could be improved.

Consider these enhancements:

  <Grid alignItems='center' 
        direction='column' 
        item 
        onClick={onHideClick} 
+       role="button"
+       aria-label={isHideNumbers ? t('Show numbers') : t('Hide numbers')}
        sx={{ cursor: 'pointer', display: 'flex', position: 'absolute', pt: '3px', right: '35px', top: '15px', opacity: 0.5, '&:hover': { opacity: 1 } }}>
packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (1)

120-127: Great architectural improvement using hooks

The replacement of the hideNumbers prop with the useIsHideNumbers hook is a solid architectural decision that:

  • Reduces prop drilling
  • Centralizes state management
  • Ensures consistent behavior across components
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dae6c3c and 477e569.

📒 Files selected for processing (11)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/index.tsx (0 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx (5 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountItem.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/DraggableAccountList.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (5 hunks)
  • packages/extension-polkagate/src/hooks/index.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useIsHideNumbers.ts (1 hunks)
  • packages/extension-polkagate/src/popup/home/YouHave.tsx (2 hunks)
  • packages/extension-polkagate/src/popup/home/index.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/passwordManagement/Login.tsx (3 hunks)
💤 Files with no reviewable changes (1)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/index.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountItem.tsx
  • packages/extension-polkagate/src/popup/home/index.tsx
🔇 Additional comments (11)
packages/extension-polkagate/src/fullscreen/homeFullScreen/components/HeaderComponents.tsx (2)

6-11: LGTM! Imports are well-organized and relevant.

The new imports align well with the component's requirements and functionality.


40-49: Verify the reduced padding impact on layout.

The Grid padding reduction from 18px to 5px might affect component spacing. Please ensure this change aligns with the dark theme design specifications.

✅ Verification successful

Grid padding change is consistent with the codebase patterns

The reduced padding from 18px to 5px aligns with the existing codebase patterns. The search results show that:

  • Most Grid components in the codebase use 5px left padding (pl='5px') as a common spacing value
  • The HideBalance component is consistently used across the application with similar props
  • The change brings this component's padding in line with the established design system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other Grid components with similar padding patterns
rg -U "Grid.*pl=.*18px" --type tsx

Length of output: 64


Script:

#!/bin/bash
# Search for Grid components with pl prop using ripgrep
rg -U "Grid.*pl=[\'\"]" --type-add 'tsx:*.tsx' --type tsx

# Also search for any design system or theme files that might define padding values
fd -e ts -e tsx -e js -e jsx theme

Length of output: 451


Script:

#!/bin/bash
# Search for Grid components with padding-left using proper escaping
rg -U 'Grid.*pl=["'\'']' --type-add 'tsx:*.tsx' --type tsx

# Check the theme file for padding definitions
cat packages/extension-polkagate/src/themes/baseTheme.ts

# Search for any HideBalance component usage to verify consistency
rg -U "HideBalance" --type-add 'tsx:*.tsx' --type tsx

Length of output: 18933

packages/extension-polkagate/src/popup/home/YouHave.tsx (3)

12-15: LGTM: Clean import organization

The new imports are well-organized and properly support the component's transition to hook-based state management.


22-22: LGTM: Improved component signature

The removal of props in favor of hook-based state management reduces component coupling and improves reusability.


46-55: Verify FormatPrice component prop types

The FormatPrice component receives multiple props. Let's ensure all props are properly typed.

✅ Verification successful

FormatPrice component props are properly typed

The FormatPrice component has a well-defined Props interface that includes all the props being used in the code snippet, including:

  • fontSize?: string
  • fontWeight?: number
  • height?: number
  • num?: number | string
  • skeletonHeight?: number
  • textColor?: string
  • width?: string
  • withCountUp?: boolean

All props are properly typed as optional properties with appropriate type definitions, matching their usage in the component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for FormatPrice component definition to verify prop types
ast-grep --pattern 'interface $_ {
  $$$
  fontSize?: $_
  fontWeight?: $_
  height?: $_
  num?: $_
  skeletonHeight?: $_
  textColor?: $_
  width?: $_
  withCountUp?: $_
  $$$
}'

Length of output: 181


Script:

#!/bin/bash
# Let's try to find the FormatPrice component definition using a broader search
rg -A 20 "export.*FormatPrice" 

# Also search for any type definitions related to FormatPrice
rg "type.*FormatPrice|interface.*FormatPrice"

# As a backup, let's find the file that might contain the component
fd "FormatPrice"

Length of output: 2533


Script:

#!/bin/bash
# Now that we found the file, let's examine its content
cat packages/extension-polkagate/src/components/FormatPrice.tsx

Length of output: 3443

packages/extension-polkagate/src/popup/passwordManagement/Login.tsx (2)

11-14: LGTM! Import changes align with the refactoring.

The new imports are properly organized and support the transition from direct state management to using the new useIsHideNumbers hook.


14-14: Verify consistent hook usage across components.

Since this is part of a larger refactor transitioning from hideNumbers to useIsHideNumbers, let's verify consistent implementation across all affected components.

Also applies to: 29-29

✅ Verification successful

Let me gather more information about the implementation to verify consistency.


Hook implementation and usage are consistent across components

The verification shows that:

  • The useIsHideNumbers hook is properly implemented with centralized state management using localStorage
  • All components are consistently using the hook to access the hide numbers state
  • No direct localStorage access or local state management for hide numbers remains
  • The hook is properly exported and imported across components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct hideNumbers state management
rg -l "const \[hideNumbers, setHideNumbers\] = useState"

# Search for useIsHideNumbers hook usage
rg -l "useIsHideNumbers"

# Search for any remaining direct localStorage access for hide_numbers
rg "localStorage.*hide_numbers"

Length of output: 743


Script:

#!/bin/bash
# Check the implementation of useIsHideNumbers hook
cat packages/extension-polkagate/src/hooks/useIsHideNumbers.ts

# Check how it's used in different components
echo "=== Login.tsx ==="
rg -A 5 "useIsHideNumbers" packages/extension-polkagate/src/popup/passwordManagement/Login.tsx

echo "=== YouHave.tsx ==="
rg -A 5 "useIsHideNumbers" packages/extension-polkagate/src/popup/home/YouHave.tsx

echo "=== TotalBalancePieChart.tsx ==="
rg -A 5 "useIsHideNumbers" packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx

echo "=== AccountInformationForHome.tsx ==="
rg -A 5 "useIsHideNumbers" packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/AccountInformationForHome.tsx

Length of output: 3513

packages/extension-polkagate/src/hooks/index.ts (1)

58-58: LGTM! The new hook export follows established patterns.

The addition of useIsHideNumbers hook promotes better state management by centralizing the number visibility logic across components.

Let's verify the hook's implementation and its usage:

✅ Verification successful

Hook implementation and usage verified successfully

The verification shows proper implementation and adoption of the useIsHideNumbers hook:

  • The hook is correctly implemented using React's useState and useEffect, with proper localStorage integration
  • It's being used in multiple components across the application:
    • Home components (YouHave.tsx, index.tsx)
    • Account-related components (AccountInformationForHome.tsx, TotalBalancePieChart.tsx)
    • Authentication components (Login.tsx)
    • Header components (HeaderComponents.tsx)
  • Some components still use hideNumbers props, suggesting the migration to the hook is in progress
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the hook implementation and its usage across components

# Check the hook implementation
echo "Checking hook implementation:"
cat packages/extension-polkagate/src/hooks/useIsHideNumbers.ts || echo "Hook file not found"

# Find components using the hook
echo -e "\nChecking hook usage:"
rg "useIsHideNumbers" --type ts --type tsx -l

# Look for any remaining hideNumbers props
echo -e "\nChecking for remaining hideNumbers props:"
rg "hideNumbers.*Props" --type ts --type tsx

Length of output: 1034


Script:

#!/bin/bash
# Let's try a different approach using just ripgrep without file type filters

# Find all files using the hook
echo "Files using useIsHideNumbers:"
rg "useIsHideNumbers"

# Look for hideNumbers props
echo -e "\nFiles with hideNumbers props:"
rg "hideNumbers.*Props"

# Check if there are any direct hideNumbers state management
echo -e "\nFiles with hideNumbers state:"
rg "hideNumbers.*useState|hideNumbers.*setState"

Length of output: 3522

packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx (3)

18-18: LGTM: Hook import is properly organized

The addition of useIsHideNumbers to the existing hook imports maintains good code organization.


253-253: LGTM: Consistent hook usage

The hideNumbers prop has been correctly replaced with the isHideNumbers hook value throughout the component, maintaining the same conditional rendering logic.

Also applies to: 263-263


214-222: Verify UI adjustments align with design system

The font size and image height adjustments appear to be part of UI refinements. Please ensure these specific dimensions (21px title, 28px amount, 28px image height) align with the design system's typography and spacing scales.

Also applies to: 227-227

✅ Verification successful

Font sizes and dimensions are consistent with design system

The verification shows that these UI adjustments align with established patterns across the codebase:

  • Font size 21px is consistently used for section headers and titles
  • Font size 28px is a standard size used for amounts, balances, and important information across many components
  • Image height 28px and width 154px for stars/rating images are used in similar contexts

The changes maintain visual consistency with the rest of the application's design system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar font sizes and image heights across the codebase
# to verify consistency with the design system

echo "Checking for font size usage patterns:"
rg --type tsx --type ts "fontSize.*21px|fontSize.*28px"

echo -e "\nChecking for image height patterns:"
rg --type tsx --type ts "height.*28px"

Length of output: 328


Script:

#!/bin/bash
# Search for similar font sizes and image heights across the codebase
# to verify consistency with the design system

echo "Checking for font size usage patterns:"
rg "fontSize.*21px|fontSize.*28px"

echo -e "\nChecking for image dimensions:"
rg "height.*28px|width.*154px"

echo -e "\nChecking for other font sizes in the same component:"
rg --context 2 "fontSize" "packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/TotalBalancePieChart.tsx"

Length of output: 21542

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 (2)
packages/extension-polkagate/src/popup/home/YouHave.tsx (2)

26-30: Consider improving error handling and storage key management

While the implementation is functional, consider these improvements:

  1. Define the storage key as a constant to prevent typos and enable reuse
  2. Implement proper error handling instead of just logging to console
+const HIDE_NUMBERS_STORAGE_KEY = 'hide_numbers';

 const onHideClick = useCallback(() => {
-  setStorage('hide_numbers', !isHideNumbers).catch(console.error);
+  setStorage(HIDE_NUMBERS_STORAGE_KEY, !isHideNumbers).catch((error) => {
+    console.error('Failed to update number visibility:', error);
+    // Consider showing a user-friendly error notification
+  });
 }, [isHideNumbers]);

57-64: Consider alternative to absolute positioning

The HideBalance component uses absolute positioning which might cause layout issues on different screen sizes or when the parent container's size changes.

Consider using a more flexible layout approach:

-<Grid alignItems='center' item sx={{ position: 'absolute', right: '14px', top: '25px' }}>
+<Grid 
+  alignItems='center'
+  item
+  sx={{
+    display: 'flex',
+    justifyContent: 'flex-end',
+    padding: '25px 14px 0 0'
+  }}
+>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 477e569 and 549b3cb.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/popup/home/YouHave.tsx (2 hunks)
🔇 Additional comments (2)
packages/extension-polkagate/src/popup/home/YouHave.tsx (2)

9-9: LGTM! Import changes are well-organized

The new imports are logically grouped and align with the component's updated architecture using the new useIsHideNumbers hook and HideBalance component.

Also applies to: 12-15


22-22: LGTM! Component signature simplified

Good refactoring to remove props in favor of the custom hook useIsHideNumbers. This centralizes state management and follows React best practices.

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 (15)
packages/extension-polkagate/src/hooks/useSelectedChains.ts (1)

22-26: Great improvement in storage subscription management!

The addition of proper cleanup for the storage subscription is a valuable improvement that prevents potential memory leaks. The implementation follows React hooks best practices by properly handling the unsubscribe callback in the useEffect cleanup function.

This pattern of proper subscription cleanup should be consistently applied across all hooks that use watchStorage. Consider verifying other hooks in the codebase:

#!/bin/bash
# Description: Find other hooks using watchStorage to verify consistent cleanup pattern
# Expected: All hooks should implement similar cleanup pattern

# Search for hooks using watchStorage
rg -l 'watchStorage' --type typescript packages/extension-polkagate/src/hooks/

# Check the implementation pattern
ast-grep --pattern 'useEffect(() => {
  $$$
  const $_ = watchStorage($$$)
  $$$
  return () => {
    $$$
  }
  $$$
})'
packages/extension-polkagate/src/hooks/usePrices.ts (1)

36-38: Consider adding error handling to the cleanup function.

While the cleanup implementation is correct, it might be good to wrap the unsubscribe call in a try-catch block to handle any potential errors during cleanup gracefully.

 return () => {
+  try {
     unsubscribe();
+  } catch (error) {
+    console.error('Error during price watcher cleanup:', error);
+  }
 };
packages/extension-polkagate/src/hooks/useProfileAccounts.tsx (1)

40-44: LGTM! Consider adding null check for unsubscribe.

The implementation of the storage watcher cleanup is correct and follows React best practices. This change prevents potential memory leaks by properly cleaning up subscriptions when the component unmounts.

Consider adding a null check for additional safety:

    const unsubscribe = watchStorage('profile', setProfile);

    return () => {
-     unsubscribe();
+     unsubscribe?.();
    };
packages/extension-polkagate/src/popup/home/ProfileTabs.tsx (1)

38-42: LGTM! Good improvement in resource management.

The addition of proper cleanup for the watchStorage subscription is a good practice that prevents potential memory leaks. This change aligns well with React's recommendations for handling subscriptions in effects.

A minor enhancement could be to add a null check before calling unsubscribe:

    return () => {
-     unsubscribe();
+     unsubscribe?.();
    };
packages/extension-polkagate/src/popup/home/AccountLabel.tsx (2)

43-43: Consider moving shadow values to theme constants

While the shadow calculation logic is good, consider extracting the hardcoded shadow values (0px 0px 2px 1px and 0px 0px 1px 1px rgba(000, 000, 000, 0.13)) to theme constants for better maintainability and consistency.

+ // In your theme file
+ const shadows = {
+   profileLight: '0px 0px 1px 1px rgba(000, 000, 000, 0.13)',
+   profileDark: (color: string) => `0px 0px 2px 1px ${color}`
+ };

- const shadow = useCallback((profile: string) => isDarkMode ? `0px 0px 2px 1px ${getColorOfUserDefinedProfile(profile)}` : '0px 0px 1px 1px rgba(000, 000, 000, 0.13)', [getColorOfUserDefinedProfile, isDarkMode]);
+ const shadow = useCallback((profile: string) => isDarkMode ? theme.shadows.profileDark(getColorOfUserDefinedProfile(profile)) : theme.shadows.profileLight, [getColorOfUserDefinedProfile, isDarkMode, theme]);

117-123: Consider extracting style constants

While the styling changes look good, consider extracting magic numbers to theme constants for better maintainability:

+ // In your theme file
+ const typography = {
+   label: {
+     fontSize: '11px'
+   }
+ };
+ const spacing = {
+   labelHeight: '18px',
+   labelPadding: '15px'
+ };

  <Grid
    container
    item
    justifyContent='flex-end'
    ref={scrollContainerRef}
-   sx={{ display: 'flex', flexWrap: 'nowrap', fontSize: '10px', height: '18px', left: right ? undefined : ml || '15px', ... }}
+   sx={{ display: 'flex', flexWrap: 'nowrap', fontSize: theme.typography.label.fontSize, height: theme.spacing.labelHeight, left: right ? undefined : ml || theme.spacing.labelPadding, ... }}
  >

Also applies to: 129-131

packages/extension-polkagate/src/components/SVG/HideBalance.tsx (3)

10-22: Enhance type definitions with documentation and stricter types

Consider improving the interface definitions:

+/** Props for the HideBalance component */
 interface Props {
+  /** Whether to show border around the button */
   border?: boolean;
+  /** Whether to hide the balance */
   hide?: boolean;
+  /** Size of the icon in pixels */
   size?: number;
+  /** Custom color for dark theme */
   darkColor?: string;
+  /** Custom color for light theme */
   lightColor?: string;
+  /** Click handler for the button */
-  onClick: () => void
+  onClick: React.MouseEventHandler<HTMLButtonElement>
 }

+/** Props for the eye icon SVG components */
 interface IconProps {
+  /** Color of the icon */
   color: string
+  /** Size of the icon in pixels */
   size?: number;
 }

24-37: Enhance SVG accessibility and performance

Consider improving the SVG implementation:

-const ClosedEye = ({ color, size = 20 }: IconProps) => (
+const ClosedEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
     fill='none'
     height= {`${size}px`}
     viewBox='0 -5 24 24'
     width={`${size}px`}
     xmlns='http://www.w3.org/2000/svg'
+    role="img"
+    aria-label="Hidden eye icon"
   >
     <path
       d='M2.68936 6.70456C2.52619 6.32384 2.08528 6.14747 1.70456 6.31064C1.32384 6.47381 1.14747 6.91472 1.31064 7.29544L2.68936 6.70456ZM15.5872 13.3287L15.3125 12.6308L15.5872 13.3287ZM9.04145 13.7377C9.26736 13.3906 9.16904 12.926 8.82185 12.7001C8.47466 12.4742 8.01008 12.5725 7.78417 12.9197L9.04145 13.7377ZM6.37136 15.091C6.14545 15.4381 6.24377 15.9027 6.59096 16.1286C6.93815 16.3545 7.40273 16.2562 7.62864 15.909L6.37136 15.091ZM22.6894 7.29544C22.8525 6.91472 22.6762 6.47381 22.2954 6.31064C21.9147 6.14747 21.4738 6.32384 21.3106 6.70456L22.6894 7.29544ZM19 11.1288L18.4867 10.582V10.582L19 11.1288ZM19.9697 13.1592C20.2626 13.4521 20.7374 13.4521 21.0303 13.1592C21.3232 12.8663 21.3232 12.3914 21.0303 12.0985L19.9697 13.1592ZM11.25 16.5C11.25 16.9142 11.5858 17.25 12 17.25C12.4142 17.25 12.75 16.9142 12.75 16.5H11.25ZM16.3714 15.909C16.5973 16.2562 17.0619 16.3545 17.409 16.1286C17.7562 15.9027 17.8545 15.4381 17.6286 15.091L16.3714 15.909ZM5.53033 11.6592C5.82322 11.3663 5.82322 10.8914 5.53033 10.5985C5.23744 10.3056 4.76256 10.3056 4.46967 10.5985L5.53033 11.6592ZM2.96967 12.0985C2.67678 12.3914 2.67678 12.8663 2.96967 13.1592C3.26256 13.4521 3.73744 13.4521 4.03033 13.1592L2.96967 12.0985ZM12 13.25C8.77611 13.25 6.46133 11.6446 4.9246 9.98966C4.15645 9.16243 3.59325 8.33284 3.22259 7.71014C3.03769 7.3995 2.90187 7.14232 2.8134 6.96537C2.76919 6.87696 2.73689 6.80875 2.71627 6.76411C2.70597 6.7418 2.69859 6.7254 2.69411 6.71533C2.69187 6.7103 2.69036 6.70684 2.68957 6.70503C2.68917 6.70413 2.68896 6.70363 2.68892 6.70355C2.68891 6.70351 2.68893 6.70357 2.68901 6.70374C2.68904 6.70382 2.68913 6.70403 2.68915 6.70407C2.68925 6.7043 2.68936 6.70456 2 7C1.31064 7.29544 1.31077 7.29575 1.31092 7.29609C1.31098 7.29624 1.31114 7.2966 1.31127 7.2969C1.31152 7.29749 1.31183 7.2982 1.31218 7.299C1.31287 7.30062 1.31376 7.30266 1.31483 7.30512C1.31698 7.31003 1.31988 7.31662 1.32353 7.32483C1.33083 7.34125 1.34115 7.36415 1.35453 7.39311C1.38127 7.45102 1.42026 7.5332 1.47176 7.63619C1.57469 7.84206 1.72794 8.13175 1.93366 8.47736C2.34425 9.16716 2.96855 10.0876 3.8254 11.0103C5.53867 12.8554 8.22389 14.75 12 14.75V13.25ZM15.3125 12.6308C14.3421 13.0128 13.2417 13.25 12 13.25V14.75C13.4382 14.75 14.7246 14.4742 15.8619 14.0266L15.3125 12.6308ZM7.78417 12.9197L6.37136 15.091L7.62864 15.909L9.04145 13.7377L7.78417 12.9197ZM22 7C21.3106 6.70456 21.3107 6.70441 21.3108 6.70427C21.3108 6.70423 21.3108 6.7041 21.3109 6.70402C21.3109 6.70388 21.311 6.70376 21.311 6.70368C21.3111 6.70352 21.3111 6.70349 21.3111 6.7036C21.311 6.7038 21.3107 6.70452 21.3101 6.70576C21.309 6.70823 21.307 6.71275 21.3041 6.71924C21.2983 6.73223 21.2889 6.75309 21.2758 6.78125C21.2495 6.83757 21.2086 6.92295 21.1526 7.03267C21.0406 7.25227 20.869 7.56831 20.6354 7.9432C20.1669 8.69516 19.4563 9.67197 18.4867 10.582L19.5133 11.6757C20.6023 10.6535 21.3917 9.56587 21.9085 8.73646C22.1676 8.32068 22.36 7.9668 22.4889 7.71415C22.5533 7.58775 22.602 7.48643 22.6353 7.41507C22.6519 7.37939 22.6647 7.35118 22.6737 7.33104C22.6782 7.32097 22.6818 7.31292 22.6844 7.30696C22.6857 7.30398 22.6867 7.30153 22.6876 7.2996C22.688 7.29864 22.6883 7.29781 22.6886 7.29712C22.6888 7.29677 22.6889 7.29646 22.689 7.29618C22.6891 7.29604 22.6892 7.29585 22.6892 7.29578C22.6893 7.29561 22.6894 7.29544 22 7ZM18.4867 10.582C17.6277 11.3882 16.5739 12.1343 15.3125 12.6308L15.8619 14.0266C17.3355 13.4466 18.5466 12.583 19.5133 11.6757L18.4867 10.582ZM18.4697 11.6592L19.9697 13.1592L21.0303 12.0985L19.5303 10.5985L18.4697 11.6592ZM11.25 14V16.5H12.75V14H11.25ZM14.9586 13.7377L16.3714 15.909L17.6286 15.091L16.2158 12.9197L14.9586 13.7377ZM4.46967 10.5985L2.96967 12.0985L4.03033 13.1592L5.53033 11.6592L4.46967 10.5985Z'
       fill={color}
     />
   </svg>
-);
+));
+
+ClosedEye.displayName = 'ClosedEye';

39-66: Apply same accessibility and performance improvements to OpenEye component

Similar improvements as ClosedEye component:

-const OpenEye = ({ color, size = 20 }: IconProps) => (
+const OpenEye = React.memo(({ color, size = 20 }: IconProps) => (
   <svg
     fill={color}
     height={`${size}px`}
     id='Capa_1'
     version='1.1'
     viewBox='0 0 448.004 448.004'
     width={`${size}px`}
     xmlSpace='preserve'
     xmlns='http://www.w3.org/2000/svg'
+    role="img"
+    aria-label="Visible eye icon"
   >
     <g>
       <path d='M46.139,217.607l-17.93-20.798C18.766,185.932,9.443,175.054,0,164.057l17.212-14.822
   c9.323,10.877,18.767,21.755,28.209,32.632l17.93,20.798L46.139,217.607z M145.589,159.157l-24.265-66.34l-21.277,7.77
   l24.265,66.34L145.589,159.157z M235.357,76.799h-22.711v70.643h22.711V76.799z M347.955,100.586l-21.275-7.77l-24.266,66.34
   l21.277,7.77L347.955,100.586z M448.004,164.057l-17.213-14.822l-46.139,53.55l17.211,14.822L448.004,164.057z M404.852,268.049
   l6.455,7.65l-6.455,7.649c-0.717,0.957-18.885,22.353-49.963,43.868c-41.598,28.808-86.779,43.987-130.768,43.987
   c-43.988,0-89.29-15.18-130.767-43.987c-31.078-21.516-49.247-43.031-49.964-43.868l-6.455-7.649l6.455-7.65
   c0.717-0.956,18.886-22.353,49.964-43.867c41.597-28.808,86.779-43.988,130.767-43.988c43.988,0,89.289,15.181,130.768,43.988
   C385.967,245.697,404.016,267.212,404.852,268.049z M286.039,275.7c0-34.306-27.732-62.037-62.038-62.037
   c-34.306,0-62.037,27.731-62.037,62.037s27.731,62.036,62.037,62.036C258.307,337.856,286.039,310.005,286.039,275.7z
    M224.001,294.585c-10.399,0-18.886-8.486-18.886-18.886s8.486-18.886,18.886-18.886v-23.906
   c-23.548,0-42.792,19.244-42.792,42.792s19.244,42.792,42.792,42.792c23.547,0,42.792-19.244,42.792-42.792h-23.906
   C242.887,286.218,234.4,294.585,224.001,294.585z'
       />
     </g>
   </svg>
-);
+));
+
+OpenEye.displayName = 'OpenEye';
packages/extension-polkagate/src/components/Loading.tsx (1)

69-87: LGTM with suggestions for improvements.

The implementation correctly handles Chrome storage changes and provides proper cleanup. However, consider these improvements:

  1. Add error handling for JSON parsing
  2. Add type safety for the callback and return value

Consider applying this diff:

-export const watchStorage = (label: string, setChanges: (value: any) => void, parse = false) => {
+export const watchStorage = <T = unknown>(
+  label: string,
+  setChanges: (value: T) => void,
+  parse = false
+): () => void => {
   // eslint-disable-next-line no-undef
   const listener = (changes: Record<string, chrome.storage.StorageChange>, areaName: 'sync' | 'local' | 'managed' | 'session') => {
     if (areaName === 'local' && label in changes) {
-      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
       const change = changes[label];
-      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
       const newValue = change.newValue; // This is optional, so handle accordingly

-      setChanges(parse ? JSON.parse((newValue || '{}') as string) : newValue);
+      try {
+        const parsedValue = parse ? JSON.parse((newValue || '{}') as string) : newValue;
+        setChanges(parsedValue as T);
+      } catch (error) {
+        console.error(`Error parsing storage value for ${label}:`, error);
+        setChanges(newValue as T);
+      }
     }
   };

   chrome.storage.onChanged.addListener(listener);

   return () => {
     chrome.storage.onChanged.removeListener(listener);
   };
 };
packages/extension-polkagate/src/hooks/useAssetsBalances.ts (3)

262-266: LGTM! Proper cleanup of storage subscription

The changes correctly implement the cleanup pattern for the watchStorage subscription, preventing potential memory leaks when the component unmounts or when dependencies change.

Consider adding similar cleanup patterns to other worker subscriptions in this file. For example:

  useEffect(() => {
    if (!SHOULD_FETCH_ASSETS || !addresses || addresses.length === 0 || isWorking || isUpdate || !selectedChains || isTestnetEnabled === undefined) {
      return;
    }

    const _selectedChains = isTestnetEnabled ? selectedChains : selectedChains.filter((genesisHash) => !TEST_NETS.includes(genesisHash));
    const multipleAssetsChainsNames = Object.keys(assetsChains);

    const singleAssetChains = genesisOptions.filter(({ text, value }) =>
      _selectedChains.includes(value as string) &&
      !ASSET_HUBS.includes(value as string) &&
      !RELAY_CHAINS_GENESISHASH.includes(value as string) &&
      !multipleAssetsChainsNames.includes(toCamelCase(text) || '')
    );

+   const workers: Worker[] = [];

    /** Fetch assets for all the selected chains by default */
    _selectedChains?.forEach((genesisHash) => {
      const isSingleTokenChain = !!singleAssetChains.find(({ value }) => value === genesisHash);
      const maybeMultiAssetChainName = multipleAssetsChainsNames.find((chainName) => chainName === getChainName(genesisHash));

      fetchAssets(genesisHash, isSingleTokenChain, maybeMultiAssetChainName);
+     workers.push(worker);
    });

+   return () => {
+     workers.forEach((worker) => worker.terminate());
+   };
  }, [SHOULD_FETCH_ASSETS, addresses, fetchAssets, isTestnetEnabled, isUpdate, isWorking, selectedChains, genesisOptions]);

262-266: Consider centralizing worker lifecycle management

The current implementation manages worker termination in individual message handlers, which could lead to worker leaks if the component unmounts before messages are received. Consider implementing a centralized worker management system.

Here's a suggested approach:

  1. Create a worker pool manager hook:
function useWorkerPool() {
  const workers = useRef<Worker[]>([]);
  
  const addWorker = useCallback((worker: Worker) => {
    workers.current.push(worker);
  }, []);
  
  const removeWorker = useCallback((worker: Worker) => {
    const index = workers.current.indexOf(worker);
    if (index > -1) {
      workers.current.splice(index, 1);
    }
  }, []);
  
  useEffect(() => {
    return () => {
      workers.current.forEach(worker => worker.terminate());
      workers.current = [];
    };
  }, []);
  
  return { addWorker, removeWorker };
}
  1. Use it in your hook:
const { addWorker, removeWorker } = useWorkerPool();

const fetchAssetOnRelayChain = useCallback((_addresses: string[], chainName: string) => {
  const worker: Worker = new Worker(...);
  addWorker(worker);
  
  worker.onmessage = (e) => {
    // ... existing logic ...
    removeWorker(worker);
    worker.terminate();
  };
}, [addWorker, removeWorker]);

Line range hint 379-381: Improve error handling for worker operations

The current error handling for workers is minimal and doesn't provide adequate user feedback.

Consider implementing more robust error handling:

  worker.onerror = (err) => {
-   console.log(err);
+   console.error('Asset fetch failed:', err);
+   setAlerts((prev) => [...prev, {
+     id: random.string({ length: 10 }),
+     severity: 'error',
+     text: t('Failed to fetch assets: {{error}}', { error: err.message })
+   }]);
+   handleSetWorkersCall(worker, 'terminate');
  };
packages/extension-ui/src/Popup/index.tsx (2)

Line range hint 231-269: Consider improving price fetching implementation.

The current implementation uses a ref to track the fetching state, which makes the code harder to test and maintain. Consider these improvements:

  1. Move the fetching state to component state
  2. Add error handling and retry logic
  3. Add loading state to prevent UI jank

Here's a suggested implementation:

- const isFetchingPricesRef = useRef(false);
+ const [isFetchingPrices, setIsFetchingPrices] = useState(false);
+ const [priceError, setPriceError] = useState<Error | null>(null);

  useEffect(() => {
-   if (priceIds && currency?.code && !isFetchingPricesRef.current) {
-     isFetchingPricesRef.current = true;
+   if (priceIds && currency?.code && !isFetchingPrices) {
+     setIsFetchingPrices(true);
+     setPriceError(null);

      getStorage('pricesInCurrencies')
        .then((res) => {
          const savedPricesInCurrencies = (res || {}) as PricesInCurrencies;
          const maybeSavedPriceInCurrentCurrencyCode = savedPricesInCurrencies[currency.code];

          if (maybeSavedPriceInCurrentCurrencyCode && isPriceUpToDate(maybeSavedPriceInCurrentCurrencyCode.date)) {
            return;
          }

          return getPrices(priceIds, currency.code.toLowerCase())
            .then((newPrices) => {
              delete (newPrices as Prices).currencyCode;
              savedPricesInCurrencies[currency.code] = newPrices;
              return setStorage('pricesInCurrencies', savedPricesInCurrencies);
            });
        })
-       .catch(console.error)
+       .catch((error: Error) => {
+         console.error(error);
+         setPriceError(error);
+       })
        .finally(() => {
-         isFetchingPricesRef.current = false;
+         setIsFetchingPrices(false);
        });
    }
-  }, [currency?.code, priceIds]);
+  }, [currency?.code, priceIds, isFetchingPrices]);

Line range hint 319-326: Consider improving error boundary implementation.

The current implementation of wrapWithErrorBoundary could be improved to:

  1. Move AlertBox outside the error boundary wrapper to prevent duplication
  2. Use route paths as dynamic triggers instead of hardcoded strings

Here's a suggested implementation:

  const wrapWithErrorBoundary = useCallback((component: React.ReactElement, trigger?: string): React.ReactElement => {
-   return <ErrorBoundary trigger={trigger}>
-     <>
-       {component}
-       {!isExtensionMode && <AlertBox />}
-     </>
-   </ErrorBoundary>;
+   return (
+     <>
+       <ErrorBoundary trigger={trigger}>
+         {component}
+       </ErrorBoundary>
+       {!isExtensionMode && <AlertBox />}
+     </>
+   );
  }, [isExtensionMode]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 549b3cb and 99c5334.

📒 Files selected for processing (14)
  • packages/extension-polkagate/src/components/Loading.tsx (1 hunks)
  • packages/extension-polkagate/src/components/SVG/HideBalance.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx (3 hunks)
  • packages/extension-polkagate/src/hooks/useAssetsBalances.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useCurrency.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useIsHideNumbers.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/usePrices.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useProfileAccounts.tsx (1 hunks)
  • packages/extension-polkagate/src/hooks/useSelectedChains.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useSelectedProfile.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/home/AccountLabel.tsx (3 hunks)
  • packages/extension-polkagate/src/popup/home/ProfileTabs.tsx (1 hunks)
  • packages/extension-ui/src/Popup/index.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx
  • packages/extension-polkagate/src/fullscreen/homeFullScreen/partials/ProfileTabFullScreen.tsx
  • packages/extension-polkagate/src/hooks/useIsHideNumbers.ts
🔇 Additional comments (7)
packages/extension-polkagate/src/hooks/useSelectedProfile.tsx (1)

19-23: Great addition of cleanup logic!

The implementation of proper cleanup for the storage subscription is a crucial improvement that prevents potential memory leaks. This pattern aligns with React's best practices for effect cleanup.

Let's verify if this cleanup pattern is consistently implemented across other similar hooks:

✅ Verification successful

Cleanup pattern is consistently implemented across all watchStorage usages

The verification confirms that all instances of watchStorage are properly implemented with cleanup in their respective useEffect hooks. Every usage follows the same pattern:

  1. The unsubscribe function is captured from watchStorage call
  2. A cleanup function is returned from useEffect that calls unsubscribe
  3. This pattern is consistently implemented across all files:
    • useSelectedProfile.tsx
    • useSelectedChains.ts
    • useProfileAccounts.tsx
    • usePrices.ts
    • useIsHideNumbers.ts
    • useCurrency.ts
    • ProfileTabs.tsx
    • ProfileTabFullScreen.tsx
    • Popup/index.tsx

The implementation in the review comment aligns with the codebase-wide pattern for proper cleanup of storage subscriptions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if other hooks properly implement the watchStorage cleanup pattern
# Expected: All hooks using watchStorage should have similar cleanup implementation

ast-grep --pattern 'const unsubscribe = watchStorage($_, $_)'

# Also check for any remaining direct watchStorage calls without cleanup
ast-grep --pattern 'watchStorage($_, $_)' | grep -v 'const unsubscribe'

Length of output: 1328


Script:

#!/bin/bash
# Let's verify if all these watchStorage usages have proper cleanup in their useEffect
# We'll check the surrounding context of each file

# Check cleanup pattern in useEffect
ast-grep --pattern 'useEffect(() => {
  $$$
  const unsubscribe = watchStorage($_, $_);
  $$$
  return () => {
    $$$
    unsubscribe();
    $$$
  };
}, $$$);'

# Also check for any watchStorage usage outside useEffect or without cleanup
rg "watchStorage" -A 5 -B 5

Length of output: 31066

packages/extension-polkagate/src/hooks/useCurrency.ts (1)

25-29: LGTM! Important cleanup implementation.

This is a crucial improvement that properly handles the cleanup of storage subscription, preventing potential memory leaks when the component unmounts.

Let's verify that similar cleanup patterns are implemented in other hooks mentioned in the summary:

✅ Verification successful

The initial results don't show the complete implementation of these hooks. We need to see the full context of watchStorage usage and useEffect cleanup patterns to verify consistent implementation across hooks.


Let's try without file type restrictions since the previous attempt failed. This should help us see the implementation patterns across hooks.


Based on the search results, I can now generate the final response:

Cleanup implementation is consistent across hooks using watchStorage

The cleanup pattern is correctly and consistently implemented across all hooks that use watchStorage subscriptions:

  • useCurrency.ts
  • usePrices.ts
  • useSelectedProfile.ts
  • useSelectedChains.ts
  • useProfileAccounts.ts
  • useIsHideNumbers.ts
  • useAssetsBalances.ts

All implementations follow the same pattern:

const unsubscribe = watchStorage(...);
return () => { unsubscribe(); };
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent implementation of storage subscription cleanup across related hooks
# Expected: All hooks should implement similar cleanup pattern with unsubscribe

# Search for hooks using watchStorage
ast-grep --pattern 'const unsubscribe = watchStorage($_, $_)
  $$$
  return () => {
    unsubscribe();
  };'

# Specifically check the mentioned hooks
for hook in useAssetsBalances usePrices useProfileAccounts useSelectedChains useSelectedProfile; do
  echo "Checking $hook implementation:"
  rg -A 5 "function $hook" packages/extension-polkagate/src/hooks/
done

Length of output: 4737


Script:

#!/bin/bash
# Let's search for watchStorage usage and verify cleanup patterns
rg -B 2 -A 5 "watchStorage\(" packages/extension-polkagate/src/hooks/ --type ts --type tsx

# Also check for useEffect cleanup patterns in these files
rg -B 2 -A 5 "useEffect\(" packages/extension-polkagate/src/hooks/ --type ts --type tsx

Length of output: 238


Script:

#!/bin/bash
# Search for watchStorage usage and cleanup patterns without file type restrictions
rg -B 2 -A 5 "watchStorage\(" packages/extension-polkagate/src/hooks/

# Check for useEffect cleanup patterns
rg -B 2 -A 5 "useEffect\(" packages/extension-polkagate/src/hooks/

# Also try to find all files that might use watchStorage
fd . packages/extension-polkagate/src/hooks/ -t f -x cat {} \; | grep -A 5 -B 2 "watchStorage"

Length of output: 105635

packages/extension-polkagate/src/hooks/usePrices.ts (1)

34-38: LGTM! Proper cleanup implementation.

The addition of the unsubscribe cleanup function in useEffect is a crucial improvement that prevents potential memory leaks and follows React's best practices for managing subscriptions.

packages/extension-polkagate/src/hooks/useProfileAccounts.tsx (1)

40-44: Verify consistent implementation across related hooks.

Let's ensure this cleanup pattern is consistently implemented across all hooks using watchStorage.

✅ Verification successful

Cleanup pattern is consistently implemented across all watchStorage usages

The verification shows that all 10 instances of watchStorage usage across the codebase follow the same consistent cleanup pattern:

  • Proper unsubscribe variable declaration
  • Correct cleanup function in useEffect's return
  • Consistent unsubscribe() call within the cleanup

This confirms that the cleanup pattern in useProfileAccounts.tsx aligns with the established pattern throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check implementation consistency across hooks using watchStorage

# Search for all hooks using watchStorage
echo "Checking hooks using watchStorage..."
ast-grep --pattern 'const $_ = watchStorage($$$)'

# Search for cleanup implementations
echo "\nChecking cleanup implementations..."
rg -B 2 -A 2 'const \w+ = watchStorage.*\n.*\n.*return \(\) => \{.*unsubscribe'

Length of output: 1834


Script:

#!/bin/bash
# Let's modify the search pattern to correctly find cleanup implementations

# Search for cleanup implementations with proper regex
echo "Checking cleanup implementations..."
rg -U -B 2 -A 2 'const \w+ = watchStorage.*[\s\S]*?return \(\) => \{[\s\S]*?unsubscribe'

# Alternative search to catch any variations
echo "\nChecking alternative cleanup patterns..."
rg -U -B 2 -A 2 'useEffect\([^)]*\) => \{.*watchStorage.*return'

Length of output: 6869

packages/extension-polkagate/src/popup/home/AccountLabel.tsx (2)

17-17: LGTM: Props interface extension

The addition of the optional right prop and its implementation in the component signature provides more flexibility for positioning while maintaining type safety.

Also applies to: 20-20


Line range hint 93-112: LGTM: Scroll behavior implementation

The scroll behavior implementation is well-done with proper event listener management, cleanup, and conditional scrolling based on content width.

packages/extension-ui/src/Popup/index.tsx (1)

170-174: LGTM! Proper cleanup implementation for storage subscription.

The implementation correctly handles the cleanup of the storage subscription by storing and calling the unsubscribe function when the component unmounts. This prevents potential memory leaks.

@Nick-1979 Nick-1979 merged commit dd51064 into main Nov 14, 2024
3 checks passed
@Nick-1979 Nick-1979 deleted the minimalDarkTheme branch November 14, 2024 09:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants