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: added clear search on removing badge and added keyboard shortcuts #9438

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

noufalrahim
Copy link
Contributor

@noufalrahim noufalrahim commented Dec 15, 2024

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

  • New Features

    • Enhanced search component to reset input when the "clearSearch" parameter includes "search".
    • Added keyboard shortcuts: clear input with "Escape" and focus input with "Ctrl+K" or "Meta+K".
  • Bug Fixes

    • Improved error handling by resetting error state upon option selection.

@noufalrahim noufalrahim requested a review from a team as a code owner December 15, 2024 08:40
Copy link
Contributor

coderabbitai bot commented Dec 15, 2024

Walkthrough

The pull request modifies the SearchByMultipleFields component to improve search functionality and user interaction. The changes focus on enhancing keyboard shortcuts and search field reset behavior. Specifically, the component now supports clearing the search input using the "Escape" key and focusing the input with "Ctrl+K" or "Meta+K" shortcuts. The implementation also adds logic to reset the search value when certain clear search parameters are provided, improving the overall user experience of the search component.

Changes

File Change Summary
src/components/Common/SearchByMultipleFields.tsx - Added keyboard event handling for "Escape" key to clear search input
- Implemented focus shortcut with "Ctrl+K" and "Meta+K"
- Updated useEffect to reset searchValue based on clearSearch.params
- Refined error handling by resetting error state on option selection

Sequence Diagram

sequenceDiagram
    participant User
    participant SearchComponent
    participant InputField

    User->>SearchComponent: Press Ctrl+K or Meta+K
    SearchComponent->>InputField: Focus input field

    User->>SearchComponent: Press Escape
    alt Input not empty
        SearchComponent->>InputField: Clear input
    end

    User->>SearchComponent: Select option
    SearchComponent->>SearchComponent: Reset error state
Loading

Assessment against linked issues

Objective Addressed Explanation
Reset Input on Badge Removal [#9401]
Reintroduce Ctrl+K Shortcut [#9401]
Esc Key for Clearing Field [#9401]

Possibly related PRs

Suggested labels

needs testing, reviewed

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 A Rabbit's Search Symphony 🔍

With Ctrl+K, the cursor leaps,
Escape clears paths where data sleeps,
A search component, nimble and bright,
Shortcuts dancing with pure delight!
Code hops forward, clean and clear 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


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 Dec 15, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 8cf0b1c
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675e95f158287b0008b704f4
😎 Deploy Preview https://deploy-preview-9438--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: 1

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

Line range hint 1-283: Add test coverage for keyboard shortcuts and search clearing.

The new keyboard shortcuts and search clearing functionality should be covered by tests to ensure reliability.

Would you like me to help generate test cases for:

  1. Keyboard shortcuts (Ctrl+K, Escape, etc.)
  2. Search clearing behavior when badges are removed
  3. Error handling with different field types

This will help maintain the stability of these new features.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f82dfa8 and 8cf0b1c.

📒 Files selected for processing (1)
  • src/components/Common/SearchByMultipleFields.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Common/SearchByMultipleFields.tsx

[error] 87-87: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

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

116-123: 🛠️ Refactor suggestion

Consolidate Escape key handling and document keyboard shortcuts.

The Escape key handling is duplicated in the code. Also, keyboard shortcuts should be documented and made visible to users.

  1. Consolidate Escape key handling:
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (
        e.key === "/" &&
        !(document.activeElement instanceof HTMLInputElement)
      ) {
        e.preventDefault();
        setOpen(true);
      }
      if ((e.ctrlKey || e.metaKey) && e.key === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(false);
      }
-      if (e.key === "Escape") {
-        setSearchValue("");
-      }
      if (open) {
        if (e.key === "ArrowDown") {
          setFocusedIndex((prevIndex) =>
            prevIndex === options.length - 1 ? 0 : prevIndex + 1,
          );
        } else if (e.key === "ArrowUp") {
          setFocusedIndex((prevIndex) =>
            prevIndex === 0 ? options.length - 1 : prevIndex - 1,
          );
        } else if (e.key === "Enter") {
          handleOptionChange(focusedIndex);
        }

        if (e.key === "Escape") {
-          inputRef.current?.focus();
-          setOpen(false);
+          setSearchValue("");
+          setOpen(false);
+          inputRef.current?.focus();
        }
  1. Add keyboard shortcuts to the interface:
interface SearchByMultipleFieldsProps {
  // ... existing props
  /** Keyboard shortcuts:
   * - "/" to open search options
   * - "Ctrl+K" or "Cmd+K" to focus search input
   * - "Escape" to clear search and close options
   * - "ArrowUp/Down" to navigate options
   * - "Enter" to select option
   */
}

Consider adding a tooltip or help text to display available keyboard shortcuts to users. This would improve discoverability of these features.

Let's check for potential shortcut conflicts:

✅ Verification successful

Let me check the keyboard event handlers in these files to verify potential conflicts.


Consolidate Escape key handling and document keyboard shortcuts

The keyboard shortcuts in SearchByMultipleFields are safe to implement as suggested:

  • FilePreviewDialog only uses Arrow keys for navigation in a modal context
  • NotificationsList doesn't expose any conflicting keyboard handlers
  • The Ctrl+K/Cmd+K and Escape shortcuts are scoped appropriately and won't interfere with other components

Proceed with the suggested changes:

  1. Consolidate the Escape key handling to avoid duplication
  2. Add keyboard shortcut documentation to the component interface
  3. Consider adding a tooltip for better discoverability
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other keyboard event handlers in the codebase
rg -A 5 "useEffect.*keydown|addEventListener.*keydown"

Length of output: 1595


Script:

#!/bin/bash
# Check keyboard event handling in NotificationsList
ast-grep --pattern 'const handleKeyDown = (e: $_) => { $$$ }' src/components/Notifications/NotificationsList.tsx

# Check keyboard event handling in FilePreviewDialog
ast-grep --pattern 'const handleKeyDown = (e: $_) => { $$$ }' src/components/Common/FilePreviewDialog.tsx

Length of output: 942

Comment on lines +87 to +89
if (clearSearch?.params && clearSearch?.params.includes("search")) {
setSearchValue("");
}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 15, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor clearSearch logic for better efficiency.

The current implementation has redundant logic for clearing the search value. Let's simplify it.

  useEffect(() => {
    if (clearSearch?.value) {
-      const clearinput = options
-        .map((op) => op.key)
-        .some((element) => clearSearch.params?.includes(element));
-      clearinput ? setSearchValue("") : null;
      inputRef.current?.focus();
-      if (clearSearch?.params && clearSearch?.params.includes("search")) {
+      if (clearSearch?.params?.some(param => 
+        param === "search" || options.some(op => op.key === param)
+      )) {
        setSearchValue("");
      }
    }
  }, [clearSearch]);
📝 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.

Suggested change
if (clearSearch?.params && clearSearch?.params.includes("search")) {
setSearchValue("");
}
useEffect(() => {
if (clearSearch?.value) {
inputRef.current?.focus();
if (clearSearch?.params?.some(param =>
param === "search" || options.some(op => op.key === param)
)) {
setSearchValue("");
}
}
}, [clearSearch]);
🧰 Tools
🪛 Biome (1.9.4)

[error] 87-87: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Copy link
Contributor

Choose a reason for hiding this comment

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

Try this implement @noufalrahim

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

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

Successfully merging this pull request may close these issues.

Improve Facility & Phone number Search Field Reset and Dynamic Shortcut Hints for new search component
2 participants