Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: shake account icons once on activation #1603

Merged
merged 3 commits into from
Oct 24, 2024
Merged

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Oct 23, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a custom hook, useAnimateOnce, for managing one-time animations based on conditions.
    • Added a new localization string for displaying comment counts in the user interface.
  • Bug Fixes

    • Improved error handling for identity and social recovery functions.
  • Refactor

    • Enhanced type safety in the AccountIconsFs component and updated function signatures for clarity.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF October 23, 2024 08:14
Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

This pull request introduces several modifications across multiple files. The AccountIconsFs component is updated to enhance type safety, improve error handling, and incorporate a new animation hook. A new localization string is added to the translation.json file. Additionally, a new custom hook, useAnimateOnce, is created to manage one-time animations based on conditions, and it is exported from the hooks index file. These changes collectively aim to refine the component's functionality and user interface.

Changes

File Change Summary
packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx - Updated function signature and removed export default from declaration.
- Modified useEffect to use bracket notation for api.query.
- Improved error handling in windowOpen functions.
- Integrated useAnimateOnce for animations.
packages/extension/public/locales/en/translation.json - Added new localization entry: "Comments ({{count}})": "".
packages/extension-polkagate/src/hooks/index.ts - Exported new hook: useAnimateOnce.
packages/extension-polkagate/src/hooks/useAnimateOnce.tsx - Introduced useAnimateOnce hook to manage one-time animation states based on a condition.

Possibly related PRs

Suggested reviewers

  • AMIRKHANEF

Poem

🐰 In the meadow where icons play,
New hooks dance in a bright ballet.
With animations that leap and twirl,
Comments counted in a joyful whirl.
Type safety shines, errors take flight,
A rabbit's cheer for code done right! 🌼


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

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

6-7: Consider validating the condition parameter

The condition parameter accepts undefined but the implementation doesn't handle this case explicitly. Consider adding validation or documenting the behavior.

