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

Feat: Update the design and shortcut key for SearchByMultipleOptions #9851

Open
wants to merge 84 commits into
base: develop
Choose a base branch
from

Conversation

AdityaJ2305
Copy link
Contributor

@AdityaJ2305 AdityaJ2305 commented Jan 8, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced search functionality with improved keyboard navigation and device-specific shortcuts.
    • Added option to choose different search types.
  • Improvements

    • Updated user interface for search components.
    • Improved form validation and error handling.
    • Enhanced user experience with a clear search option.
    • Enhanced control flow in user password reset with visual feedback during operations.
  • Component Updates

    • Replaced OrganizationSelector with GovtOrganizationSelector in multiple components.
    • Refined search option management across different pages.
    • Transitioned facility form to focus solely on creation mode.
  • Localization

    • Added new translation keys for search functionality.

Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces comprehensive modifications to the search functionality across multiple components. The primary focus is on enhancing the SearchByMultipleFields component with improved keyboard navigation, device-specific shortcuts, and refined search option rendering. Additionally, several components have been updated to use a new GovtOrganizationSelector, and localization improvements have been made to support more intuitive search interactions.

Changes

File Change Summary
src/components/Common/SearchByMultipleFields.tsx Major refactoring of search component with new keyboard navigation, device-specific shortcuts, and enhanced UI. Removed shortcutKey, made initialOptionIndex required.
src/pages/Encounters/EncounterList.tsx Introduced handleFieldChange method to update query parameters on field changes. Removed unused clearSearch function.
src/pages/Organization/OrganizationPatients.tsx Improved search parameter management and added phone number length validation. Updated onSearch and onFieldChange props.
src/components/Patient/PatientIndex.tsx Removed shortcutKey from search options and updated phone number reset logic.
src/components/Patient/PatientRegistration.tsx Replaced OrganizationSelector with GovtOrganizationSelector.
src/components/Users/CreateUserForm.tsx Replaced OrganizationSelector with GovtOrganizationSelector.
src/pages/Facility/FacilitiesPage.tsx Removed clearSearch and updated shortcutKey to initialOptionIndex.
src/pages/Organization/components/GovtOrganizationSelector.tsx Renamed OrganizationSelector to GovtOrganizationSelector with updated interface.
public/locale/en.json Added new localization keys for search functionality.
src/components/Users/UserResetPassword.tsx Updated button logic for password reset with visual feedback.
src/components/Facility/FacilityForm.tsx Transitioned to a creation mode for the facility form, updated schema and removed organization selection logic.

Assessment against linked issues

Objective Addressed Explanation
Implement ⌘K shortcut
Navigation through dropdown with arrow keys
ENTER key for search type selection
ESC key to close dropdown and clear input
Phone number search validation Minimum length check added.

Possibly related PRs

  • Reorder Patient Search buttons #9319: The changes in the main PR regarding the SearchByMultipleFields component and the removal of the shortcutKey property relate to the reordering of search buttons in this PR, which also involves modifications to search functionality.
  • Search UI for discharge patients #9320: The introduction of the SearchByMultipleFields component in the DischargedPatientsList component is relevant as it enhances search capabilities, similar to the changes made in the main PR.
  • New Patient Search and Register UI #9400: The new patient search and register UI in this PR may relate to the changes in the SearchByMultipleFields component, as both involve improving search functionalities.

Suggested labels

needs review, needs testing

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hop, hop, search with glee,
Keys dancing, options free!
⌘K brings magic near,
Search refined without a fear
A rabbit's code, crisp and bright! 🔍


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b6f9e8b and 9ad3ca1.

📒 Files selected for processing (1)
  • public/locale/en.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)

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. (Beta)
  • @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 Jan 8, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4a59e22
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678bba7b33a0b80008aafac1
😎 Deploy Preview https://deploy-preview-9851--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.

@JavidSumra
Copy link
Contributor

@AdityaJ2305 I think you can make use of useKeyBoardShortcut hook instead of manual handling keyboard events

@Jacobjeevan Jacobjeevan mentioned this pull request Jan 10, 2025
6 tasks
@AdityaJ2305
Copy link
Contributor Author

Fixed: #9867 (comment)

@AdityaJ2305 AdityaJ2305 marked this pull request as ready for review January 10, 2025 18:14
@AdityaJ2305 AdityaJ2305 requested a review from a team as a code owner January 10, 2025 18:14
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: 2

🧹 Nitpick comments (3)
src/pages/Organization/OrganizationPatients.tsx (1)

41-52: Consider improving phone number validation.

The phone number validation logic could be more robust:

  1. The magic number 13 should be extracted as a constant for better maintainability.
  2. The validation should consider minimum length requirements for different phone number formats.

Apply this diff to improve the validation:

+const MIN_PHONE_LENGTH = 13;
+
 const handleSearch = useCallback((key: string, value: string) => {
   const searchParams = {
     name: key === "name" ? value : "",
     phone_number:
       key === "phone_number"
-        ? value.length >= 13 || value === ""
+        ? value.length >= MIN_PHONE_LENGTH || value === ""
           ? value
           : undefined
         : undefined,
   };
   updateQuery(searchParams);
 }, []);
src/components/Common/SearchByMultipleFields.tsx (2)

191-214: Reduce code duplication in keyboard shortcut hints.

The keyboard shortcut hint UI is duplicated between the phone number input and text input sections. Consider extracting it into a reusable component.

Create a new component for the keyboard hints:

const KeyboardShortcutHint: React.FC<{ isOpen: boolean }> = ({ isOpen }) => {
  if (isOpen) {
    return (
      <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
        ESC
      </span>
    );
  }
  
  return (
    <span>
      {isAppleDevice ? (
        <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
          ⌘K
        </span>
      ) : (
        <div className="flex gap-1 font-medium">
          <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
            Ctrl
          </span>
          <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
            K
          </span>
        </div>
      )}
    </span>
  );
};

Then use it in both places:

 <div className="absolute top-1/2 right-2 transform -translate-y-1/2 flex items-center space-x-2 text-xs text-gray-500">
-  {open ? (
-    <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
-      ESC
-    </span>
-  ) : (
-    <span>
-      {isAppleDevice ? (
-        <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
-          ⌘K
-        </span>
-      ) : (
-        <div className="flex gap-1 font-medium">
-          <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
-            Ctrl
-          </span>
-          <span className="border border-gray-300 rounded px-1 py-0.5 bg-white text-gray-500">
-            K
-          </span>
-        </div>
-      )}
-    </span>
-  )}
+  <KeyboardShortcutHint isOpen={open} />
 </div>

Also applies to: 226-249


130-140: Enhance keyboard navigation robustness.

The keyboard navigation logic could be improved in two areas:

  1. Add visual feedback when no item is focused (focusedIndex === -1)
  2. Make the Enter key handler more defensive

Apply these improvements:

 } else if (e.key === "Enter" && focusedIndex !== -1) {
+  if (focusedIndex >= unselectedOptions.length) {
+    return;
+  }
   const selectedOptionIndex = options.findIndex(
     (option) => option.key === unselectedOptions[focusedIndex].key,
   );
+  if (selectedOptionIndex === -1) {
+    return;
+  }
   handleOptionChange(selectedOptionIndex);
 }

