-
Notifications
You must be signed in to change notification settings - Fork 6
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
[ISSUE-205] Refactor AddressInput and GeneralRecipientInput #465
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
📝 Walkthrough📝 WalkthroughWalkthroughThis pull request includes significant updates across several components related to recipient data handling and validation in a React application. The Changes
Possibly related PRs
Suggested labels
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: 12
🧹 Outside diff range and nitpick comments (7)
src/components/Request/Create/Views/Initial.view.tsx (2)
134-141
: LGTM: Improved AddressInput props and handling.The changes to the
AddressInput
component improve its usage by consolidating multiple props into a singleonUpdate
function. This simplifies the component's interface and makes it easier to manage state updates.A minor suggestion:
Consider destructuring the
update
object in theonUpdate
function for improved readability:-onUpdate={(update: InputUpdate) => { - setRecipientAddress(update.value) - setInputChanging(update.isChanging) - setIsValidRecipient(update.isValid) +onUpdate={({ value, isChanging, isValid }: InputUpdate) => { + setRecipientAddress(value) + setInputChanging(isChanging) + setIsValidRecipient(isValid) }}
Line range hint
153-153
: LGTM: Improved submit button disabled state.The updated disabled state for the submit button enhances user experience by preventing submissions with invalid or incomplete data. This change aligns well with the new input validation approach.
Consider adding visual feedback or tooltips to indicate why the button is disabled. This could improve user understanding and guide them to complete the form correctly. For example:
<button className="wc-disable-mf btn-purple btn-xl" onClick={handleOnNext} disabled={!isValidRecipient || inputChanging || isLoading || !_tokenValue} title={ !isValidRecipient ? "Invalid recipient address" : inputChanging ? "Input is changing" : !_tokenValue ? "Token value is required" : isLoading ? "Processing..." : "" } > {isLoading ? ( <div className="flex w-full flex-row items-center justify-center gap-2"> <Loading /> {loadingState} </div> ) : ( 'Confirm' )} </button>This addition would provide more context to the user about why the button is disabled.
src/components/Global/AddressInput/index.tsx (1)
6-11
: Consider makingplaceholder
prop optional inAddressInputProps
Since a default value is provided for
placeholder
in the component, consider making it optional in theAddressInputProps
type definition to reflect that it's not required when using the component.Apply this diff to adjust the type definition:
type AddressInputProps = { - placeholder: string + placeholder?: string value: string onUpdate: (update: InputUpdate) => void className?: string }src/components/Global/ValidatedInput/index.tsx (4)
32-33
: Simplify the condition for better readabilityThe condition
'' === debouncedValue || debouncedValue === previousValueRef.current
can be simplified to improve readability.Apply this diff to simplify the condition:
-if ('' === debouncedValue || debouncedValue === previousValueRef.current) { +if (!debouncedValue || debouncedValue === previousValueRef.current) { return }
17-25
: Type the component usingFC
from ReactFor consistency and better type enforcement, consider typing the
ValidatedInput
component withReact.FC
.Apply this diff:
const ValidatedInput = ({ +const ValidatedInput: React.FC<ValidatedInputProps> = ({ label, placeholder = '', value, debounceTime = 300, onUpdate, validate, className, }: ValidatedInputProps) => {
80-82
: Reconsider settingspellCheck
to"false"
The
spellCheck
attribute is set to"false"
. If the input field is expected to accept text that might benefit from spell checking, consider enabling it.
85-91
: Add accessible labels to the loading spinnerThe loading spinner lacks accessible labels, which may hinder users relying on screen readers.
Apply this diff to include
aria-label
:<div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent motion-reduce:animate-none" role="status" + aria-label="Validating input" />
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
- src/components/Claim/Link/Initial.view.tsx (4 hunks)
- src/components/Global/AddressInput/index.tsx (1 hunks)
- src/components/Global/GeneralRecipientInput/index.tsx (1 hunks)
- src/components/Global/ValidatedInput/index.tsx (1 hunks)
- src/components/Request/Create/Views/Initial.view.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/components/Request/Create/Views/Initial.view.tsx (2)
Line range hint
1-172
: Overall assessment: Improvements align with PR objectives.The changes in this file successfully refactor the
AddressInput
component usage and improve state management for input validation. The modifications enhance the user experience by providing better control over form submission based on input validity and changes.Key improvements:
- Introduction of the
InputUpdate
type for consolidated input handling.- Simplified
AddressInput
component interface.- Enhanced submit button disabled state logic.
These changes align well with the PR objectives of refactoring input components and resolving issues related to input validation loops. The code is now more maintainable and provides a clearer flow of data and validation states.
10-10
: LGTM: New import for input validation.The addition of the
InputUpdate
import fromValidatedInput
is appropriate for the changes in this component. It suggests an improvement in input handling and validation.To ensure this import is used correctly throughout the file, run the following script:
✅ Verification successful
Verification Successful:
InputUpdate
is correctly used in the file.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of InputUpdate in the file # Test: Check if InputUpdate is used in the file rg -q 'InputUpdate' src/components/Request/Create/Views/Initial.view.tsx && echo "InputUpdate is used in the file" || echo "InputUpdate is not used in the file" # Test: Check how InputUpdate is used in the file rg 'InputUpdate' src/components/Request/Create/Views/Initial.view.tsxLength of output: 337
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/components/Global/GeneralRecipientInput/index.tsx (3)
29-62
: Well-refactoredcheckAddress
function.The
checkAddress
function has been significantly improved:
- Wrapping it in
useCallback
is good for performance.- The refactored logic is more concise and easier to follow.
- Returning a boolean aligns with the single responsibility principle.
One minor suggestion:
Consider extracting the regex for US account numbers into a named constant at the top of the file for better readability and maintainability:
const US_ACCOUNT_REGEX = /^[0-9]{6,17}$/;Then use it in the function:
} else if (US_ACCOUNT_REGEX.test(recipient)) {
64-89
: Well-structuredonInputUpdate
function.The
onInputUpdate
function is well-implemented:
- Using
useCallback
is good for performance.- It effectively handles both valid and invalid input cases.
- The update object construction aligns well with the
GeneralRecipientUpdate
type.A minor suggestion for improved clarity:
Consider using object shorthand notation when the property name matches the variable name. For example:
_update = { recipient: 'ens' === recipientType.current ? { address: resolvedAddress.current, name: update.value } : { address: update.value, name: undefined }, type: recipientType.current, isValid: true, isChanging: update.isChanging, errorMessage, // Using shorthand here }This makes the code slightly more concise and easier to read.
91-101
: Simplified render logic withValidatedInput
.The use of the
ValidatedInput
component greatly simplifies the render logic and improves the overall structure of the component. The props passed toValidatedInput
align well with its expected functionality.A minor suggestion for consistency:
Consider using object shorthand notation for the
className
prop to match the style used in other parts of the component:<ValidatedInput placeholder={placeholder} label="To" value={recipient.name ?? recipient.address} debounceTime={750} validate={checkAddress} onUpdate={onInputUpdate} className // Using shorthand here />This small change would make the prop passing style consistent throughout the component.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- src/components/Claim/Link/Initial.view.tsx (3 hunks)
- src/components/Global/GeneralRecipientInput/index.tsx (1 hunks)
- src/components/Global/ValidatedInput/index.tsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (12)
src/components/Global/GeneralRecipientInput/index.tsx (3)
2-21
: Improved imports and type definitions.The changes to imports and type definitions reflect a positive shift towards more functional programming practices and improved type safety. The new
GeneralRecipientUpdate
type provides a clear structure for updates, which enhances code readability and maintainability.
24-27
: Improved component structure and state management.The new component signature is more concise and clearly defines the expected props. The use of
useRef
forrecipientType
,errorMessage
, andresolvedAddress
is an excellent optimization, as these values don't need to trigger re-renders when changed.
Line range hint
1-105
: Overall excellent refactoring of the GeneralRecipientInput component.This refactoring represents a significant improvement in code structure, performance, and maintainability:
- Shift towards functional programming with
useCallback
anduseRef
.- Improved type definitions for better type safety.
- Simplified component structure with clear prop definitions.
- Well-refactored
checkAddress
andonInputUpdate
functions.- Use of
ValidatedInput
component for cleaner render logic.These changes align well with React best practices and modern JavaScript/TypeScript conventions. The code is now more readable, efficient, and easier to maintain.
src/components/Global/ValidatedInput/index.tsx (6)
3-16
: Well-defined prop types and interfacesThe component's props and update types are clearly defined, enhancing type safety and readability.
31-57
: Effective use ofuseEffect
for handling validationThe implementation correctly handles asynchronous validation with proper cleanup to prevent memory leaks. The
isStale
flag effectively prevents state updates on unmounted components.
59-66
: Appropriate debouncing logic inuseEffect
The use of
setTimeout
withinuseEffect
effectively debounces the input value, preventing excessive validation calls and improving performance.
67-70
: Correct handling of input changesThe
handleChange
function appropriately updates the state and notifies parent components of changes.
73-75
: Avoid duplicate class names in conditional renderingThe conditional class names might lead to duplicate border classes, potentially causing styling issues.
77-79
: Enhance accessibility by associating the label with the inputThe input field lacks an explicit association with the label, which can affect screen reader users.
src/components/Claim/Link/Initial.view.tsx (3)
1-2
: Import statement correctly updated.The import of
GeneralRecipientUpdate
is accurate, resolving the previous typo issue.
246-263
: Properly handle async operations insideuseEffect
.As previously noted, calling
estimatePoints
directly insideuseEffect
can lead to unhandled promises and potential issues. Consider defining and invoking an async function withinuseEffect
for better error handling and cleanup.
468-477
:onUpdate
handler correctly updates state.The
onUpdate
function successfully updates the state based onGeneralRecipientUpdate
, ensuring proper management of recipient data.
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, nice abstraction for inputs
Note: Didn't even knew we had a notion bot here...
In two components with similar logic (validating an input) there was an issue that if the input changed while still validating, it would enter in a loop alternating between both values, this PR fixes that by: