Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix: [Clear Button is active when no input is selected in Dropdown] #9264

Merged
merged 14 commits into from
Dec 11, 2024

Conversation

Rustix69
Copy link
Contributor

@Rustix69 Rustix69 commented Dec 1, 2024

Proposed Changes

  • Fixes Clear button is active when no input is selected in dropdown #9263
  • Added a state const [hasTyped, setHasTyped] = useState(false);.
  • Modified handleInputChange to set hasTyped(true) when the user types
  • In handleSelectionChange, set setQuery(optionLabel(selectedOption)); to update query after selection.
  • Set hasTyped(true) after selection to ensure the "Clear Selection" button is shown.
  • In the ComboboxButton rendering logic, updated the condition for showing the "Clear Selection" button:
  • Added setHasTyped(false) in the onClick handler for clearing selection to reset the hasTyped state.

Behaviour after the changes

  • The website allows users to search and select options from a dropdown, with the input dynamically filtering results as the user types.
  • The "Clear Selection" button only appears after the user types or selects an option, making it easy to clear the selected value.
  • The input field reflects the current query, and the dropdown updates based on the user's input, offering a smooth and interactive search experience.

Screen Records

Screencast.from.2024-12-02.00-14-08.webm

Summary by CodeRabbit

  • New Features

    • Enhanced facility selection handling allows for a clearer representation of no facility selected.
    • Improved navigation logic ensures actions only proceed with a valid facility selected.
  • Bug Fixes

    • Error handling added to prevent navigation attempts without a selected facility.
  • Documentation

    • Updated type definitions for state management to reflect nullable values for better clarity.

@Rustix69 Rustix69 requested a review from a team as a code owner December 1, 2024 18:56
Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Warning

Rate limit exceeded

@ANIR1604 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 32 seconds before requesting another review.

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between df44056 and b4f21d7.

📒 Files selected for processing (2)
  • src/components/Assets/AssetsList.tsx (3 hunks)
  • src/components/Patient/ManagePatients.tsx (2 hunks)

Walkthrough

The changes in this pull request focus on enhancing the state management of the AssetsList, FacilitiesSelectDialogue, and ManagePatients components. The selectedFacility state is now initialized as undefined or null, and the logic for handling these states has been updated accordingly. This includes modifications to conditional rendering and error handling to ensure that navigation and actions only occur when a valid facility is selected. The overall goal is to improve clarity and robustness in the handling of facility selection.

Changes

File Path Change Summary
src/components/Assets/AssetsList.tsx Updated selectedFacility state to be initialized as undefined. Adjusted conditional rendering logic and state reset in AssetImportModal.
src/components/ExternalResult/FacilitiesSelectDialogue.tsx Changed selectedFacility prop type to allow null. Updated logic for Submit button's disabled state.
src/components/Patient/ManagePatients.tsx Modified selectedFacility state to be nullable. Enhanced error handling in handleOk function and adjusted state reset logic.

Assessment against linked issues

Objective Addressed Explanation
Clear button state shouldn't be shown when no input is selected (9263) The changes do not address the issue regarding the clear button state in the AutoComplete dropdown.

Possibly related PRs

  • Added dynamic lock icon and strong types #9006: This PR modifies the handling of the selectedFacility state in the PatientHome component, which is directly related to the changes made in the AssetsList component regarding the selectedFacility state management.
  • Camera Preset Not Resetting on Re-selection Bug #9186: This PR updates the ManagePatients component to change the handling of the selectedFacility state, aligning with the changes made in the AssetsList component regarding state initialization and validation.
  • fixes dropdown click events issue #9047: This PR updates the FacilitiesSelectDialogue component, which is directly related to the changes in the AssetsList component as both involve the handling of the selectedFacility state and its validation logic.

Suggested reviewers

  • rithviknishad
  • khavinshankar
  • Jacobjeevan

Poem

In the land of code where rabbits play,
We fixed the states in a clearer way.
With null for facilities, oh what a sight,
No more confusion, everything feels right!
Hopping through logic, we made it so clear,
Now every selection brings us good cheer! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Dec 1, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit b4f21d7
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6757d8b1f431610008c2e9e3
😎 Deploy Preview https://deploy-preview-9264--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/Form/AutoCompleteAsync.tsx (2)