Also, consider adding a CSS class to indicate when no item is focused:

 className={cn(
   "flex items-center p-2 rounded-md cursor-pointer",
   {
     "bg-gray-100": focusedIndex === index,
+    "bg-gray-50": focusedIndex === -1,
     "hover:bg-secondary-100": true,
   },
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b998f5d and 7f2735f.

📒 Files selected for processing (3)
  • src/components/Common/SearchByMultipleFields.tsx (5 hunks)
  • src/pages/Encounters/EncounterList.tsx (2 hunks)
  • src/pages/Organization/OrganizationPatients.tsx (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/pages/Encounters/EncounterList.tsx

[error] 165-175: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

src/pages/Organization/OrganizationPatients.tsx

[error] 55-61: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (1)
src/components/Common/SearchByMultipleFields.tsx (1)

118-126: LGTM! Keyboard shortcut implementation follows best practices.

The change from "/" to "Cmd/Ctrl + K" aligns with modern web application patterns and provides a more intuitive search experience. The implementation correctly handles both Mac and Windows/Linux modifier keys.

src/pages/Organization/OrganizationPatients.tsx Outdated Show resolved Hide resolved
src/pages/Encounters/EncounterList.tsx Outdated Show resolved Hide resolved
@AdityaJ2305 AdityaJ2305 marked this pull request as draft January 11, 2025 06:23
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 12, 2025
Copy link

👋 Hi, @AdityaJ2305,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@AdityaJ2305 AdityaJ2305 force-pushed the serachinput_design_update branch from 91e9334 to 3cfb24a Compare January 12, 2025 09:37
@AdityaJ2305
Copy link
Contributor Author

AdityaJ2305 commented Jan 12, 2025

  • Rename to GovtOrganizationSelector

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

🧹 Nitpick comments (1)
src/components/Common/SearchByMultipleFields.tsx (1)

383-396: Add accessibility attributes to clear search button.

The clear search button needs proper accessibility attributes.

 <Button
   variant="ghost"
   size="sm"
+  aria-label={t("clear_search")}
   className="w-full flex items-center justify-center text-muted-foreground"
   onClick={() => {
     setSearchValue("");
     inputRef.current?.focus();
   }}
 >
   <CareIcon icon="l-times" className="mr-2 h-4 w-4" />
   {t("clear_search")}
 </Button>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 013e52a and 166646b.

📒 Files selected for processing (1)
  • src/components/Common/SearchByMultipleFields.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
🔇 Additional comments (6)
src/components/Common/SearchByMultipleFields.tsx (6)

56-79: Well-structured keyboard shortcut component!

Good job on:

  • Extracting the component outside the main component
  • Using semantic kbd tags
  • Handling device-specific shortcuts

141-156: Improved keyboard shortcut handling!

Good improvements:

  • Added stopPropagation() to prevent browser's search on Ctrl+K
  • Enhanced Escape key handling to clear search or close menu

210-234: Clean UI implementation with error handling!

Good improvements:

  • Added error handling for phone input
  • Consistent keyboard shortcut hint placement
  • Proper error state management

260-354: Excellent search options UI implementation!

Great attention to:

  • Keyboard navigation hints with Enter key
  • Proper ARIA attributes
  • Clear visual feedback for focused state

94-102: ⚠️ Potential issue

Add bounds checking for initialOptionIndex.

The initialOptionIndex should be validated to prevent array out-of-bounds errors.

-  const [selectedOptionIndex, setSelectedOptionIndex] = useState(initialOptionIndex);
+  const [selectedOptionIndex, setSelectedOptionIndex] = useState(
+    initialOptionIndex < 0 || initialOptionIndex >= options.length
+      ? 0
+      : initialOptionIndex
+  );

Likely invalid or redundant comment.


160-170: ⚠️ Potential issue

Add empty state handling for keyboard navigation.

The code is vulnerable to runtime errors when unselectedOptions is empty.

 if (open) {
+  if (unselectedOptions.length === 0) return;
   if (e.key === "ArrowDown") {
     setFocusedIndex((prevIndex) =>
       prevIndex === unselectedOptions.length - 1 ? 0 : prevIndex + 1,
     );
   } else if (e.key === "ArrowUp") {
     setFocusedIndex((prevIndex) =>
       prevIndex === 0 ? unselectedOptions.length - 1 : prevIndex - 1,
     );
   } else if (e.key === "Enter") {
+    if (focusedIndex < 0 || focusedIndex >= unselectedOptions.length) return;
     const selectedOptionIndex = options.findIndex(
       (option) => option.key === unselectedOptions[focusedIndex].key,
     );
     handleOptionChange(selectedOptionIndex);
   }
 }

Likely invalid or redundant comment.

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

🧹 Nitpick comments (1)
src/components/Common/SearchByMultipleFields.tsx (1)

107-107: Use strict equality operator.

Replace == with === for strict type checking:

-const isSingleOption = options.length == 1;
+const isSingleOption = options.length === 1;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 166646b and 2440d1e.

📒 Files selected for processing (1)
  • src/components/Common/SearchByMultipleFields.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (4)
src/components/Common/SearchByMultipleFields.tsx (4)

56-84: Well-implemented keyboard shortcut component!

The KeyboardShortcutHint component follows best practices by using semantic kbd tags and handling device-specific shortcuts appropriately.


146-161: Improved keyboard shortcut handling!

The implementation properly addresses the reported issues:

  • Prevents browser's default search behavior with stopPropagation
  • Correctly manages input focus
  • Clearly separates Escape key behaviors for menu close and search clear

165-175: Add empty state handling for keyboard navigation.

The keyboard navigation logic needs guards for empty state:

 if (open) {
+  if (unselectedOptions.length === 0) return;
+
   if (e.key === "ArrowDown") {
     setFocusedIndex((prevIndex) =>
       prevIndex === unselectedOptions.length - 1 ? 0 : prevIndex + 1,
     );
   } else if (e.key === "ArrowUp") {
     setFocusedIndex((prevIndex) =>
       prevIndex === 0 ? unselectedOptions.length - 1 : prevIndex - 1,
     );
   } else if (e.key === "Enter") {
+    if (focusedIndex < 0 || focusedIndex >= unselectedOptions.length) return;
     const selectedOptionIndex = options.findIndex(
       (option) => option.key === unselectedOptions[focusedIndex].key,
     );
     handleOptionChange(selectedOptionIndex);
   }
 }

388-401: Add accessibility attributes to clear search button.

The clear search button should have proper accessibility attributes:

 <Button
   variant="ghost"
   size="sm"
+  aria-label={t("clear_search")}
   className="w-full flex items-center justify-center text-muted-foreground"
   onClick={() => {
     setSearchValue("");
     inputRef.current?.focus();
   }}
 >
   <CareIcon icon="l-times" className="mr-2 h-4 w-4" />
   {t("clear_search")}
 </Button>

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

🧹 Nitpick comments (2)
src/pages/Organization/OrganizationPatients.tsx (1)

65-72: Remove redundant block statement.

The function contains an unnecessary block statement that can be safely removed.

Apply this diff to simplify the code:

 const handleFieldChange = () => {
-  {
-    updateQuery({
-      name: undefined,
-      phone_number: undefined,
-    });
-  }
+  updateQuery({
+    name: undefined,
+    phone_number: undefined,
+  });
 };
🧰 Tools
🪛 Biome (1.9.4)

[error] 66-71: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

src/pages/Encounters/EncounterList.tsx (1)

163-174: Remove redundant block statement.

The function contains an unnecessary block statement that can be safely removed.

Apply this diff to simplify the code:

 const handleFieldChange = () => {
-  {
-    updateQuery({
-      status,
-      encounter_class: encounterClass,
-      priority,
-      name: undefined,
-      encounter_id: undefined,
-      external_identifier: undefined,
-    });
-  }
+  updateQuery({
+    status,
+    encounter_class: encounterClass,
+    priority,
+    name: undefined,
+    encounter_id: undefined,
+    external_identifier: undefined,
+  });
 };
🧰 Tools
🪛 Biome (1.9.4)

[error] 164-173: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2440d1e and b57bc33.

📒 Files selected for processing (5)
  • public/locale/en.json (2 hunks)
  • src/components/Facility/CreateFacilityForm.tsx (2 hunks)
  • src/pages/Encounters/EncounterList.tsx (3 hunks)
  • src/pages/Facility/FacilitiesPage.tsx (2 hunks)
  • src/pages/Organization/OrganizationPatients.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/components/Facility/CreateFacilityForm.tsx
  • src/pages/Facility/FacilitiesPage.tsx
  • public/locale/en.json
🧰 Additional context used
🪛 Biome (1.9.4)
src/pages/Encounters/EncounterList.tsx

[error] 164-173: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

src/pages/Organization/OrganizationPatients.tsx

[error] 66-71: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: CodeQL-Build
🔇 Additional comments (7)
src/pages/Organization/OrganizationPatients.tsx (4)

33-33: LGTM!

The cacheBlacklist is correctly updated to include the search fields used in the component.


37-50: LGTM!

The searchOptions array is well-structured with clear placeholders and proper typing.


106-112: LGTM!

The SearchByMultipleFields component is correctly configured with the new props.


52-63: 🛠️ Refactor suggestion

Improve phone number validation logic.

The current validation logic for phone numbers (length >= 13) seems arbitrary and might prevent searching for valid phone numbers with different formats.

Consider using a more flexible validation approach:

-        key === "phone_number"
-          ? value.length >= 13 || value === ""
-            ? value
-            : undefined
-          : undefined,
+        key === "phone_number"
+          ? value.trim() || undefined
+          : undefined,

Let the PhoneNumberFormField component handle the validation and error display instead.

Likely invalid or redundant comment.

src/pages/Encounters/EncounterList.tsx (3)

151-154: LGTM!

The cacheBlacklist is correctly updated to include all the search fields used in the component.


275-279: LGTM!

The onEscapeKeyDown handler is correctly added to prevent the default Esc key behavior, addressing the issue mentioned in the PR objectives.


287-293: LGTM!

The SearchByMultipleFields component is correctly configured with the new props.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 16, 2025
Copy link

👋 Hi, @AdityaJ2305,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 16, 2025
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

🧹 Nitpick comments (5)
src/components/Facility/FacilityForm.tsx (5)

46-68: Consider making the phone number validation more flexible for international usage.

The phone number validation is currently hardcoded for Indian numbers (+91). Consider making it more flexible to support international phone numbers.

-    .regex(
-      /^\+91[0-9]{10}$/,
-      "Phone number must start with +91 followed by 10 digits",
-    ),
+    .regex(
+      /^\+[1-9]\d{1,14}$/,
+      "Please enter a valid international phone number (E.164 format)",
+    ),

109-117: Enhance error handling with type safety.

Consider using a typed error interface instead of casting to an unknown structure. This will make the error handling more maintainable and type-safe.

interface FacilityError {
  errors: {
    msg: string[];
  };
}

// Usage in onError
onError: (error: Error) => {
  const errorData = error.cause as FacilityError;
  // ... rest of the code
}

148-148: Consider making the geolocation timeout configurable.

The 10-second timeout is hardcoded. Consider making it configurable through props or environment variables for different network conditions.


331-331: Internationalize loading and action text.

Consider using translation keys for consistency with the rest of the application:

  • "Getting Location..."
  • "Get Current Location"
  • "Creating Facility..."
  • "Create Facility"
-                  Getting Location...
+                  {t("getting_location")}
-                  Get Current Location
+                  {t("get_current_location")}
-              Creating Facility...
+              {t("creating_facility")}
-            "Create Facility"
+            {t("create_facility")}

Also applies to: 336-336, 446-446, 449-449


160-160: Enhance accessibility for form sections.

Add aria-labels to the form sections for better screen reader support.

-          <h3 className="text-lg font-medium">Basic Information</h3>
+          <h3 className="text-lg font-medium" aria-label="Basic Information Section">Basic Information</h3>
// Apply similar changes to other section headings

Also applies to: 255-255, 318-318, 387-387

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f64215 and 03605a3.

📒 Files selected for processing (3)
  • public/locale/en.json (2 hunks)
  • src/components/Facility/FacilityForm.tsx (9 hunks)
  • src/pages/Organization/components/GovtOrganizationSelector.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pages/Organization/components/GovtOrganizationSelector.tsx
  • public/locale/en.json
🧰 Additional context used
📓 Learnings (1)
src/components/Facility/FacilityForm.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9852
File: src/components/Facility/FacilityCreate.tsx:505-509
Timestamp: 2025-01-10T10:19:48.667Z
Learning: The `FacilityCreate` component in `src/components/Facility/FacilityCreate.tsx` is being phased out in favor of `CreateFacilityForm`.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (1)
src/components/Facility/FacilityForm.tsx (1)

414-431: Review the organization selector visibility logic.

The organization selector is shown when organizationId is not provided, but marked as required. This might lead to confusion. Consider:

  1. Making the logic more explicit
  2. Adding a comment explaining the conditional rendering
  3. Validating the organization selection in the form schema
✅ Verification successful

The organization selector logic is correctly implemented

The current implementation handles two valid scenarios:

  1. When organizationId is provided, it's automatically set as geo_organization
  2. When organizationId is not provided, user must select using the required selector

Consider adding a comment explaining this dual-mode behavior for better maintainability.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if this component is used without organizationId elsewhere
rg "CreateFacilityForm" -A 5 -B 5

Length of output: 731


Script:

#!/bin/bash
# Check for schema definition and validation
rg "const.*Schema.*=.*z\." -A 10 src/components/Facility/FacilityForm.tsx

# Look for component usage
rg "<CreateFacilityForm" -A 3 -B 3

Length of output: 533


Script:

#!/bin/bash
# Get complete schema definition
rg "facilityFormSchema.*=.*z\.object\({" -A 20 src/components/Facility/FacilityForm.tsx

# Look for component usage with different patterns
rg -l "FacilityForm" | xargs rg "organizationId"

Length of output: 938

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

🔭 Outside diff range comments (2)
src/components/Facility/FacilityForm.tsx (2)

Line range hint 116-134: Simplify form submission logic to handle only creation.

Since this component is transitioning to a creation-only form:

  1. Remove the update-related mutation
  2. Simplify the onSubmit handler
  3. Clean up the isPending state handling
-const { mutate: updateFacility, isPending: isUpdatePending } = useMutation({
-  mutationFn: mutate(routes.updateFacility, {
-    pathParams: { id: facilityId || "" },
-  }),
-  onSuccess: (_data: FacilityModel) => {
-    toast.success(t("facility_updated_successfully"));
-    queryClient.invalidateQueries({ queryKey: ["organizationFacilities"] });
-    form.reset();
-    onSubmitSuccess?.();
-  },
-});

 const onSubmit = (data: FacilityFormValues) => {
-  const requestData = {
-    ...data,
-    phone_number: parsePhoneNumber(data.phone_number),
-  };
-
-  if (facilityId) {
-    updateFacility(requestData);
-  } else {
-    createFacility(requestData);
-  }
+  createFacility({
+    ...data,
+    phone_number: parsePhoneNumber(data.phone_number),
+  });
 };

Line range hint 509-533: Simplify submit button to handle only creation state.

The submit button still handles both create and update states. Simplify it to match the component's new purpose.

 <Button
   type="submit"
   className="w-full"
-  disabled={facilityId ? isUpdatePending : isPending}
-  data-cy={facilityId ? "update-facility" : "submit-facility"}
+  disabled={isPending}
+  data-cy="submit-facility"
 >
-  {facilityId ? (
-    isUpdatePending ? (
-      <>
-        <CareIcon
-          icon="l-spinner"
-          className="mr-2 h-4 w-4 animate-spin"
-        />
-        {t("updating_facility")}
-      </>
-    ) : (
-      t("update_facility")
-    )
-  ) : isPending ? (
+  {isPending ? (
     <>
       <CareIcon
         icon="l-spinner"
         className="mr-2 h-4 w-4 animate-spin"
       />
       {t("creating_facility")}
     </>
   ) : (
     t("create_facility")
   )}
 </Button>
🧹 Nitpick comments (1)
src/components/Facility/FacilityForm.tsx (1)

Line range hint 1-47: Consider implementing keyboard shortcuts using useKeyBoardShortcut hook.

As suggested in the PR comments by JavidSumra, consider implementing keyboard shortcuts using the useKeyBoardShortcut hook for better user experience.

 import { useEffect, useState } from "react";
+import { useKeyBoardShortcut } from "@/hooks/useKeyBoardShortcut";
 import { useForm } from "react-hook-form";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03605a3 and 49995aa.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityForm.tsx (2 hunks)
  • src/pages/Organization/components/GovtOrganizationSelector.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pages/Organization/components/GovtOrganizationSelector.tsx
🧰 Additional context used
📓 Learnings (1)
src/components/Facility/FacilityForm.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9852
File: src/components/Facility/FacilityCreate.tsx:505-509
Timestamp: 2025-01-10T10:19:48.667Z
Learning: The `FacilityCreate` component in `src/components/Facility/FacilityCreate.tsx` is being phased out in favor of `CreateFacilityForm`.
🔇 Additional comments (1)
src/components/Facility/FacilityForm.tsx (1)

Line range hint 384-393: Update form schema to match the new organization selector implementation.

The form schema still uses geo_organization while the UI has been updated to use GovtOrganizationSelector. This mismatch could lead to validation issues.

Let's verify if this change is consistent across the codebase:

src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 17, 2025
@rithviknishad rithviknishad removed changes required Deploy-Failed Deplyment is not showing preview labels Jan 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
4 participants