-
Notifications
You must be signed in to change notification settings - Fork 5
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
refactor: use SimpleModalTitle component #1557
Conversation
WalkthroughThe pull request introduces various modifications across multiple components in the governance section of the application. Key changes include type adjustments for props, restructuring of modal titles, and enhancements to timeout handling in event functions. Additionally, the updates focus on improving code clarity and maintainability by removing unused imports, consolidating rendering logic, and ensuring type safety throughout the components. Changes
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 (14)
packages/extension-polkagate/src/popup/receive/ReceiveModal.tsx (2)
20-20
: Minor formatting change in function signatureThe spacing in the function signature has been adjusted. While this doesn't affect functionality, it's worth noting for consistency. Ensure this formatting aligns with the project's style guide.
49-56
: LGTM: Improved QRCode rendering with conditional checkThe addition of a conditional check before rendering the QRCode component is a good safety measure. It prevents potential errors that could occur if the
formatted
variable is falsy.Consider extracting the QRCode styling into a separate object or theme to improve readability and maintainability. For example:
const qrCodeStyle = { bgColor: theme.palette.background.paper, fgColor: theme.palette.text.primary, level: 'H', size: 275 }; // Then in the JSX: <QRCode {...qrCodeStyle} value={formatted} />This approach would make it easier to adjust the QRCode styling in the future and keep the JSX cleaner.
packages/extension-polkagate/src/fullscreen/governance/Toolbar.tsx (2)
49-54
: LGTM: Simplified timeout handlingThe changes in
onTopMenuMenuMouseEnter
simplify the timeout clearing logic and align with the updatedtimeoutId
type. The use ofas unknown as number
is a valid workaround for TypeScript's typing ofsetTimeout
.Consider creating a custom hook for managing timeouts to encapsulate this logic and improve reusability. For example:
function useTimeout(callback: () => void, delay: number) { const timeoutRef = useRef<number | null>(null); const set = useCallback(() => { timeoutRef.current = setTimeout(callback, delay) as unknown as number; }, [callback, delay]); const clear = useCallback(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }, []); return { set, clear }; }This would allow you to simplify the
onTopMenuMenuMouseEnter
function and make the timeout management more consistent across the component.
102-102
: LGTM: Improved theme responsivenessThe update to the
borderColor
property using a ternary operator based on the theme mode is a good improvement. It enhances the component's adaptability to different theme settings.For consistency and potential reusability, consider extracting the theme-dependent styles into a separate object or custom hook. This approach could be applied to other theme-dependent properties as well. For example:
const useToolbarStyles = (theme) => ({ borderColor: theme.palette.mode === 'dark' ? 'primary.main' : undefined, backgroundColor: theme.palette.mode === 'light' ? 'primary.main' : 'background.paper', // ... other theme-dependent styles }); // In your component const styles = useToolbarStyles(theme); // Then use it in your JSX <Grid ... sx={{ ...styles, /* other styles */ }}>This would centralize your theme-dependent styles and make them easier to manage and reuse across components.
packages/extension-polkagate/src/fullscreen/governance/delegate/partial/Confirmation.tsx (4)
21-24
: LGTM! Consider using optional chaining for consistency.The changes to the
Props
interface improve type safety by allowingundefined
values fordelegateInformation
,allCategoriesLength
, andremovedTracksLength
. This is a good practice when these values might not always be available.For consistency with TypeScript conventions, consider using optional chaining for
removedTracksLength
:removedTracksLength?: number;This achieves the same effect as
number | undefined
while being more concise.
106-109
: LGTM! Consider extracting the conviction logic for better readability.The changes correctly implement optional chaining to handle potentially undefined values of
delegateInformation.delegateConviction
. The ternary operator provides a fallback value when the conviction is 0.To improve readability, consider extracting the conviction logic into a separate variable:
const conviction = delegateInformation?.delegateConviction; const displayConviction = conviction === 0 ? 0.1 : conviction; <DisplayInfo caption={t('Vote multiplier:')} value={t(`${displayConviction}x`)} />This separation makes the logic easier to understand at a glance.
114-114
: LGTM! Consider extracting the logic for better readability.The changes correctly handle different statuses and use optional chaining for
delegateInformation?.delegatedTracks.length
. This aligns well with the updates to theProps
interface.To improve readability, consider extracting the logic into a separate variable:
const categoriesCount = status === 'Remove' && removedTracksLength ? removedTracksLength : delegateInformation?.delegatedTracks.length; <DisplayInfo caption={t('Number of referenda categories:')} value={t(`${categoriesCount} of ${allCategoriesLength}`, { replace: { token } })} />This separation makes the logic easier to understand and maintain.
116-116
: LGTM! Consider using a consistent format for the fallback value.The changes correctly implement optional chaining and nullish coalescing to handle cases where
fee
might be undefined or null. This is a good practice for ensuring robust rendering.For consistency with the rest of the codebase, consider formatting the fallback value to match the expected format of
fee.toHuman()
:<DisplayInfo caption={t('Fee:')} value={fee?.toHuman() as string ?? '0.00 Unit'} />Replace 'Unit' with the appropriate token symbol if available. This ensures that even the fallback value maintains the expected format.
packages/extension-polkagate/src/fullscreen/governance/post/castVote/Review.tsx (2)
Line range hint
46-55
: Improved function signature and variable handling.The updated function signature using object destructuring enhances code readability. The fallback for the
status
variable is a good practice to prevent potential undefined errors.Consider using the nullish coalescing operator for a more concise fallback:
- const isOngoing = !ENDED_STATUSES.includes(status || ''); + const isOngoing = !ENDED_STATUSES.includes(status ?? '');This change makes the intent clearer and is slightly more performant.
14-14
: Consider renaming the "Proxy" type to avoid shadowing.The static analysis tool flagged a potential issue with shadowing the global "Proxy" property. While this is likely a false positive given the context of your application, it's worth considering a more specific name to avoid any potential confusion.
If "Proxy" is a well-established term in your project's domain, you might want to keep it. However, if you decide to rename, consider something more specific like
GovernanceProxy
orVotingProxy
to clearly differentiate it from the globalProxy
object.🧰 Tools
🪛 Biome
[error] 14-14: 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)
packages/extension-polkagate/src/fullscreen/governance/post/castVote/index.tsx (1)
119-148
: LGTM: Improved title handling with useMemo.The addition of the
useMemo
hook for calculating the title based on the current step is a good improvement. It centralizes the title logic, potentially improves performance, and makes the component more maintainable.Consider adding a default case to the switch statement to handle any unexpected step values:
default: console.warn(`Unexpected step value: ${step}`); return t('Unknown Step');This would provide a fallback title and log a warning for debugging purposes.
packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx (3)
169-171
: Consider simplifying thehandleClose
logic for better readability.The modification to
handleClose
improves the control flow, but the ternary operator might be a bit confusing. Consider refactoring it for better clarity:const handleClose = useCallback(() => { if (step === STEPS.PROXY && proxyStep) { setStep(proxyStep); } else { setOpen(false); } }, [proxyStep, setOpen, step]);This version makes the logic more explicit and easier to understand at a glance.
205-207
: LGTM: Type casting improves type safety.The explicit casting of
estimatedFee
toBalance
type is a good practice for ensuring type safety. However, consider adding a comment explaining why this fallback is necessary:// Fallback to a minimal fee when transaction payment API is not available return setEstimatedFee(api?.createType('Balance', BN_ONE) as Balance);This comment would help future developers understand the reasoning behind this fallback mechanism.
290-294
: LGTM:SimpleModalTitle
component improves consistency and simplifies the code.The introduction of the
SimpleModalTitle
component is a great improvement. It simplifies the modal's header section and likely improves consistency across the application.Consider extracting the
onClose
logic to a separate variable for better readability:const onCloseHandler = step !== STEPS.WAIT_SCREEN ? handleClose : noop; <SimpleModalTitle icon='vaadin:del' onClose={onCloseHandler} title={title} />This small change makes the component props easier to read and understand.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- packages/extension-polkagate/src/fullscreen/governance/Toolbar.tsx (5 hunks)
- packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx (6 hunks)
- packages/extension-polkagate/src/fullscreen/governance/delegate/partial/Confirmation.tsx (2 hunks)
- packages/extension-polkagate/src/fullscreen/governance/post/castVote/Cast.tsx (1 hunks)
- packages/extension-polkagate/src/fullscreen/governance/post/castVote/Review.tsx (6 hunks)
- packages/extension-polkagate/src/fullscreen/governance/post/castVote/index.tsx (7 hunks)
- packages/extension-polkagate/src/popup/receive/ReceiveModal.tsx (3 hunks)
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx
[error] 9-9: 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)
packages/extension-polkagate/src/fullscreen/governance/post/castVote/Review.tsx
[error] 14-14: 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 (25)
packages/extension-polkagate/src/popup/receive/ReceiveModal.tsx (3)
12-12
: LGTM: Import of SimpleModalTitle componentThe addition of the
SimpleModalTitle
import aligns with the PR objective to refactor and use this component. This change promotes code reuse and consistency across the application.
31-35
: LGTM: Refactored to use SimpleModalTitle componentThe replacement of the custom modal title implementation with the
SimpleModalTitle
component is a good refactoring decision. It simplifies the code, improves maintainability, and ensures consistency across modals in the application. The props passed to the component (icon, onClose, and title) are appropriate for its usage.
Line range hint
1-74
: Overall assessment: Good refactoring with minor improvement suggestionsThe changes in this file successfully implement the PR objective of using the
SimpleModalTitle
component. The refactoring improves code consistency and maintainability across the application. The conditional rendering of the QRCode adds a layer of safety.A few minor suggestions for improvement:
- Ensure the function signature formatting aligns with the project's style guide.
- Consider extracting the QRCode styling into a separate object or theme for better maintainability.
These changes represent a positive step towards a more consistent and maintainable codebase.
packages/extension-polkagate/src/fullscreen/governance/Toolbar.tsx (5)
27-27
: LGTM: Improved clarity in commentThe change from "mili sec" to "ms" for the
MENU_DELAY
constant comment is a good improvement. It uses a more standard abbreviation for milliseconds, enhancing code readability.
44-46
: LGTM: OptimizedhandleOpenDelegate
withuseCallback
The conversion of
handleOpenDelegate
to use theuseCallback
hook is a good optimization. This memoizes the function, preventing unnecessary re-creations on each render. The empty dependency array is correct as the function doesn't depend on any props or state.
58-58
: LGTM: Consistent simplification of timeout clearingThe simplification of the timeout clearing logic in
onTopMenuMenuMouseLeave
is consistent with the changes made inonTopMenuMenuMouseEnter
. This improves code readability and maintains consistency across the component.
69-69
: LGTM: Improved type safety inTopMenuComponent
The changes in
TopMenuComponent
enhance type safety and consistency:
- The function parameters are now more concise and type-safe.
- The
onMouseLeave
event handler correctly callsonTopMenuMenuMouseLeave
without parameters, aligning with its definition.These improvements reduce the risk of runtime errors and make the code more robust.
Also applies to: 76-79
34-34
: LGTM: Updated type for browser compatibilityThe change from
NodeJS.Timeout | null
tonumber | null
fortimeoutId
is appropriate for browser environments wheresetTimeout
returns a number. This improves type accuracy and browser compatibility.Please verify that this type change is consistent with how
timeoutId
is used throughout the component. Run the following script to check for any remainingNodeJS.Timeout
references:✅ Verification successful
Verification Successful: Type Change Confirmed
The change from
NodeJS.Timeout | null
tonumber | null
fortimeoutId
has been verified. No remainingNodeJS.Timeout
references were found inToolbar.tsx
, ensuring type consistency and browser compatibility.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining NodeJS.Timeout references in the file rg --type typescript "NodeJS\.Timeout" packages/extension-polkagate/src/fullscreen/governance/Toolbar.tsxLength of output: 142
Script:
#!/bin/bash # Retry searching for any remaining NodeJS.Timeout references in the specified file without specifying file type rg 'NodeJS\.Timeout' packages/extension-polkagate/src/fullscreen/governance/Toolbar.tsxLength of output: 89
packages/extension-polkagate/src/fullscreen/governance/delegate/partial/Confirmation.tsx (2)
100-103
: LGTM! Proper handling of potentially undefined values.The changes in this segment correctly implement optional chaining to handle cases where
delegateInformation
might be undefined. This prevents potential runtime errors and aligns with the updates made to theProps
interface.
Line range hint
1-146
: Overall, excellent improvements in type safety and error handling.The changes in this file consistently improve the handling of potentially undefined values, making the component more robust and less prone to runtime errors. The use of optional chaining and nullish coalescing aligns well with TypeScript best practices.
The minor suggestions provided in the review comments are aimed at further enhancing readability and consistency, but the core improvements are solid and well-implemented.
Great job on these updates!
packages/extension-polkagate/src/fullscreen/governance/post/castVote/Review.tsx (4)
11-15
: Improved type safety and import organization.Great job on removing the
@ts-nocheck
directive and reorganizing the imports. These changes enhance type safety and improve code readability. The separate import of theVoteInformation
type is particularly beneficial for maintaining clear type definitions.🧰 Tools
🪛 Biome
[error] 14-14: 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)
73-76
: Improved consistency in accessing STATUS_COLOR properties.The use of bracket notation for accessing
STATUS_COLOR
properties enhances consistency and allows for more flexible property access. This is a good stylistic improvement.
107-118
: Simplified onBackClick function and TypeScript workaround.The simplified
onBackClick
function improves code readability. Good job on this change.However, the addition of a TypeScript ignore comment in the
useEffect
hook suggests an underlying type issue://@ts-ignore setModalHeight(ref.current?.offsetHeight as number);This workaround might hide potential runtime errors. Consider investigating the root cause of this type issue and finding a type-safe solution. If you need assistance in resolving this, please let me know.
180-199
: Conditional rendering of SignArea2 component.The addition of a conditional check for the
address
prop before rendering the SignArea2 component is a good practice to prevent potential runtime errors.However, it's important to ensure that this change doesn't unintentionally hide the SignArea2 component in valid use cases. Please verify that:
- The
address
prop is always provided when it's expected to be.- There are no scenarios where SignArea2 should be rendered even if
address
is undefined.If you need assistance in verifying these conditions, I can help you create a script to check for
address
usage across the codebase.packages/extension-polkagate/src/fullscreen/governance/post/castVote/index.tsx (8)
73-73
: LGTM: Improved function signature with object destructuring.The update to use object destructuring for props in the function signature is a good improvement. It enhances readability and makes it easier to manage props in the future.
86-87
: LGTM: Improved type safety with optional chaining.The use of optional chaining (
?.
) in thevoteTx
andremoveTx
assignments is a good improvement. It enhances type safety by safely handling potentially undefined values.
115-116
: LGTM: Improved readability in votedInfo calculation.The separation of the undefined case return statement improves the readability of the
votedInfo
calculation. It clearly distinguishes between the main calculation and the fallback case.
157-157
: LGTM: Improved type safety in setEstimatedFee call.The addition of the type assertion to
Balance
in thesetEstimatedFee
call improves type safety. It ensures that the correct type is used when setting the estimated fee.
21-21
: Verify the usage of SimpleModalTitle component.The
SimpleModalTitle
component has been imported. Please ensure it's used correctly in the component, replacing any previous title rendering logic. If it's not used, consider removing the import.#!/bin/bash # Search for usage of SimpleModalTitle component rg --type typescript "SimpleModalTitle" packages/extension-polkagate/src/fullscreen/governance/post/castVote/index.tsx
26-26
: Verify the usage of getConviction function.The
getConviction
function has been imported from '../myVote/util'. Please ensure it's used correctly in the component, replacing any previous conviction calculation logic. If it's not used, consider removing the import.#!/bin/bash # Search for usage of getConviction function rg --type typescript "getConviction" packages/extension-polkagate/src/fullscreen/governance/post/castVote/index.tsx
8-8
: Verify the removal of Vote type import.The Vote type import has been removed. Please ensure that this type is no longer used in the file or has been replaced appropriately. If it's still needed, consider re-adding the import.
10-10
: Verify the usage of newly added imports.New imports have been added:
faVoteYea
from '@fortawesome/free-solid-svg-icons'BN
,BN_ONE
, andnoop
from '@polkadot/util'Please ensure these imports are used appropriately in the component. If any of them are not used, consider removing them to keep the imports clean.
Also applies to: 15-15
packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx (2)
6-22
: LGTM: Import statements have been updated appropriately.The import statements have been reorganized and updated to include necessary types and components while removing unused ones. This improves code cleanliness and maintainability.
🧰 Tools
🪛 Biome
[error] 9-9: 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)
113-167
: LGTM: Excellent refactoring of title logic usinguseMemo
.The introduction of the
useMemo
hook for computing the title is a great improvement. It centralizes the title logic, making it easier to maintain and understand. The memoization can also potentially improve performance by avoiding unnecessary re-computations when the dependencies haven't changed.packages/extension-polkagate/src/fullscreen/governance/post/castVote/Cast.tsx (1)
36-36
: LGTM. Verify null handling fornotVoted
prop.The change to include
null
as a possible value for thenotVoted
prop is acceptable. It provides more flexibility in how the prop can be used.Please ensure that the component handles the
null
case appropriately. Run the following script to check hownotVoted
is used within the component:
<SimpleModalTitle | ||
icon={faVoteYea} | ||
onClose={step !== STEPS.WAIT_SCREEN ? handleClose : noop} | ||
title= {title} | ||
/> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Improved modal title rendering, but type issues need attention.
The use of SimpleModalTitle
for rendering the modal title is a good improvement. It enhances consistency and potentially improves reusability of the title rendering logic.
However, the addition of @ts-ignore
comments is concerning. These comments suppress TypeScript errors, which could hide potential issues. Please review the type definitions for voteInformation
and votedInfo
to ensure they are correct and compatible. If possible, fix the underlying type issues instead of using @ts-ignore
.
Also applies to: 239-239, 273-273
There was a problem hiding this 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/delegate/index.tsx (1)
9-9
: Consider the "Proxy" type naming.The static analysis tool flagged a potential shadowing of the global "Proxy" property. This is likely a false positive, as the "Proxy" type is probably defined in the project's type definitions. However, to improve code clarity, you might consider prefixing the type with a domain-specific name (e.g.,
GovernanceProxy
) if it doesn't conflict with existing conventions in the codebase.🧰 Tools
🪛 Biome
[error] 9-9: 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)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx (6 hunks)
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx
[error] 9-9: 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 (5)
packages/extension-polkagate/src/fullscreen/governance/delegate/index.tsx (5)
6-10
: LGTM: Import statements have been updated and organized.The new imports (
Balance
,BN
,SimpleModalTitle
) are necessary for the changes made in the component. The reorganization of imports improves code readability.Also applies to: 13-18, 23-23
🧰 Tools
🪛 Biome
[error] 9-9: 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)
114-168
: LGTM: Title logic refactored usinguseMemo
.The title logic has been effectively refactored using a
useMemo
hook. This change improves readability and maintainability by centralizing the title computation. The conditions cover all possible states of the component, and the hook dependencies are appropriate.
170-171
: LGTM:handleClose
function improved.The modification to the
handleClose
function improves the control flow when closing the modal. It now correctly handles thePROXY
step by only updating the step state ifproxyStep
is defined.
207-207
: LGTM: Explicit type casting forestimatedFee
.The explicit casting of
estimatedFee
toBalance
type improves type safety. This is a good practice, especially when dealing with blockchain-related data.
291-295
: LGTM:SimpleModalTitle
component implemented.The introduction of the
SimpleModalTitle
component streamlines the modal's header section. The component receives appropriate props, and theonClose
prop is correctly set tonoop
during theWAIT_SCREEN
step to prevent closing during processing.
Summary by CodeRabbit
Release Notes
New Features
SimpleModalTitle
component for improved modal header rendering.ReceiveModal
.Improvements
Delegate
andCastVote
components for better readability and maintainability.Toolbar
for improved performance.ReceiveModal
for better user experience.Bug Fixes
Confirmation
component by accommodating potentialundefined
values.Code Quality
Review
component.