-export default function useAnimateOnce (condition: boolean | undefined): boolean {
+export default function useAnimateOnce (condition: boolean): boolean {
   const [animate, setAnimate] = useState(false);
packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx (1)

103-119: Consider using optional chaining for API queries.

While the bracket notation works, optional chaining might be more readable for API queries.

-if (api.query?.['recovery'] && SOCIAL_RECOVERY_CHAINS.includes(account.genesisHash)) {
+if (api.query?.recovery && SOCIAL_RECOVERY_CHAINS.includes(account.genesisHash)) {
   api.query.recovery.recoverable(formatted)

Also, consider extracting the type assertions into helper functions for better maintainability:

const parseProxies = (result: unknown): Proxy[] => {
  const [announcements] = result as [Vec<PalletProxyAnnouncement>, u128];
  return JSON.parse(JSON.stringify(announcements)) as Proxy[];
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9d22ab9 and 67502d2.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx (7 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/useAnimateOnce.tsx (1 hunks)
  • packages/extension/public/locales/en/translation.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/extension/public/locales/en/translation.json
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx

[error] 10-10: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (2)
packages/extension-polkagate/src/fullscreen/accountDetails/components/useAnimateOnce.tsx (1)

1-4: LGTM: Proper license and imports

The file includes the correct license header and necessary React imports.

packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx (1)

39-41: LGTM! Clean hook implementation for animations.

The animation states are properly separated for each icon type, following React best practices.

@Nick-1979 Nick-1979 self-assigned this Oct 23, 2024
Nick-1979 and others added 2 commits October 23, 2024 12:21
* refactor: optimize useAnimateOnce

* refactor: remove unused

---------

Co-authored-by: Nick <[email protected]>
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: 4

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/hooks/useAnimateOnce.tsx (1)

6-17: Consider defining defaults in the interface.

While the current implementation is correct, consider moving the default values into the interface definition for better maintainability and type documentation.

 interface AnimateOnceConfig {
-  duration?: number;
-  delay?: number;
+  duration?: number; // defaults to 500
+  delay?: number; // defaults to 0
   onStart?: () => void;
   onComplete?: () => void;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cf333b9 and b5d7a97.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx (8 hunks)
  • packages/extension-polkagate/src/hooks/index.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useAnimateOnce.tsx (1 hunks)
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx

[error] 10-10: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (7)
packages/extension-polkagate/src/hooks/useAnimateOnce.tsx (2)

1-4: LGTM! Imports and header are properly structured.

The file includes appropriate copyright notice, license information, and necessary React hook imports.


53-59: LGTM! Effect cleanup is properly implemented.

The useEffect hook properly handles cleanup on unmount and dependency changes.

packages/extension-polkagate/src/fullscreen/accountDetails/components/AccountIconsFs.tsx (4)

18-18: LGTM! Good performance optimization.

The component is now properly memoized using React.memo, which can help prevent unnecessary re-renders.

Also applies to: 27-27, 187-188


38-40: LGTM! Animation states are properly managed.

The useAnimateOnce hook is correctly applied to manage the shake animations for each icon.


102-105: LGTM! Improved type safety and API access.

Good improvements:

  • Using bracket notation for API queries is more robust
  • Type assertions properly handle the query results

Also applies to: 111-115


144-144: LGTM! Animation props are properly implemented.

The shake animations are correctly bound to their respective states through the FontAwesomeIcon components.

Also applies to: 149-149, 167-167, 178-178

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

16-16: LGTM! Verify the hook implementation.

The export statement follows the established patterns in the file and is correctly placed in alphabetical order.

Let's verify that the hook implementation exists:

✅ Verification successful

Let me gather more information about the hook implementation since we found the file but need to verify its contents.

The previous results confirmed the file exists but with a .tsx extension. Let's examine its contents to ensure it exports a default function and follows proper hook implementation patterns before making a final decision.


Hook implementation verified and follows best practices

The hook implementation exists and is well-implemented with:

  • Proper TypeScript types and interfaces
  • Accessibility consideration (prefers-reduced-motion)
  • Proper cleanup of timeouts
  • Default exports as expected
  • Comprehensive JSDoc documentation
  • Follows React hooks best practices (useCallback, useEffect, useRef)

The export in the barrel file correctly matches this implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the useAnimateOnce hook implementation exists and exports a default.

# Test 1: Check if the hook file exists
fd -t f "useAnimateOnce.ts" -x echo "Hook file found: {}"

# Test 2: Verify the hook exports a default
ast-grep --pattern 'export default function useAnimateOnce'

Length of output: 196


Script:

#!/bin/bash
# Check the actual implementation of useAnimateOnce hook
cat ./packages/extension-polkagate/src/hooks/useAnimateOnce.tsx

Length of output: 1924

Comment on lines +25 to +26
export default function useAnimateOnce (condition: boolean | undefined, config: AnimateOnceConfig = {}): boolean {
const [animate, setAnimate] = useState(false);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider stricter typing for the condition parameter.

The condition parameter accepts undefined, which might lead to unexpected behavior. Consider making it strictly boolean.

-export default function useAnimateOnce (condition: boolean | undefined, config: AnimateOnceConfig = {}): boolean {
+export default function useAnimateOnce (condition: boolean, config: AnimateOnceConfig = {}): boolean {
📝 Committable suggestion

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

Suggested change
export default function useAnimateOnce (condition: boolean | undefined, config: AnimateOnceConfig = {}): boolean {
const [animate, setAnimate] = useState(false);
export default function useAnimateOnce (condition: boolean, config: AnimateOnceConfig = {}): boolean {
const [animate, setAnimate] = useState(false);

Comment on lines +35 to +40
const cleanup = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
}
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance cleanup implementation.

The cleanup function should also reset the animation state to ensure consistent behavior during unmount or when dependencies change.

 const cleanup = useCallback(() => {
   if (timeoutRef.current) {
     clearTimeout(timeoutRef.current);
     timeoutRef.current = undefined;
+    setAnimate(false);
   }
 }, []);

Committable suggestion was skipped due to low confidence.

Comment on lines +31 to +32
// Check if the user prefers reduced motion
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility check implementation.

The current implementation checks motion preferences only once during initialization. Consider using a more robust solution that can react to preference changes.

-const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
+const [prefersReducedMotion, setPrefersReducedMotion] = useState(mediaQuery.matches);
+
+useEffect(() => {
+  const handler = (event: MediaQueryListEvent) => {
+    setPrefersReducedMotion(event.matches);
+  };
+  
+  mediaQuery.addEventListener('change', handler);
+  return () => mediaQuery.removeEventListener('change', handler);
+}, []);
📝 Committable suggestion

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

Suggested change
// Check if the user prefers reduced motion
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Check if the user prefers reduced motion
const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
const [prefersReducedMotion, setPrefersReducedMotion] = useState(mediaQuery.matches);
useEffect(() => {
const handler = (event: MediaQueryListEvent) => {
setPrefersReducedMotion(event.matches);
};
mediaQuery.addEventListener('change', handler);
return () => mediaQuery.removeEventListener('change', handler);
}, []);

Comment on lines +6 to +9
import type { DeriveAccountInfo } from '@polkadot/api-derive/types';
import type { Option, u128, Vec } from '@polkadot/types';
//@ts-ignore
import type { PalletProxyAnnouncement, PalletRecoveryActiveRecovery } from '@polkadot/types/lookup';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type shadowing and improve type imports.

The imported Proxy type shadows the global Proxy object, which could lead to confusion. Consider renaming it to be more specific.

-import type { Proxy } from '../../../util/types';
+import type { AccountProxy } from '../../../util/types';

// Update usage of Proxy type to AccountProxy throughout the file
-const fetchedProxies = JSON.parse(JSON.stringify(_p[0])) as unknown as Proxy[];
+const fetchedProxies = JSON.parse(JSON.stringify(_p[0])) as unknown as AccountProxy[];

Committable suggestion was skipped due to low confidence.

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