-
-
Notifications
You must be signed in to change notification settings - Fork 33
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
fix: network modal showing while the page is loading #4711
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThe changes enhance the donation modal management across multiple components. Key updates include the introduction of a new enum for modal priorities, improved state management for modal visibility, and refined logic for handling wallet sanctions. The Changes
Possibly related PRs
Suggested reviewers
Poem
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
useEffect(() => { | ||
const handleRouteChangeComplete = () => { | ||
closeModal(); | ||
setIsRedirecting(false); | ||
}; | ||
if(isRedirecting) { | ||
router.events.on('routeChangeComplete', handleRouteChangeComplete); | ||
} | ||
return () => { | ||
router.events.off('routeChangeComplete', handleRouteChangeComplete); | ||
}; | ||
}, [isRedirecting]); |
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.
LGTM, but fix the formatting issue.
The useEffect
hook ensures that the modal closes only after the navigation is complete, preventing premature closure during the redirect process.
The static analysis tool has flagged a formatting issue. Apply this diff to fix it:
- if(isRedirecting) {
+ if (isRedirecting) {
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.
useEffect(() => { | |
const handleRouteChangeComplete = () => { | |
closeModal(); | |
setIsRedirecting(false); | |
}; | |
if(isRedirecting) { | |
router.events.on('routeChangeComplete', handleRouteChangeComplete); | |
} | |
return () => { | |
router.events.off('routeChangeComplete', handleRouteChangeComplete); | |
}; | |
}, [isRedirecting]); | |
useEffect(() => { | |
const handleRouteChangeComplete = () => { | |
closeModal(); | |
setIsRedirecting(false); | |
}; | |
if (isRedirecting) { | |
router.events.on('routeChangeComplete', handleRouteChangeComplete); | |
} | |
return () => { | |
router.events.off('routeChangeComplete', handleRouteChangeComplete); | |
}; | |
}, [isRedirecting]); |
Tools
GitHub Check: build
[failure] 36-36:
Insert·
…issue_4449_network_modal Update Branch
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: 6
Outside diff range and nitpick comments (3)
src/components/views/donate/DonateIndex.tsx (2)
120-127
: Simplify the condition by removing redundant undefined checkIn the
useEffect
, the checkuserData?.id !== undefined
is unnecessary because ifuserData?.id
isundefined
, the comparison withproject.adminUser.id
will already returnfalse
. You can simplify the condition as follows:Apply this diff to simplify the condition:
-useEffect(() => { - if ( - userData?.id !== undefined && - userData?.id === project.adminUser.id - ) { +useEffect(() => { + if (userData?.id === project.adminUser.id) { setDonateModalByPriority( DonateModalPriorityValues.DonationByProjectOwner, ); } setIsModalPriorityChecked( DonateModalPriorityValues.DonationByProjectOwner, ); }, [userData?.id, project.adminUser]);
261-285
: Use strict equality===
instead of loose equality==
In your conditional statements for rendering modals, you're using
==
to comparehighestModalPriorityUnchecked
with'All Checked'
. It's recommended to use strict equality===
to prevent unexpected type coercion and enhance code reliability.Apply this diff to use strict equality:
-{(highestModalPriorityUnchecked == 'All Checked' || +{(highestModalPriorityUnchecked === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked) && currentDonateModal === DonateModalPriorityValues.DonationByProjectOwner && ( <DonationByProjectOwner closeModal={() => { setDonateModalByPriority( DonateModalPriorityValues.None, ); }} /> )} ... -{(highestModalPriorityUnchecked == 'All Checked' || +{(highestModalPriorityUnchecked === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked) && currentDonateModal === DonateModalPriorityValues.OFACSanctionListModal && ( <SanctionModal closeModal={() => { setDonateModalByPriority( DonateModalPriorityValues.None, ); }} /> )}src/components/views/donate/OnTime/OneTimeDonationCard.tsx (1)
374-384
: Use strict equality operator===
instead of==
It's recommended to use the strict equality operator
===
in JavaScript to prevent unexpected type coercion. Replace==
with===
when comparinghighestModalPriorityUnchecked
to'All Checked'
.Apply this diff to make the change:
- {(highestModalPriorityUnchecked == 'All Checked' || + {(highestModalPriorityUnchecked === 'All Checked' ||
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- src/components/views/donate/DonateIndex.tsx (7 hunks)
- src/components/views/donate/OnTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (7 hunks)
Additional context used
Biome
src/context/donate.context.tsx
[error] 128-128: Don't use 'Boolean' as a type.
Use lowercase primitives for consistency.
Safe fix: Use 'boolean' instead(lint/complexity/noBannedTypes)
[error] 165-168: Unnecessary use of boolean literals in conditional expression.
Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with(lint/complexity/noUselessTernary)
Additional comments not posted (6)
src/context/donate.context.tsx (4)
76-81
: Addition ofDonateModalPriorityValues
enum enhances clarityIntroducing the
DonateModalPriorityValues
enum improves the readability and maintainability of modal priority management within the donation context.
147-176
: Efficient implementation ofsetIsModalPriorityChecked
The function
setIsModalPriorityChecked
effectively manages modal status checks and updates the highest unchecked modal priority. The use ofuseRef
for maintaining the modal status map anduseCallback
for memoization is appropriate.Tools
Biome
[error] 165-168: Unnecessary use of boolean literals in conditional expression.
Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with(lint/complexity/noUselessTernary)
178-188
: Well-structuredsetDonateModalByPriority
functionThe
setDonateModalByPriority
function correctly updates the current modal based on priority, ensuring that higher priority modals are displayed appropriately.
Line range hint
225-239
: Context provider passes new state and functions correctlyThe updated context values, including
currentDonateModal
,setDonateModalByPriority
,setIsModalPriorityChecked
, andhighestModalPriorityUnchecked
, are properly provided to the context consumers.src/components/views/donate/OnTime/OneTimeDonationCard.tsx (2)
38-41
: Imported modules are correctly includedThe necessary modules
DonateModalPriorityValues
anduseDonateData
are imported from'@/context/donate.context'
, ensuring the component has access to the updated donation context.
80-88
: Destructured properties fromuseDonateData
are properly utilizedThe destructuring of
useDonateData
includes the necessary properties for modal management and project data, which are used appropriately throughout the component.
src/context/donate.context.tsx
Outdated
@@ -102,9 +124,18 @@ export const DonateProvider: FC<IProviderProps> = ({ children, project }) => { | |||
const [selectedRecurringToken, setSelectedRecurringToken] = useState< | |||
ISelectTokenWithBalance | undefined | |||
>(); | |||
const isModalStatusChecked = useRef< | |||
Map<DonateModalPriorityValues, Boolean> |
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.
Use 'boolean' instead of 'Boolean' in type annotations
The TypeScript type Boolean
refers to the wrapper object, whereas boolean
refers to the primitive type. It's recommended to use boolean
for type annotations to ensure consistency and avoid unexpected behavior.
Suggested fix:
- Map<DonateModalPriorityValues, Boolean>
+ Map<DonateModalPriorityValues, 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.
Map<DonateModalPriorityValues, Boolean> | |
Map<DonateModalPriorityValues, boolean> |
Tools
Biome
[error] 128-128: Don't use 'Boolean' as a type.
Use lowercase primitives for consistency.
Safe fix: Use 'boolean' instead(lint/complexity/noBannedTypes)
src/context/donate.context.tsx
Outdated
isAllChecked && | ||
isModalStatusChecked.current.get(modalStatus) | ||
? true | ||
: false; |
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.
Simplify unnecessary ternary operator
The use of the ternary operator returning true
or false
is redundant here. You can simplify the code by directly assigning the boolean expression.
Suggested fix:
- isAllChecked =
- isAllChecked &&
- isModalStatusChecked.current.get(modalStatus)
- ? true
- : false;
+ isAllChecked =
+ isAllChecked && !!isModalStatusChecked.current.get(modalStatus);
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.
isAllChecked && | |
isModalStatusChecked.current.get(modalStatus) | |
? true | |
: false; | |
isAllChecked = | |
isAllChecked && !!isModalStatusChecked.current.get(modalStatus); |
Tools
Biome
[error] 165-168: Unnecessary use of boolean literals in conditional expression.
Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with(lint/complexity/noUselessTernary)
{(highestModalPriorityUnchecked == 'All Checked' || | ||
currentDonateModal >= highestModalPriorityUnchecked) && | ||
currentDonateModal === | ||
DonateModalPriorityValues.DonationByProjectOwner && ( | ||
<DonationByProjectOwner | ||
closeModal={() => { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.None, | ||
); | ||
}} | ||
/> | ||
)} | ||
|
||
{(highestModalPriorityUnchecked == 'All Checked' || | ||
currentDonateModal >= highestModalPriorityUnchecked) && | ||
currentDonateModal === | ||
DonateModalPriorityValues.OFACSanctionListModal && ( | ||
<SanctionModal | ||
closeModal={() => { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.None, | ||
); | ||
}} | ||
/> | ||
)} |
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.
Refactor duplicate modal rendering logic
The rendering logic for <DonationByProjectOwner />
and <SanctionModal />
is almost identical. To improve maintainability and reduce code duplication, consider creating a reusable component or function that handles modal rendering based on modal priority.
For example, you could create a function:
const renderModal = (modalType: DonateModalPriorityValues, ModalComponent: React.FC) => {
return (
(highestModalPriorityUnchecked === 'All Checked' ||
currentDonateModal >= highestModalPriorityUnchecked) &&
currentDonateModal === modalType && (
<ModalComponent
closeModal={() => {
setDonateModalByPriority(DonateModalPriorityValues.None);
}}
/>
)
);
};
And use it like this:
{renderModal(DonateModalPriorityValues.DonationByProjectOwner, DonationByProjectOwner)}
{renderModal(DonateModalPriorityValues.OFACSanctionListModal, SanctionModal)}
const validateSanctions = async () => { | ||
if (project.organization?.label === 'endaoment' && address) { | ||
// We just need to check if the wallet is sanctioned for endaoment projects | ||
const sanctioned = await isWalletSanctioned(address); | ||
if (sanctioned) { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.OFACSanctionListModal, | ||
); | ||
return; | ||
} | ||
} | ||
setIsModalPriorityChecked( | ||
DonateModalPriorityValues.OFACSanctionListModal, | ||
); | ||
}; |
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.
Handle potential errors from isWalletSanctioned
API call
In the validateSanctions
function, the asynchronous call to isWalletSanctioned(address)
may fail due to network errors or other issues. To ensure the application remains stable, consider wrapping the API call in a try-catch block to handle any potential exceptions.
Apply this diff to enhance error handling:
const validateSanctions = async () => {
if (project.organization?.label === 'endaoment' && address) {
+ try {
// We just need to check if the wallet is sanctioned for endaoment projects
const sanctioned = await isWalletSanctioned(address);
if (sanctioned) {
setDonateModalByPriority(
DonateModalPriorityValues.OFACSanctionListModal,
);
return;
}
+ } catch (error) {
+ console.error('Error checking wallet sanctions:', error);
+ // Optionally, set an error state or display an error message to the user
+ }
}
setIsModalPriorityChecked(
DonateModalPriorityValues.OFACSanctionListModal,
);
};
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.
const validateSanctions = async () => { | |
if (project.organization?.label === 'endaoment' && address) { | |
// We just need to check if the wallet is sanctioned for endaoment projects | |
const sanctioned = await isWalletSanctioned(address); | |
if (sanctioned) { | |
setDonateModalByPriority( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
return; | |
} | |
} | |
setIsModalPriorityChecked( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
}; | |
const validateSanctions = async () => { | |
if (project.organization?.label === 'endaoment' && address) { | |
try { | |
// We just need to check if the wallet is sanctioned for endaoment projects | |
const sanctioned = await isWalletSanctioned(address); | |
if (sanctioned) { | |
setDonateModalByPriority( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
return; | |
} | |
} catch (error) { | |
console.error('Error checking wallet sanctions:', error); | |
// Optionally, set an error state or display an error message to the user | |
} | |
} | |
setIsModalPriorityChecked( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
}; |
useEffect(() => { | ||
if (showChangeNetworkModal && acceptedChains) { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.ShowNetworkModal, | ||
); | ||
} | ||
setIsModalPriorityChecked(DonateModalPriorityValues.ShowNetworkModal); | ||
}, [showChangeNetworkModal, acceptedChains]); |
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.
Verify the placement of setIsModalPriorityChecked
In the useEffect
, setIsModalPriorityChecked
is called outside the if
block that checks for showChangeNetworkModal
and acceptedChains
. If the intention is to mark the modal priority as checked only when these conditions are met, consider moving setIsModalPriorityChecked
inside the if
block. Otherwise, if it should run regardless, this placement is correct.
{(highestModalPriorityUnchecked == 'All Checked' || | ||
currentDonateModal >= highestModalPriorityUnchecked) && | ||
currentDonateModal === | ||
DonateModalPriorityValues.ShowNetworkModal && ( | ||
<DonateWrongNetwork | ||
setShowModal={setShowChangeNetworkModal} | ||
acceptedChains={acceptedChains.filter( | ||
chain => chain.chainType !== ChainType.STELLAR, | ||
)} | ||
/> | ||
)} |
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.
Simplify the conditional rendering logic for better readability
The condition used to render the <DonateWrongNetwork>
component is complex and may be hard to read or maintain. Consider simplifying the logic by extracting it into a descriptive variable.
Apply this refactor to improve readability:
+const shouldShowDonateWrongNetwork =
+ (highestModalPriorityUnchecked === 'All Checked' ||
+ currentDonateModal >= highestModalPriorityUnchecked) &&
+ currentDonateModal === DonateModalPriorityValues.ShowNetworkModal;
- {(highestModalPriorityUnchecked === 'All Checked' ||
- currentDonateModal >= highestModalPriorityUnchecked) &&
- currentDonateModal ===
- DonateModalPriorityValues.ShowNetworkModal && (
+ {shouldShowDonateWrongNetwork && (
<DonateWrongNetwork
setShowModal={setShowChangeNetworkModal}
acceptedChains={acceptedChains.filter(
chain => chain.chainType !== ChainType.STELLAR,
)}
/>
)}
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.
{(highestModalPriorityUnchecked == 'All Checked' || | |
currentDonateModal >= highestModalPriorityUnchecked) && | |
currentDonateModal === | |
DonateModalPriorityValues.ShowNetworkModal && ( | |
<DonateWrongNetwork | |
setShowModal={setShowChangeNetworkModal} | |
acceptedChains={acceptedChains.filter( | |
chain => chain.chainType !== ChainType.STELLAR, | |
)} | |
/> | |
)} | |
const shouldShowDonateWrongNetwork = | |
(highestModalPriorityUnchecked === 'All Checked' || | |
currentDonateModal >= highestModalPriorityUnchecked) && | |
currentDonateModal === DonateModalPriorityValues.ShowNetworkModal; | |
{shouldShowDonateWrongNetwork && ( | |
<DonateWrongNetwork | |
setShowModal={setShowChangeNetworkModal} | |
acceptedChains={acceptedChains.filter( | |
chain => chain.chainType !== ChainType.STELLAR, | |
)} | |
/> | |
)} |
@mohammadranjbarz to review! |
…issue_4449_network_modal Update Branch
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 (3)
src/context/donate.context.tsx (1)
144-154
: Consider simplifying the shouldRenderModal function.The condition in the
shouldRenderModal
function is quite complex. Consider breaking it down into smaller, more readable parts or adding comments to explain the logic.Here's a suggestion to improve readability:
const shouldRenderModal = useCallback( (modalToRender: DonateModalPriorityValues): boolean => { const isHighestPriorityOrAllChecked = highestModalPriorityUnchecked.current === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked.current; return isHighestPriorityOrAllChecked && currentDonateModal === modalToRender; }, [currentDonateModal], );src/components/views/donate/OnTime/OneTimeDonationCard.tsx (2)
Line range hint
373-380
: Enhanced modal rendering logicThe updated rendering logic for the
DonateWrongNetwork
modal improves the component's flexibility in managing modal visibility. This change aligns well with the new modal priority system.To further enhance readability, consider extracting the condition into a descriptive variable:
+ const shouldShowDonateWrongNetwork = shouldRenderModal(DonateModalPriorityValues.ShowNetworkModal); - {shouldRenderModal(DonateModalPriorityValues.ShowNetworkModal) && ( + {shouldShowDonateWrongNetwork && ( <DonateWrongNetwork setShowModal={setShowChangeNetworkModal} acceptedChains={acceptedChains.filter( chain => chain.chainType !== ChainType.STELLAR, )} /> )}This extraction would make the condition more self-explanatory and easier to maintain.
Sanction-related code still present in other files
While sanction-related code has been removed from
OneTimeDonationCard.tsx
, it still exists in the following files:
src/services/donation.ts
src/context/donate.context.tsx
src/components/modals/SanctionedModal.tsx
src/components/views/donate/DonateIndex.tsx
src/components/views/donate/OnTime/DonateModal.tsx
Please verify whether the presence of sanction-related code in these files is intentional or if further removal is necessary to ensure consistency and compliance across the codebase.
Analysis chain
Line range hint
1-624
: Verification needed: Removal of sanction-related codeThe AI summary indicates that sanction validation logic has been completely removed from this component. While this simplifies the code, it's important to verify that this removal doesn't negatively impact the donation process or compliance requirements.
Please run the following script to check for any remaining sanction-related code and to verify that the removal was intentional:
Please review the results of this script to ensure that the removal of sanction-related code was intentional and doesn't introduce any compliance issues.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for remaining sanction-related code and verify intentional removal # Test: Search for sanction-related terms in the current file echo "Checking for sanction-related terms in OneTimeDonationCard.tsx:" rg "sanction|OFAC" src/components/views/donate/OnTime/OneTimeDonationCard.tsx # Test: Search for sanction-related terms in other files echo "Checking for sanction-related terms in other files:" rg "sanction|OFAC" --type typescript -g '!OneTimeDonationCard.tsx' # Test: Check for any recent commits mentioning sanctions echo "Checking recent commits mentioning sanctions:" git log -n 5 --grep="sanction"Length of output: 1482
Script:
#!/bin/bash # Description: Corrected script to check for remaining sanction-related code and review recent commits # Test: Search for sanction-related terms in the current file echo "Checking for sanction-related terms in OneTimeDonationCard.tsx:" rg "sanction|OFAC" src/components/views/donate/OnTime/OneTimeDonationCard.tsx # Test: Search for sanction-related terms in all TypeScript files echo "Checking for sanction-related terms in other TypeScript files:" rg "sanction|OFAC" --type ts,tsx # Test: Check for any recent commits mentioning sanctions echo "Checking recent commits mentioning sanctions:" git log -n 5 --grep="sanction"Length of output: 1466
Script:
#!/bin/bash # Description: Corrected script to check for remaining sanction-related code and review recent commits # Test: Search for sanction-related terms in the current file echo "Checking for sanction-related terms in OneTimeDonationCard.tsx:" rg "sanction|OFAC" src/components/views/donate/OnTime/OneTimeDonationCard.tsx # Test: Search for sanction-related terms in all .ts and .tsx files echo "Checking for sanction-related terms in other TypeScript files:" rg "sanction|OFAC" --type ts --type tsx # Test: Check for any recent commits mentioning sanctions echo "Checking recent commits mentioning sanctions:" git log -n 5 --grep="sanction"Length of output: 1470
Script:
#!/bin/bash # Description: Corrected script to check for remaining sanction-related code and review recent commits # Test: Search for sanction-related terms in the current file echo "Checking for sanction-related terms in OneTimeDonationCard.tsx:" rg "sanction|OFAC" src/components/views/donate/OnTime/OneTimeDonationCard.tsx # Test: Search for sanction-related terms in all .ts and .tsx files using glob patterns echo "Checking for sanction-related terms in other TypeScript files:" rg "sanction|OFAC" -g "*.ts" -g "*.tsx" # Test: Check for any recent commits mentioning sanctions echo "Checking recent commits mentioning sanctions:" git log -n 5 --grep="sanction"Length of output: 2909
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- src/components/views/donate/DonateIndex.tsx (7 hunks)
- src/components/views/donate/OnTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (7 hunks)
Files skipped from review as they are similar to previous changes (1)
- src/components/views/donate/DonateIndex.tsx
Additional comments not posted (11)
src/context/donate.context.tsx (8)
11-11
: LGTM: Import statement updated correctly.The addition of
useRef
to the import statement is consistent with its usage in the component.
41-41
: LGTM: IDonateContext interface updated appropriately.The new properties and methods added to the IDonateContext interface are consistent with the introduced modal management functionality. The types used are appropriate for their purposes.
Also applies to: 47-49, 53-55
75-80
: LGTM: DonateModalPriorityValues enum added correctly.The new enum appropriately represents different modal priorities with clear and consistent naming conventions.
86-86
: LGTM: DonateContext default values updated correctly.The new default values added for the new properties and methods are consistent with the interface changes and use appropriate types.
Also applies to: 90-93
125-130
: LGTM: New state variables and refs added correctly.The new state variables and refs for modal management are correctly typed and initialized.
Also applies to: 134-135
190-199
: LGTM: setDonateModalByPriority function implemented correctly.The
setDonateModalByPriority
function is implemented logically and handles the modal priority changes appropriately.
237-238
: LGTM: DonateContext.Provider value prop updated correctly.The new properties added to the value prop of DonateContext.Provider are consistent with the interface changes and provide the necessary context values for the new modal management functionality.
Also applies to: 250-250
Line range hint
1-268
: Overall assessment: Modal management functionality well-implemented.The changes introduce a robust modal management system to the DonateContext. The new enum, state variables, and functions work together to provide a flexible and priority-based approach to handling multiple modals. The implementation is consistent throughout the file and well-integrated with the existing code.
Some suggestions for improvement have been made regarding the complexity of certain functions, but overall, the changes enhance the functionality of the donation system in a meaningful way.
src/components/views/donate/OnTime/OneTimeDonationCard.tsx (3)
38-41
: Improved state management with donate contextThe addition of the
DonateModalPriorityValues
anduseDonateData
imports, along with the expanded use of theuseDonateData
hook, demonstrates a positive refactoring of the donation logic. This change enhances the component's ability to manage modal states and priorities more effectively.Also applies to: 80-87
Line range hint
1-624
: Summary of changes: Improved state management and simplified logicThe changes in this file represent a significant improvement in state management and modal handling for the one-time donation process. The introduction of the donate context and its associated hooks provides better control and flexibility over modal priorities and rendering.
Key improvements:
- Enhanced state management through the
useDonateData
hook.- More dynamic control over modal rendering, especially for the network modal.
- Simplified component logic by removing sanction-related code.
These changes should lead to a more maintainable and flexible component. However, it's crucial to verify that the removal of sanction-related code doesn't introduce any compliance issues.
Overall, these changes appear to be a positive step towards a more robust and efficient donation system.
347-354
: Proper management of modal priorityThe new useEffect hook effectively manages the priority of the network modal. It correctly uses the
setDonateModalByPriority
andsetIsModalPriorityChecked
functions from the donate context.The dependency array is appropriate, ensuring the effect runs when
showChangeNetworkModal
oracceptedChains
change.To ensure the correct usage of these new context functions across the codebase, run the following verification script:
Verification successful
Proper management of modal priority verified
The
useEffect
hook inOneTimeDonationCard.tsx
correctly manages the priority of the network modal usingsetDonateModalByPriority
andsetIsModalPriorityChecked
. All usages of these context functions across the codebase are consistent and properly implemented.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of setDonateModalByPriority and setIsModalPriorityChecked # Test: Search for usage of setDonateModalByPriority echo "Checking usage of setDonateModalByPriority:" rg "setDonateModalByPriority" --type typescript -A 3 # Test: Search for usage of setIsModalPriorityChecked echo "Checking usage of setIsModalPriorityChecked:" rg "setIsModalPriorityChecked" --type typescript -A 3Length of output: 372
Script:
#!/bin/bash # Description: Verify the usage of setDonateModalByPriority and setIsModalPriorityChecked using correct file type patterns # Test: Search for usage of setDonateModalByPriority echo "Checking usage of setDonateModalByPriority:" rg "setDonateModalByPriority" --glob "*.ts" --glob "*.tsx" -A 3 # Test: Search for usage of setIsModalPriorityChecked echo "Checking usage of setIsModalPriorityChecked:" rg "setIsModalPriorityChecked" --glob "*.ts" --glob "*.tsx" -A 3Length of output: 6224
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 (2)
src/components/views/donate/OnTime/OneTimeDonationCard.tsx (2)
348-355
: Enhanced modal management logicThe new useEffect hook improves the management of modal visibility based on network compatibility. This is a good approach to handling complex UI states.
Consider adding a brief comment explaining the purpose of this effect for better code readability:
useEffect(() => { + // Set network modal priority when it needs to be shown if (showChangeNetworkModal && acceptedChains) { setDonateModalByPriority( DonateModalPriorityValues.ShowNetworkModal, ); } setIsModalPriorityChecked(DonateModalPriorityValues.ShowNetworkModal); }, [showChangeNetworkModal, acceptedChains]);
374-384
: Improved modal rendering logicThe updated rendering logic for the
DonateWrongNetwork
component now takes into account modal priorities, which is a good improvement for managing complex UI states. However, the condition is quite complex and could benefit from being extracted into a separate variable for better readability.Consider refactoring as follows:
+const shouldShowDonateWrongNetwork = + (highestModalPriorityUnchecked === 'All Checked' || + currentDonateModal >= highestModalPriorityUnchecked) && + currentDonateModal === DonateModalPriorityValues.ShowNetworkModal; -{(highestModalPriorityUnchecked === 'All Checked' || - currentDonateModal >= highestModalPriorityUnchecked) && - currentDonateModal === - DonateModalPriorityValues.ShowNetworkModal && ( +{shouldShowDonateWrongNetwork && ( <DonateWrongNetwork setShowModal={setShowChangeNetworkModal} acceptedChains={acceptedChains.filter( chain => chain.chainType !== ChainType.STELLAR, )} /> )}This change will make the code more readable and easier to maintain.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- src/components/views/donate/DonateIndex.tsx (8 hunks)
- src/components/views/donate/OnTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (7 hunks)
Files skipped from review as they are similar to previous changes (2)
- src/components/views/donate/DonateIndex.tsx
- src/context/donate.context.tsx
Additional comments not posted (3)
src/components/views/donate/OnTime/OneTimeDonationCard.tsx (3)
38-41
: Improved state management with contextThe addition of
DonateModalPriorityValues
anduseDonateData
from the donate context, along with the expanded use of theuseDonateData
hook, demonstrates a move towards more centralized and consistent state management. This approach can lead to better maintainability and easier debugging.Also applies to: 80-88
Line range hint
1-644
: Summary of changesThis review has covered several significant changes to the
OneTimeDonationCard
component:
- Improved state management using a centralized donate context.
- Enhanced modal management logic with priority-based rendering.
- Removal of sanction-related code.
These changes generally improve the component's structure and maintainability. However, it's important to verify that sanction checks are still being handled appropriately elsewhere in the application if required.
The refactoring suggestions provided in the review comments should help further improve code readability and maintainability.
Line range hint
1-644
: Verification needed: Removal of sanction-related codeThe sanction validation logic and associated state management have been removed from this component, which simplifies its implementation. However, it's crucial to ensure that sanction checks are still being performed elsewhere in the application if they are required for compliance or legal reasons.
Could you please verify and confirm that:
- Sanction checks are now handled in a different part of the application, or
- Sanction checks are no longer required for this donation flow
This verification will help ensure that we haven't inadvertently removed an important compliance check.
Verification successful
Sanction-related code successfully removed from OneTimeDonationCard.tsx.
The sanction validation logic and associated code have been removed from
OneTimeDonationCard.tsx
, ensuring the component's implementation is now simplified. Please confirm that sanction checks are appropriately handled elsewhere in the application as needed.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for sanction-related code in the codebase echo "Searching for sanction-related code..." rg -i 'sanction|ofac' --type ts --type tsx echo "Searching for wallet address validation..." rg -i 'wallet.*address.*valid' --type ts --type tsxLength of output: 336
Script:
#!/bin/bash # Search for sanction-related code in .ts and .tsx files echo "Searching for sanction-related code in .ts and .tsx files..." rg -i 'sanction|ofac' --glob '*.ts' --glob '*.tsx' echo "Searching for wallet address validation in .ts and .tsx files..." rg -i 'wallet.*address.*valid' --glob '*.ts' --glob '*.tsx'Length of output: 4294
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 (3)
src/context/donate.context.tsx (2)
75-80
: LGTM: Well-structured enum for modal priorities.The
DonateModalPriorityValues
enum provides a clear and organized way to manage modal priorities. This structure will help maintain consistency across the application when dealing with different modal scenarios.Consider adding brief comments for each enum value to explain their specific use cases, especially for less self-explanatory ones like
OFACSanctionListModal
. This would enhance code readability and maintainability.
189-199
: LGTM: Effective shouldRenderModal function with a minor suggestion.The
shouldRenderModal
function efficiently determines whether a modal should be rendered based on the current state and priorities. The logic is clear and concise.Consider extracting the condition into a separate, descriptive variable for even better readability:
const shouldRenderModal = useCallback( (modalRender: DonateModalPriorityValues) => { const isHighestPriorityOrAllChecked = highestModalPriorityUnchecked.current === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked.current; return isHighestPriorityOrAllChecked && currentDonateModal === modalRender; }, [currentDonateModal], );This minor change would make the function's intent even clearer at a glance.
src/components/views/donate/OnTime/OneTimeDonationCard.tsx (1)
347-359
: Improved modal priority management with potential for refinementThe new
useEffect
hook effectively manages modal priorities, ensuring that the network modal is given the correct priority when needed. This directly addresses the PR objective of managing modal visibility during page transitions.However, the use of
setTimeout
with a 0ms delay to set the modal priority check is a bit unconventional. While it likely works as intended, it might be worth considering if this can be simplified.Consider if the
setTimeout
is necessary. If the goal is to ensure the state update happens after the current render cycle, you might be able to achieve the same result by moving thesetIsModalPriorityChecked
call to a separateuseEffect
with[showChangeNetworkModal, acceptedChains]
as dependencies:useEffect(() => { if (showChangeNetworkModal && acceptedChains) { setDonateModalByPriority(DonateModalPriorityValues.ShowNetworkModal); } }, [showChangeNetworkModal, acceptedChains]); useEffect(() => { if (showChangeNetworkModal && acceptedChains) { setIsModalPriorityChecked(DonateModalPriorityValues.ShowNetworkModal); } }, [showChangeNetworkModal, acceptedChains]);This approach might be clearer and avoid the need for
setTimeout
.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- src/components/views/donate/DonateIndex.tsx (8 hunks)
- src/components/views/donate/OnTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (7 hunks)
Files skipped from review as they are similar to previous changes (1)
- src/components/views/donate/DonateIndex.tsx
Additional comments not posted (7)
src/context/donate.context.tsx (5)
11-11
: LGTM: Import of useRef is appropriate for the new functionality.The addition of
useRef
from 'react' is consistent with the new modal management features being implemented. This hook is suitable for storing mutable values that don't require re-renders.
46-48
: LGTM: Enhanced IDonateContext interface for improved modal management.The additions to the
IDonateContext
interface (setDonateModalByPriority
,setIsModalPriorityChecked
, andshouldRenderModal
) provide a robust set of methods for managing modal priorities and visibility. These changes align well with the newDonateModalPriorityValues
enum and enhance the overall modal control capabilities of the context.Also applies to: 52-55
125-130
: LGTM: Effective state management for modal priorities.The introduction of
isModalStatusChecked
andhighestModalPriorityUnchecked
refs, along with thecurrentDonateModal
state, provides an efficient way to manage modal priorities and status. Using refs for values that don't require re-renders is a good optimization. ThecurrentDonateModal
state allows for reactive updates to the UI based on the active modal.Also applies to: 134-135
178-187
: LGTM: Well-implemented setDonateModalByPriority function.The
setDonateModalByPriority
function is concise and effectively manages the current modal based on priority. It correctly handles the case when the new modal has a higher priority and resets toNone
when appropriate. The use ofuseCallback
with[currentDonateModal]
as a dependency ensures optimal performance by memoizing the function.
Line range hint
1-265
: Overall: Well-implemented modal management system with minor suggestions for improvement.The changes introduce a robust modal management system using priority-based rendering. The new
DonateModalPriorityValues
enum, along with thesetIsModalPriorityChecked
,setDonateModalByPriority
, andshouldRenderModal
functions, provide a comprehensive solution for controlling modal visibility and priority.Key strengths:
- Clear structure with the new enum for modal priorities.
- Efficient state management using refs and useState.
- Performance optimization with useCallback.
Suggestions for improvement:
- Add brief comments to the
DonateModalPriorityValues
enum for clarity.- Refactor the
setIsModalPriorityChecked
function for better readability.- Consider extracting the condition in
shouldRenderModal
into a descriptive variable.These changes significantly enhance the modal management capabilities of the
DonateContext
, providing a more controlled and efficient way to handle multiple modals in the application.src/components/views/donate/OnTime/OneTimeDonationCard.tsx (2)
38-41
: Improved modal management with new context propertiesThe addition of
DonateModalPriorityValues
and the enhanceduseDonateData
hook with new properties (shouldRenderModal
,setDonateModalByPriority
,setIsModalPriorityChecked
) demonstrates an improvement in modal management. This change aligns well with the PR objectives of addressing issues related to modal display and navigation.Also applies to: 80-87
Line range hint
377-384
: Enhanced control over DonateWrongNetwork modal renderingThe rendering of the
DonateWrongNetwork
component is now controlled byshouldRenderModal(DonateModalPriorityValues.ShowNetworkModal)
. This change ensures that the modal is only displayed when it has the highest priority, effectively addressing the issue of multiple modals being shown simultaneously. The filtering of the Stellar chain type fromacceptedChains
remains in place, maintaining the existing logic for handling different chain types.
…issue_4449_network_modal
…issue_4449_network_modal Update Branch
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: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- lang/ca.json (0 hunks)
- lang/en.json (0 hunks)
- lang/es.json (0 hunks)
- src/components/views/donate/DonateIndex.tsx (8 hunks)
- src/components/views/donate/DonationCard.tsx (0 hunks)
- src/components/views/donate/OneTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (6 hunks)
💤 Files not reviewed due to no reviewable changes (4)
- lang/ca.json
- lang/en.json
- lang/es.json
- src/components/views/donate/DonationCard.tsx
🧰 Additional context used
🪛 GitHub Check: build
src/components/views/donate/DonateIndex.tsx
[failure] 271-271:
Insert↹
[failure] 272-272:
Insert↹
[failure] 273-273:
Insert↹
[failure] 274-274:
Insert↹
[failure] 275-275:
Insert↹
[failure] 276-276:
Insert↹
[failure] 277-277:
Insert↹
[failure] 278-278:
Insert↹
[failure] 279-279:
Insert↹
[failure] 280-280:
Insert↹
🔇 Additional comments (14)
src/context/donate.context.tsx (6)
11-11
: LGTM: Appropriate import additionThe addition of
useRef
is consistent with the new modal management functionality being implemented.
47-49
: LGTM: Appropriate interface updatesThe additions of
setDonateModalByPriority
andshouldRenderModal
to theIDonateContext
interface are consistent with the new modal priority management functionality.Also applies to: 53-53
73-79
: LGTM: Well-structured enum for modal prioritiesThe
DonateModalPriorityValues
enum is appropriately defined to represent different modal priorities. The order of the enum values implies a clear priority hierarchy.
87-90
: LGTM: Appropriate default context value updatesThe additions of default implementations for
setDonateModalByPriority
andshouldRenderModal
in theDonateContext
default value are consistent with the interface updates and provide appropriate no-op functions.
122-127
: LGTM: Well-structured state management for modalsThe addition of refs
isModalStatusChecked
andhighestModalPriorityUnchecked
, along with thecurrentDonateModal
state, provides a solid foundation for managing modal priorities and visibility. The use of refs for values that don't need to trigger re-renders is a good performance optimization.Also applies to: 131-132
175-199
: LGTM: Well-implemented modal management functionsThe
setDonateModalByPriority
andshouldRenderModal
functions are well-implemented and provide appropriate functionality for managing modal priorities and rendering. The use ofuseCallback
for memoization is a good practice for optimizing performance. These functions are correctly provided in the context value for use by child components.Also applies to: 241-241, 243-243
src/components/views/donate/DonateIndex.tsx (3)
23-26
: LGTM: New imports and hooks for enhanced modal managementThe new imports and hooks are consistent with the PR objectives, introducing functionality for modal management and wallet sanctions checking. These additions will support the implementation of the network modal and sanctioned wallet address modal management.
Also applies to: 51-52, 73-73, 90-90
118-131
: LGTM: Effective use of useEffect for sanction validation and modal managementThe new useEffect hooks effectively implement the required logic for sanction validation and project owner donation modal display. These changes align well with the PR objectives and enhance the component's functionality.
271-280
: Ignore false positive indentation warningsThe static analysis tool has flagged indentation issues for lines 271-280. However, upon inspection, the indentation appears to be correct. This seems to be a false positive from the static analysis tool and can be safely ignored.
🧰 Tools
🪛 GitHub Check: build
[failure] 271-271:
Insert↹
[failure] 272-272:
Insert↹
[failure] 273-273:
Insert↹
[failure] 274-274:
Insert↹
[failure] 275-275:
Insert↹
[failure] 276-276:
Insert↹
[failure] 277-277:
Insert↹
[failure] 278-278:
Insert↹
[failure] 279-279:
Insert↹
[failure] 280-280:
Insert↹
src/components/views/donate/OneTime/OneTimeDonationCard.tsx (5)
38-41
: Improved state management with context APIThe addition of
DonateModalPriorityValues
and the enhanceduseDonateData
hook withshouldRenderModal
andsetDonateModalByPriority
properties indicates a move towards centralized state management for donation-related logic. This change improves code organization and makes it easier to manage complex modal interactions.Also applies to: 83-89
333-339
: Enhanced modal management logicThe new approach using
shouldRenderModal
andsetDonateModalByPriority
provides more granular control over modal visibility. This change effectively addresses the issue of the network modal interfering with navigation, as mentioned in the PR objectives.Consider adding a comment explaining the priority system for future maintainers:
// Set network modal as the highest priority to ensure it's shown first setDonateModalByPriority(DonateModalPriorityValues.ShowNetworkModal);Also applies to: 376-383
Line range hint
232-248
: Streamlined donation logicThe removal of the
isSanctioned
state and the associated validation logic simplifies the component. The updatedhandleDonate
function now incorporates checks for active QF rounds and network eligibility, providing a more comprehensive donation flow.Consider adding a comment to explain the flow:
// Donation flow: // 1. Check for sufficient balance // 2. Check for active QF round and network eligibility // 3. Check if user is signed in // 4. Show appropriate modal based on the above checks
Line range hint
376-383
: Improved UI rendering and user feedbackThe conditional rendering of
DonateWrongNetwork
usingshouldRenderModal
aligns well with the new centralized modal management approach. The addition ofEligibilityBadges
enhances user understanding of donation eligibility, providing valuable feedback to the user.These changes contribute to a more informative and user-friendly donation process.
Also applies to: 419-425
Line range hint
1-686
: Overall improvement in code quality and user experienceThe changes in this file significantly enhance the donation process by:
- Centralizing state management using context API
- Improving modal handling with priority-based rendering
- Streamlining the donation logic
- Enhancing user feedback with eligibility badges
These modifications effectively address the issues mentioned in the PR objectives, particularly the problem with the network modal interfering with navigation. The code is now more organized and maintainable.
Great job on these improvements!
<DonateContainer> | ||
{shouldRenderModal( | ||
DonateModalPriorityValues.DonationByProjectOwner, | ||
) && ( | ||
<DonationByProjectOwner | ||
closeModal={() => { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.None, | ||
); | ||
}} | ||
/> | ||
)} | ||
|
||
{shouldRenderModal( | ||
DonateModalPriorityValues.OFACSanctionListModal, | ||
) && ( | ||
<SanctionModal | ||
closeModal={() => { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.None, | ||
); | ||
}} | ||
/> | ||
)} |
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.
🛠️ Refactor suggestion
Refactor duplicate modal rendering logic
The rendering logic for <DonationByProjectOwner />
and <SanctionModal />
is almost identical. To improve maintainability and reduce code duplication, consider creating a reusable component or function that handles modal rendering based on modal priority.
For example, you could create a function:
const renderModal = (modalType: DonateModalPriorityValues, ModalComponent: React.FC) => {
return (
shouldRenderModal(modalType) && (
<ModalComponent
closeModal={() => {
setDonateModalByPriority(DonateModalPriorityValues.None);
}}
/>
)
);
};
And use it like this:
{renderModal(DonateModalPriorityValues.DonationByProjectOwner, DonationByProjectOwner)}
{renderModal(DonateModalPriorityValues.OFACSanctionListModal, SanctionModal)}
🧰 Tools
🪛 GitHub Check: build
[failure] 271-271:
Insert↹
[failure] 272-272:
Insert↹
[failure] 273-273:
Insert↹
[failure] 274-274:
Insert↹
[failure] 275-275:
Insert↹
[failure] 276-276:
Insert↹
[failure] 277-277:
Insert↹
[failure] 278-278:
Insert↹
[failure] 279-279:
Insert↹
[failure] 280-280:
Insert↹
const validateSanctions = async () => { | ||
if (project.organization?.label === 'endaoment' && address) { | ||
// We just need to check if the wallet is sanctioned for endaoment projects | ||
const sanctioned = await isWalletSanctioned(address); | ||
if (sanctioned) { | ||
setDonateModalByPriority( | ||
DonateModalPriorityValues.OFACSanctionListModal, | ||
); | ||
return; | ||
} | ||
} | ||
}; |
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.
Add error handling to validateSanctions
function
The validateSanctions
function implements the required sanction checking logic. However, it's recommended to add error handling for the API call to isWalletSanctioned(address)
to prevent potential unhandled exceptions.
Consider wrapping the API call in a try-catch block:
const validateSanctions = async () => {
if (project.organization?.label === 'endaoment' && address) {
+ try {
// We just need to check if the wallet is sanctioned for endaoment projects
const sanctioned = await isWalletSanctioned(address);
if (sanctioned) {
setDonateModalByPriority(
DonateModalPriorityValues.OFACSanctionListModal,
);
return;
}
+ } catch (error) {
+ console.error('Error checking wallet sanctions:', error);
+ // Optionally, set an error state or display an error message to the user
+ }
}
};
📝 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.
const validateSanctions = async () => { | |
if (project.organization?.label === 'endaoment' && address) { | |
// We just need to check if the wallet is sanctioned for endaoment projects | |
const sanctioned = await isWalletSanctioned(address); | |
if (sanctioned) { | |
setDonateModalByPriority( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
return; | |
} | |
} | |
}; | |
const validateSanctions = async () => { | |
if (project.organization?.label === 'endaoment' && address) { | |
try { | |
// We just need to check if the wallet is sanctioned for endaoment projects | |
const sanctioned = await isWalletSanctioned(address); | |
if (sanctioned) { | |
setDonateModalByPriority( | |
DonateModalPriorityValues.OFACSanctionListModal, | |
); | |
return; | |
} | |
} catch (error) { | |
console.error('Error checking wallet sanctions:', error); | |
// Optionally, set an error state or display an error message to the user | |
} | |
} | |
}; |
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 (3)
src/context/donate.context.tsx (3)
47-49
: LGTM: New context methods for modal managementThe addition of
setDonateModalByPriority
andshouldRenderModal
to theIDonateContext
interface is appropriate for the new modal management functionality. These methods will allow components to interact with the modal priority system effectively.Consider using a more specific return type for
shouldRenderModal
:shouldRenderModal: (modalRender: DonateModalPriorityValues) => boolean;This explicitly indicates that the function returns a boolean value, improving type safety and readability.
Also applies to: 53-53
122-127
: Consider using TypeScript's Record type for better type safetyThe use of
Map
forisModalStatusChecked
is a good choice for dynamic key-value pairs. However, consider using TypeScript'sRecord
type forhighestModalPriorityUnchecked
to improve type safety and readability.const highestModalPriorityUnchecked = useRef< Record<DonateModalPriorityValues | 'All Checked', boolean> >({ [DonateModalPriorityValues.None]: true, 'All Checked': false });This approach ensures that all possible values are accounted for at compile-time.
189-199
: Simplify shouldRenderModal functionThe
shouldRenderModal
function can be simplified for better readability.Consider refactoring to:
const shouldRenderModal = useCallback( (modalRender: DonateModalPriorityValues) => { const isHighestPriority = highestModalPriorityUnchecked.current === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked.current; return isHighestPriority && currentDonateModal === modalRender; }, [currentDonateModal], );This version improves readability by breaking down the condition into a named variable.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- src/components/views/donate/DonateIndex.tsx (9 hunks)
- src/context/donate.context.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/components/views/donate/DonateIndex.tsx
🔇 Additional comments (4)
src/context/donate.context.tsx (4)
11-11
: LGTM: New import and enum additionThe addition of
useRef
import and the newDonateModalPriorityValues
enum are well-implemented. The enum provides a clear structure for managing different modal priorities in the donation process.Also applies to: 73-78
175-187
: LGTM: setDonateModalByPriority implementationThe
setDonateModalByPriority
function is well-implemented. It correctly handles the modal priority system and updates the current modal state accordingly.
241-241
: LGTM: Updated context provider valueThe addition of
setDonateModalByPriority
andshouldRenderModal
to the context provider value is correct and aligns with the interface changes.Also applies to: 243-243
Line range hint
1-268
: Overall assessment: Well-implemented modal priority system with room for minor improvementsThe changes in this file successfully implement a new modal priority system for the donation context. The addition of the
DonateModalPriorityValues
enum, new state variables, and functions likesetIsModalPriorityChecked
,setDonateModalByPriority
, andshouldRenderModal
provide a robust framework for managing multiple modals in the donation process.The implementation aligns well with the PR objectives, addressing the issue of modal interference during navigation. The new system should effectively manage the visibility of modals based on their priorities.
While the overall implementation is sound, there are a few areas where minor improvements could be made:
- Consider using TypeScript's
Record
type for improved type safety in some areas.- The
setIsModalPriorityChecked
function could benefit from refactoring for better readability and performance.- Some functions, like
shouldRenderModal
, could be simplified for improved clarity.These suggestions are minor and do not detract from the overall quality of the implementation. Great job on addressing this complex issue!
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.
Thanks @HrithikSampson
LGTM
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 (3)
src/context/donate.context.tsx (3)
74-79
: LGTM: DonateModalPriorityValues enum addedThe new
DonateModalPriorityValues
enum effectively defines priorities for different modals, which aligns with the PR objectives. This will help in managing multiple modals more efficiently.Consider adding a brief comment above the enum to explain its purpose and how the priority values are used. This would enhance code readability and maintainability.
// Defines priority values for donation-related modals. // Higher values indicate higher priority for display. export enum DonateModalPriorityValues { // ... (existing enum values) }
124-129
: LGTM: Modal status tracking implemented with useRefThe implementation of
isModalStatusChecked
andhighestModalPriorityUnchecked
usinguseRef
is appropriate for tracking mutable values without triggering re-renders. This approach aligns with React best practices for performance optimization.Consider initializing
isModalStatusChecked
with default values for all enum members to ensure consistency:const isModalStatusChecked = useRef<Map<DonateModalPriorityValues, boolean>>( new Map( Object.values(DonateModalPriorityValues) .filter(value => typeof value === 'number') .map(value => [value, false]) ) );This initialization ensures that all modal statuses are explicitly set to
false
at the start, which can prevent potential undefined behavior.
143-201
: LGTM with suggestions: Modal management functions implementedThe implementation of
setIsModalPriorityChecked
,setDonateModalByPriority
, andshouldRenderModal
provides the necessary functionality for managing modal priorities and visibility. These functions align with the PR objectives of improving modal management.Consider the following improvements to enhance readability and maintainability:
Simplify
setIsModalPriorityChecked
:const setIsModalPriorityChecked = useCallback( (modalChecked: DonateModalPriorityValues): void => { if ( highestModalPriorityUnchecked.current === 'All Checked' || modalChecked > highestModalPriorityUnchecked.current ) { return; } isModalStatusChecked.current.set(modalChecked, true); updateHighestUncheckedModal(); }, [] ); const updateHighestUncheckedModal = () => { const modals = Object.values(DonateModalPriorityValues).filter( modal => typeof modal === 'number' ) as DonateModalPriorityValues[]; const highestUnchecked = modals.reduce((highest, modal) => { if (!isModalStatusChecked.current.get(modal) && modal > highest) { return modal; } return highest; }, DonateModalPriorityValues.None); highestModalPriorityUnchecked.current = highestUnchecked === DonateModalPriorityValues.None ? 'All Checked' : highestUnchecked; };Simplify
setDonateModalByPriority
:const setDonateModalByPriority = useCallback( (changeModal: DonateModalPriorityValues) => { if (!isModalStatusChecked.current.get(changeModal)) { setIsModalPriorityChecked(changeModal); } setCurrentDonateModal(prevModal => changeModal === DonateModalPriorityValues.None ? DonateModalPriorityValues.None : changeModal > prevModal ? changeModal : prevModal ); }, [setIsModalPriorityChecked] );Simplify
shouldRenderModal
:const shouldRenderModal = useCallback( (modalRender: DonateModalPriorityValues) => currentDonateModal === modalRender && (highestModalPriorityUnchecked.current === 'All Checked' || currentDonateModal >= highestModalPriorityUnchecked.current), [currentDonateModal] );These refactorings improve readability and reduce complexity while maintaining the same functionality.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- src/components/views/donate/DonateIndex.tsx (9 hunks)
- src/components/views/donate/OneTime/OneTimeDonationCard.tsx (4 hunks)
- src/context/donate.context.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/components/views/donate/DonateIndex.tsx
- src/components/views/donate/OneTime/OneTimeDonationCard.tsx
🔇 Additional comments (5)
src/context/donate.context.tsx (5)
11-11
: LGTM: New modal management functionality addedThe changes introduce new properties to the
IDonateContext
interface, includingsetDonateModalByPriority
andshouldRenderModal
. These additions align with the PR objectives of improving modal management. TheuseRef
import is also appropriately added to support this new functionality.Also applies to: 47-49, 53-54
88-92
: LGTM: Default implementations added for new modal management functionsThe default
DonateContext
value has been updated with new properties that match the additions to theIDonateContext
interface. These default implementations ensure that the context remains functional even if a provider is not properly set up, which is a good practice for error prevention.
133-134
: LGTM: currentDonateModal state addedThe addition of the
currentDonateModal
state variable using theDonateModalPriorityValues
enum is appropriate. Initializing it withDonateModalPriorityValues.None
is a good default value, ensuring that no modal is shown initially.
243-243
: LGTM: New modal management functions added to DonateContext.Provider valueThe newly implemented functions
setDonateModalByPriority
,shouldRenderModal
, andsetIsModalPriorityChecked
are correctly added to theDonateContext.Provider
value. This ensures that these functions are available to all components consuming the DonateContext.Also applies to: 245-245, 247-247
Line range hint
1-270
: Overall assessment: Improved modal management implementationThe changes in this file successfully implement enhanced modal management for the donation context, aligning well with the PR objectives. The new
DonateModalPriorityValues
enum, state variables, and functions provide a structured approach to handling multiple modals with different priorities.Key improvements:
- Introduction of
DonateModalPriorityValues
enum for clear modal prioritization.- Implementation of
setIsModalPriorityChecked
,setDonateModalByPriority
, andshouldRenderModal
functions for managing modal states and visibility.- Use of
useRef
for efficient state management without unnecessary re-renders.While the implementation is functional, there are opportunities for further refinement:
- Adding comments to explain the purpose and usage of the
DonateModalPriorityValues
enum.- Initializing
isModalStatusChecked
with default values for all enum members.- Refactoring complex functions like
setIsModalPriorityChecked
for improved readability and maintainability.These changes significantly enhance the modal management capabilities of the application, addressing the issues mentioned in the PR objectives.
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 (3)
src/context/donate.context.tsx (3)
74-79
: LGTM: New enum for modal prioritiesThe
DonateModalPriorityValues
enum is a good addition for managing modal priorities. It aligns well with the PR objectives.Consider adding a brief comment explaining the purpose of this enum and how the priority values are used.
export enum DonateModalPriorityValues { + // Defines priority values for different modal types. + // Higher values indicate higher priority. None, ShowNetworkModal, DonationByProjectOwner, OFACSanctionListModal, }
122-127
: LGTM: New refs for modal status trackingThe new
useRef
hooks forisModalStatusChecked
andhighestModalPriorityUnchecked
are well-implemented for tracking modal statuses. The types are consistent with theDonateModalPriorityValues
enum.Consider adding brief comments explaining the purpose of these refs for better code readability.
+ // Tracks the checked status of each modal const isModalStatusChecked = useRef< Map<DonateModalPriorityValues, boolean> >(new Map()); + // Tracks the highest priority of unchecked modals const highestModalPriorityUnchecked = useRef< DonateModalPriorityValues | 'All Checked' >(DonateModalPriorityValues.None);
175-199
: LGTM: New modal management functions and context updatesThe new functions
setDonateModalByPriority
andshouldRenderModal
are well-implemented for managing modal visibility based on priority. The additions to theDonateContext.Provider
value are consistent with the new functionality.Consider adding brief comments explaining the purpose of these functions for better code readability.
+ // Updates the current modal based on priority const setDonateModalByPriority = useCallback( (changeModal: DonateModalPriorityValues) => { // ... (existing implementation) }, [currentDonateModal], ); + // Determines if a modal should be rendered based on current state const shouldRenderModal = useCallback( (modalRender: DonateModalPriorityValues) => { // ... (existing implementation) }, [currentDonateModal], );Also applies to: 241-241, 243-243, 245-245
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- src/components/views/donate/DonateIndex.tsx (9 hunks)
- src/context/donate.context.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/components/views/donate/DonateIndex.tsx
🔇 Additional comments (4)
src/context/donate.context.tsx (4)
11-11
: LGTM: New modal management functionality addedThe changes introduce new properties to the
IDonateContext
interface and import theuseRef
hook. These additions are consistent with the new modal management functionality described in the PR objectives.Also applies to: 47-49, 53-54
88-90
: LGTM: Default context values for new modal management methodsThe new properties added to the default
DonateContext
value correspond to the methods introduced in theIDonateContext
interface. The placeholder implementations are appropriate for a context default value.
131-132
: LGTM: New state for current modalThe addition of the
currentDonateModal
state variable is appropriate for tracking the currently active modal. The initial value ofDonateModalPriorityValues.None
is a sensible default.
Line range hint
1-268
: Overall assessment: Well-implemented modal management functionalityThe changes in this file successfully implement the new modal management functionality as described in the PR objectives. The additions include a new enum for modal priorities, state variables for tracking modal status, and functions for managing modal visibility based on priority.
Key points:
- The implementation is consistent with the PR objectives and AI-generated summary.
- The code is generally well-structured and typed correctly.
- There are opportunities for minor improvements in code readability, such as adding comments and refactoring complex functions.
Great job on implementing this feature! The suggested improvements are minor and aimed at enhancing code maintainability.
const setIsModalPriorityChecked = useCallback( | ||
(modalChecked: DonateModalPriorityValues): void => { | ||
if ( | ||
highestModalPriorityUnchecked.current != 'All Checked' && | ||
(modalChecked <= highestModalPriorityUnchecked.current || | ||
highestModalPriorityUnchecked.current === | ||
DonateModalPriorityValues.None) | ||
) { | ||
isModalStatusChecked.current.set(modalChecked, true); | ||
let highestModalStatusUnchecked = | ||
DonateModalPriorityValues.None; | ||
let isAllChecked = true; | ||
const modals: DonateModalPriorityValues[] = Object.values( | ||
DonateModalPriorityValues, | ||
).filter( | ||
modal => typeof modal !== 'string', | ||
) as DonateModalPriorityValues[]; | ||
for (const modalStatus of modals) { | ||
if (!isModalStatusChecked.current.get(modalStatus)) { | ||
highestModalStatusUnchecked = modalStatus; | ||
} | ||
isAllChecked = | ||
(isAllChecked && | ||
!!isModalStatusChecked.current.get(modalStatus)) || | ||
modalStatus === DonateModalPriorityValues.None; | ||
} | ||
highestModalPriorityUnchecked.current = isAllChecked | ||
? 'All Checked' | ||
: highestModalStatusUnchecked; | ||
} | ||
}, | ||
[], | ||
); |
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.
🛠️ Refactor suggestion
Optimize setIsModalPriorityChecked function
I agree with the previous review comment suggesting a refactor of this function. In addition to the proposed changes, consider the following improvements:
- Use early returns to simplify the logic flow.
- Extract the modal filtering logic into a separate function for reusability.
- Use more descriptive variable names to improve readability.
Here's a suggested refactor incorporating these points:
const getNumericModals = () => Object.values(DonateModalPriorityValues).filter(
modal => typeof modal === 'number'
) as DonateModalPriorityValues[];
const setIsModalPriorityChecked = useCallback(
(modalChecked: DonateModalPriorityValues): void => {
if (
highestModalPriorityUnchecked.current === 'All Checked' ||
modalChecked > highestModalPriorityUnchecked.current
) {
return;
}
isModalStatusChecked.current.set(modalChecked, true);
const numericModals = getNumericModals();
const highestUncheckedModal = numericModals.reduce((highest, modal) => {
if (!isModalStatusChecked.current.get(modal) && modal > highest) {
return modal;
}
return highest;
}, DonateModalPriorityValues.None);
const areAllModalsChecked = numericModals.every(modal =>
isModalStatusChecked.current.get(modal) || modal === DonateModalPriorityValues.None
);
highestModalPriorityUnchecked.current = areAllModalsChecked
? 'All Checked'
: highestUncheckedModal;
},
[],
);
This refactored version improves readability and performance while maintaining the original functionality.
…issue_4449_network_modal Update Branch
I have closed both the networkModal and the sanctioned wallet address when I close the sanctions Modal if both networkModal and the sanctionsModal appear and user clicks inside the sanctions Modal to visit all projects page. the networkModal wont interfere
relates to #4449 (comment)
and relates to #4449
relates also to #4612 and test can be seen in #4712 for OFAC Sanctions Modal, as for all wallet addresses it returns sanctioned in #4712
I have tried to show only one modal in donation page. Sometimes modals were coinciding and interupting the flow.
Summary by CodeRabbit
Summary by CodeRabbit