95-99: Consider resetting hasTyped when input is cleared

The input handling looks good, but consider resetting hasTyped to false when the input becomes empty through backspace/delete to maintain consistency with the component's behavior.

 const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
   const newQuery = event.target.value;
   setQuery(newQuery);
-  setHasTyped(newQuery.length > 0); // Set hasTyped to true if input is not empty
+  setHasTyped(newQuery.length > 0); // Update hasTyped based on input presence

107-108: Consider simplifying the visibility condition

While the logic is correct, the condition could be more readable by grouping related checks.

-  const shouldShowClearButton = (hasSelection || hasTyped) && query !== ""; // Exclude placeholder when query is empty
+  const shouldShowClearButton = query !== "" && (hasSelection || hasTyped); // Show only when there's input and user interaction
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f76c625 and f24045e.

📒 Files selected for processing (1)
  • src/components/Form/AutoCompleteAsync.tsx (4 hunks)
🔇 Additional comments (4)
src/components/Form/AutoCompleteAsync.tsx (4)

67-67: LGTM: Clean state management addition

The new state variable hasTyped is well-named and appropriately initialized to track user interaction with the input field.


101-105: LGTM: Comprehensive selection handling

The selection handler properly manages all relevant states, ensuring the input field reflects the selected option while maintaining the typed state.


147-157: LGTM: Comprehensive clear button implementation

The clear button implementation properly resets all relevant states and maintains good UX with tooltips and accessibility features.


Line range hint 1-236: Verify similar patterns in other form components

Let's ensure consistency across other form components that might have similar clear button functionality.

✅ Verification successful

Clear button implementation is consistent with existing patterns

The implementation in AutoCompleteAsync.tsx follows the same clear button pattern found in other form components:

  • TextFormField.tsx uses CareIcon with l-times-circle for clearing input
  • ModelCrudEditor.tsx uses similar icon pattern for removal actions
  • The new implementation maintains consistency with these existing patterns, including:
    • Using the same icon (l-times-circle)
    • Proper positioning (absolute positioning on the right)
    • Similar interaction patterns (click to clear)
    • Consistent styling approach

The changes align well with the existing codebase patterns and maintain UI/UX consistency across form components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar clear button patterns in other form components
echo "Searching for similar clear button implementations..."
rg -l "CareIcon.*times-circle" "src/components/Form"

# Search for other autocomplete implementations
echo "Checking for other autocomplete implementations..."
rg -l "Combobox.*clear.*selection" "src/components"

Length of output: 421


Script:

#!/bin/bash
# Let's examine the clear button implementations in the identified files
echo "Checking ModelCrudEditor.tsx implementation:"
rg -A 5 -B 5 "times-circle" "src/components/Form/ModelCrudEditor.tsx"

echo "\nChecking TextFormField.tsx implementation:"
rg -A 5 -B 5 "times-circle" "src/components/Form/FormFields/TextFormField.tsx"

# Let's also check for other Combobox components that might have similar patterns
echo "\nChecking for other Combobox components:"
ast-grep --pattern 'const $_ = ($_: Props) => {
  $$$
  Combobox
  $$$
}'

Length of output: 1218

@Rustix69
Copy link
Contributor Author

Rustix69 commented Dec 1, 2024

@Jacobjeevan I had not touched the other codes but its giving errors in Cypress Tests that are being shown in different components. And the clear button is working smoothly after making the code changes

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 1, 2024
@Jacobjeevan Jacobjeevan added changes required and removed question Further information is requested needs-triage labels Dec 2, 2024
@Jacobjeevan
Copy link
Contributor

@ANIR1604 Any updates?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
src/components/Assets/AssetsList.tsx (2)

Line range hint 461-477: Consider using a more robust null check

The current check facility === null might miss cases where facility is undefined. Consider using a more inclusive check.

-      {facility === null && (
+      {!facility && (

498-506: Enhance error logging message

While the null check is good, the error message could be more descriptive to aid debugging.

-            console.error("No facility selected");
+            console.error("Navigation failed: No facility selected in FacilitiesSelectDialogue");
src/components/Patient/ManagePatients.tsx (1)

960-973: Consider adding error notification for better UX

While the error logging is good, consider showing a user-friendly notification when no facility is selected.

          } else {
            console.error("No facility selected");
+           Notification.Error({
+             msg: "Please select a facility to continue"
+           });
          }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f24045e and d047018.

📒 Files selected for processing (3)
  • src/components/Assets/AssetsList.tsx (4 hunks)
  • src/components/ExternalResult/FacilitiesSelectDialogue.tsx (1 hunks)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🔇 Additional comments (5)
src/components/ExternalResult/FacilitiesSelectDialogue.tsx (1)

14-14: LGTM: Type enhancement for better null safety

The change to make selectedFacility explicitly nullable improves type safety and aligns with the component's behavior.

src/components/Assets/AssetsList.tsx (2)

49-49: LGTM: Consistent state initialization

The initialization of facility and selectedFacility states with null is consistent with the type changes and provides clear initial state representation.

Also applies to: 55-56


480-485: LGTM: Proper state cleanup

The facility state reset logic is well-implemented with appropriate condition checking.

src/components/Patient/ManagePatients.tsx (2)

105-106: LGTM: Consistent state initialization

The initialization of selectedFacility as null is consistent with the pattern used across other components.


978-978: LGTM: Proper state cleanup

The reset of selectedFacility to null on cancel is appropriate.

@Rustix69
Copy link
Contributor Author

Rustix69 commented Dec 5, 2024

@ANIR1604 Any updates?

Now It's working Perfect Sir @Jacobjeevan. I had attached a screencast of the website after the changes. Plz review and approve my PR if it's ok.

Screencast.from.2024-12-06.03-55-34.webm

@Rustix69 Rustix69 requested a review from Jacobjeevan December 5, 2024 22:49
src/components/Assets/AssetsList.tsx Outdated Show resolved Hide resolved
src/components/Patient/ManagePatients.tsx Outdated Show resolved Hide resolved
src/components/Patient/ManagePatients.tsx Outdated Show resolved Hide resolved
src/components/Assets/AssetsList.tsx Outdated Show resolved Hide resolved
src/components/Assets/AssetsList.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
src/components/Patient/ManagePatients.tsx (1)

978-991: Enhance error message clarity

While the error handling is good, the error messages could be more descriptive and actionable.

Consider updating the error messages to be more specific:

-            Notification.Error({ msg: "No facility selected" });
+            Notification.Error({ msg: "Please select a facility to proceed" });
-            Notification.Error({ msg: "Unknown dialog state" });
+            Notification.Error({ msg: "Invalid operation requested. Please try again" });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d047018 and 8ec85e6.

📒 Files selected for processing (2)
  • src/components/Assets/AssetsList.tsx (4 hunks)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Assets/AssetsList.tsx
🔇 Additional comments (2)
src/components/Patient/ManagePatients.tsx (2)

103-104: LGTM: Proper state initialization

The nullable type definition and null initialization for selectedFacility state is appropriate for handling the unselected state.


996-996: LGTM: Proper state cleanup

The reset of selectedFacility to null in the cancel handler ensures proper cleanup of the selection state.

@Rustix69 Rustix69 requested a review from Jacobjeevan December 6, 2024 16:26
@Rustix69
Copy link
Contributor Author

Rustix69 commented Dec 6, 2024

@Jacobjeevan Solved all the errors related to clear selection at all instances.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
src/components/Patient/ManagePatients.tsx (1)

978-993: Consider extracting dialog handlers into separate functions.

The current implementation works correctly but could be more maintainable. Consider refactoring the handlers into separate functions for better readability and testability.

+ const handleFacilityDialogOk = () => {
+   if (!selectedFacility) {
+     Notification.Error({ msg: "No facility selected" });
+     return;
+   }
+   
+   const routes = {
+     create: `facility/${selectedFacility.id}/patient`,
+     'list-discharged': `facility/${selectedFacility.id}/discharged-patients`
+   };
+   
+   const route = routes[showDialog];
+   if (route) {
+     navigate(route);
+   }
+ };
+
+ const handleFacilityDialogCancel = () => {
+   setShowDialog(undefined);
+   setSelectedFacility(null);
+ };

  <FacilitiesSelectDialogue
    show={!!showDialog}
    setSelected={(e) => setSelectedFacility(e)}
    selectedFacility={selectedFacility}
-   handleOk={() => {
-     if (selectedFacility) {
-       switch (showDialog) {
-         case "create":
-           navigate(`facility/${selectedFacility.id}/patient`);
-           break;
-         case "list-discharged":
-           navigate(`facility/${selectedFacility.id}/discharged-patients`);
-           break;
-       }
-     } else {
-       Notification.Error({ msg: "No facility selected" });
-     }
-   }}
-   handleCancel={() => {
-     setShowDialog(undefined);
-     setSelectedFacility(null);
-   }}
+   handleOk={handleFacilityDialogOk}
+   handleCancel={handleFacilityDialogCancel}
  />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8ec85e6 and 6656540.

📒 Files selected for processing (1)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Patient/ManagePatients.tsx (1)

103-104: LGTM! Explicit nullable type improves type safety.

The state initialization with explicit null type aligns well with TypeScript best practices and helps prevent undefined behavior.

@Rustix69 Rustix69 requested a review from Jacobjeevan December 6, 2024 18:25
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
src/components/Assets/AssetsList.tsx (1)

Line range hint 461-472: Fix the handleOk implementation and null check

Two issues need attention:

  1. The handleOk function returns undefined without any action, which seems incorrect
  2. The null check should use strict equality for better type safety

Apply these changes:

-      {facility == null && (
+      {facility === null && (
         <FacilitiesSelectDialogue
           show={importAssetModalOpen}
           setSelected={(e) => setFacility(e)}
           selectedFacility={selectedFacility}
-          handleOk={() => {
-            return undefined;
-          }}
+          handleOk={() => {
+            if (selectedFacility) {
+              setFacility(selectedFacility);
+              setImportAssetModalOpen(false);
+            }
+          }}
           handleCancel={() => {
             return setImportAssetModalOpen(false);
           }}
         />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6656540 and 65f43c6.

📒 Files selected for processing (2)
  • src/components/Assets/AssetsList.tsx (4 hunks)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Patient/ManagePatients.tsx
🧰 Additional context used
📓 Learnings (1)
src/components/Assets/AssetsList.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9080
File: src/components/Users/LinkedFacilities.tsx:42-42
Timestamp: 2024-11-12T12:46:55.920Z
Learning: In the `LinkedFacilities` component (`src/components/Users/LinkedFacilities.tsx`), when using `FacilitySelect` which supports an array of `FacilityModel` items, and restricting selection to just one, it's acceptable to keep the `facility` state typed as `any` to maintain compatibility.
🔇 Additional comments (3)
src/components/Assets/AssetsList.tsx (3)

55-55: LGTM: State initialization follows established patterns

The initialization of selectedFacility as an optional FacilityModel aligns with the component's requirements and existing patterns.


494-503: LGTM: Robust facility selection handling

The implementation includes all necessary safeguards:

  • Null check before navigation
  • User feedback through notification
  • Proper state cleanup on cancel

55-55: Verify alignment with PR objectives

While the facility selection implementation is solid, let's verify if these changes address the original issue regarding the clear button visibility in the dropdown component.

Also applies to: 494-503

@Rustix69
Copy link
Contributor Author

@rithviknishad Ok I will be working on this tomorrow. Can't I change it to null at Time 0 ? In my point of view it will be a great approach to give it a null value.

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 10, 2024
@Rustix69
Copy link
Contributor Author

@rithviknishad Sir plz review my PR ... Are we ok to go with these changes ?

@rithviknishad rithviknishad removed Deploy-Failed Deplyment is not showing preview question Further information is requested needs-triage labels Dec 11, 2024
@rithviknishad rithviknishad merged commit 113dddd into ohcnetwork:develop Dec 11, 2024
20 checks passed
Copy link

@ANIR1604 Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Clear button is active when no input is selected in dropdown
4 participants