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: Searchbar results. Added pre push tests. #1329

Merged
merged 3 commits into from
Nov 7, 2024
Merged

Conversation

alexdigdir
Copy link
Contributor

@alexdigdir alexdigdir commented Nov 1, 2024

  • Searchbar results will now only reflect hits related to selected party.
  • Added pre push hook, running Playwright tests and Typescript checks.

Hva er endret?

Dokumentasjon / Storybook / testdekning

  • Dokumentasjon er oppdatert eller ikke relevant / nødvendig.
  • Ny komponent har en eller flere stories i Storybook, eller så er ikke dette relevant.
  • Det er blitt lagt til nye tester / eksiterende tester er blitt utvidet, eller tester er ikke relevant.

Skjermbilder eller GIFs (valgfritt)

Summary by CodeRabbit

  • New Features

    • Enhanced search functionality to consider only selected parties in the search dialog.
    • Improved responsiveness of search results based on changes in party and organization data.
  • Bug Fixes

    • Refined internal state management for party selection in the search dropdown.

@alexdigdir alexdigdir requested a review from a team as a code owner November 1, 2024 09:12
Copy link

coderabbitai bot commented Nov 1, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the useEffect hook in the useDialogs API and updates the SearchDropdown component to utilize selectedParties instead of parties. The dependency array of the useEffect now includes parties and organizations, enhancing the effect's responsiveness to changes in these variables. The SearchDropdown component's data flow is altered to ensure that only selected parties are considered in the search process, while the overall structure and rendering logic remain unchanged.

Changes

File Change Summary
packages/frontend/src/api/useDialogs.tsx Updated the dependency array of the useEffect hook in useSearchDialogs to include parties and organizations.
packages/frontend/src/components/Header/SearchDropdown.tsx Changed the data retrieval from useParties to selectedParties, affecting the argument passed to useSearchDialogs.

Possibly related PRs

Suggested labels

dev

Suggested reviewers

  • seanes

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f0f392e and 9668b9c.

📒 Files selected for processing (1)
  • packages/frontend/src/components/Header/SearchDropdown.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/frontend/src/components/Header/SearchDropdown.tsx

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 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.

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

@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 (4)
.husky/pre-push (2)

1-7: Add error handling and exit code checks.

While the basic structure is good, the script needs to be more robust to prevent pushes when tests or type checking fail.

Here's a more resilient implementation:

 #!/bin/bash
+set -eo pipefail
+
+# Check if pnpm is available
+if ! command -v pnpm &> /dev/null; then
+    echo "Error: pnpm is not installed"
+    exit 1
+fi
+
+# Verify frontend workspace exists
+if ! pnpm --filter frontend ls &> /dev/null; then
+    echo "Error: frontend workspace not found"
+    exit 1
+fi
+
 echo "### Running pre-push hook ### "
+
 echo "Running Playwright tests..."
-pnpm --filter frontend test:playwright
+if ! pnpm --filter frontend test:playwright; then
+    echo "Error: Playwright tests failed"
+    exit 1
+fi
+
 echo "Running typechecking..."
-pnpm --filter frontend typecheck
+if ! pnpm --filter frontend typecheck; then
+    echo "Error: Type checking failed"
+    exit 1
+fi
+
 echo "Done. Will now push to origin."
+exit 0

Changes include:

  • Added error handling for command availability and workspace existence
  • Added proper exit code checking for each command
  • Added set -eo pipefail for stricter error handling
  • Added explicit successful exit

4-4: Consider adding timeout limits for long-running operations.

The Playwright tests and type checking operations could potentially hang. Consider adding timeout limits to prevent indefinite waiting.

Example implementation:

# Function to run command with timeout
run_with_timeout() {
    timeout 5m "$@"
    return $?
}

# Usage
run_with_timeout pnpm --filter frontend test:playwright

Also applies to: 6-6

packages/frontend/src/components/Header/SearchDropdown.tsx (1)

Line range hint 55-71: Consider performance and maintainability improvements.

A few suggestions to enhance the code:

  1. Consider memoizing the search results rendering to prevent unnecessary re-renders
  2. Extract the magic number 5 in slice(0, 5) to a named constant

Here's how you could implement these improvements:

+const MAX_SEARCH_RESULTS = 5;
+const MemoizedSearchResults = React.memo(({ results, onClose, formatDistance }) => (
+  results.slice(0, MAX_SEARCH_RESULTS).map((item) => (
+    <SearchDropdownItem key={item.id}>
+      <InboxItem
+        key={item.id}
+        checkboxValue={item.id}
+        title={item.title}
+        summary={item.summary}
+        sender={item.sender}
+        receiver={item.receiver}
+        metaFields={item.metaFields}
+        linkTo={item.linkTo}
+        onClose={onClose}
+        isUnread={!item.isSeenByEndUser}
+        isMinimalistic
+      />
+      <div className={cx(styles.rightContent)}>
+        <span className={styles.timeSince}>
+          {autoFormatRelativeTime(new Date(item.updatedAt), formatDistance)}
+        </span>
+        <Avatar
+          name={item.sender.name}
+          profile={item.sender.isCompany ? 'organization' : 'person'}
+          imageUrl={item.sender.imageURL}
+          size="small"
+        />
+      </div>
+    </SearchDropdownItem>
+  ))
+));

 {/* Search results: */}
 {isFetching ? (
   <SearchDropdownSkeleton numberOfItems={3} />
 ) : (
-  searchResults?.slice(0, 5).map((item) => (
-    <SearchDropdownItem key={item.id}>
-      ...
-    </SearchDropdownItem>
-  ))
+  <MemoizedSearchResults 
+    results={searchResults ?? []}
+    onClose={handleClose}
+    formatDistance={formatDistance}
+  />
 )}
packages/frontend/src/api/useDialogs.tsx (1)

117-117: Consider removing the lint ignore comment.

The added dependencies parties and organizations are correctly included as they are used within the effect's callback. Since all dependencies are now properly declared, the lint ignore comment biome-ignore lint/correctness/useExhaustiveDependencies appears unnecessary.

Apply this diff to remove the unnecessary comment:

-  // biome-ignore lint/correctness/useExhaustiveDependencies: Full control of what triggers this code is needed
  useEffect(() => {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 935f0ab and f0f392e.

📒 Files selected for processing (3)
  • .husky/pre-push (1 hunks)
  • packages/frontend/src/api/useDialogs.tsx (1 hunks)
  • packages/frontend/src/components/Header/SearchDropdown.tsx (1 hunks)
🔇 Additional comments (4)
.husky/pre-push (1)

1-7: Verify the hook's execution permissions.

Ensure the script has the correct execution permissions set.

✅ Verification successful

Pre-push hook has correct execution permissions

The file .husky/pre-push has the required executable permissions set (rwx), allowing it to run properly during git push operations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the pre-push hook has correct permissions

# Test: Check if the file is executable
ls -l .husky/pre-push | grep -q "^-rwx" && echo "Permissions OK" || echo "Missing execute permission"

Length of output: 80

packages/frontend/src/components/Header/SearchDropdown.tsx (1)

27-31: LGTM! The changes align with the PR objectives.

The modification to use selectedParties instead of parties correctly implements the requirement to filter search results based on the selected party.

Let's verify the implementation of useSearchDialogs to ensure it properly handles the parties parameter:

✅ Verification successful

The useSearchDialogs hook correctly utilizes the parties parameter

The implementation confirms that the parties parameter is properly used in the hook:

  • It maps the party URIs from the provided parties array (partyURIs = parties.map((party) => party.party))
  • Uses these URIs in the query key and query function for fetching dialogs (queryKey, searchDialogs(partyURIs, ...))
  • Applies the parties data when mapping dialog DTOs to inbox items (mapDialogDtoToInboxItem(..., parties, ...))
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the useSearchDialogs implementation
# Expected: The hook should use the parties parameter in its query/filter logic

# Search for the useSearchDialogs implementation
ast-grep --pattern 'export const useSearchDialogs = $_'

Length of output: 2349

packages/frontend/src/api/useDialogs.tsx (2)

117-117: Changes align well with PR objectives.

The addition of parties and organizations to the dependency array ensures that search results are properly filtered based on the selected party, which directly addresses the PR's goal of enhancing searchbar functionality.


117-117: Verify potential performance impact.

The addition of parties and organizations to the dependency array is correct and aligns with the PR's objective to filter search results by selected party. However, frequent updates to these dependencies could trigger unnecessary re-renders.

Let's analyze the update frequency of these dependencies:

✅ Verification successful

Based on the search results, I can now provide a conclusive response about the performance concerns:

Performance impact is minimal - dependencies have low update frequency

The codebase analysis shows that both parties and organizations are stable dependencies:

  • parties is primarily set through user selection via setSelectedParties
  • organizations is fetched once and cached (with 24h Redis TTL on backend)
  • Both are used for filtering search results, which is the intended behavior

The re-renders triggered by these dependencies are necessary for correct functionality and don't pose a performance concern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how often parties and organizations are updated
# Look for state updates or API calls that modify these values

# Search for parties/organizations state updates
echo "Searching for parties state updates..."
rg -A 3 "setParties|parties\s*=|parties:" --type typescript

echo "Searching for organizations state updates..."
rg -A 3 "setOrganizations|organizations\s*=|organizations:" --type typescript

# Look for related API calls
echo "Searching for API endpoints that might update these values..."
rg -A 3 "useQuery.*parties|useQuery.*organizations" --type typescript

Length of output: 637


Script:

#!/bin/bash
# Let's try without typescript file type specification
echo "Searching for parties state updates..."
rg -A 3 "setParties|parties\s*=|parties:"

echo "Searching for organizations state updates..."
rg -A 3 "setOrganizations|organizations\s*=|organizations:"

echo "Searching for API endpoints that might update these values..."
rg -A 3 "useQuery.*parties|useQuery.*organizations"

# Also search for the context where these dependencies are used
echo "Searching for the component using these dependencies..."
rg -A 10 -B 10 "\[setSearchResults, data\?\?\.searchDialogs\?\?.items, enabled, parties, organizations\]"

Length of output: 15627

Copy link
Contributor

@seanes seanes left a comment

Choose a reason for hiding this comment

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

Why should we add pre push hook when we already have a hook for this on pre commit? I don't want to run all these operations on all frontend files when I run a commit. Only on stages files, and not only for frontend.

@alexdigdir
Copy link
Contributor Author

alexdigdir commented Nov 4, 2024

Why should we add pre push hook when we already have a hook for this on pre commit? I don't want to run all these operations on all frontend files when I run a commit. Only on stages files, and not only for frontend.

I was not aware of an already existing pre-commit hook that does this, only (optional) pre-commit hook I can find runs pnpm lint-staged -- --color only.

The tests in this PR are already only running on frontend, running tests in the /packages/frontend/tests folder:
`echo "Running Playwright tests..."

pnpm --filter frontend test:playwright

echo "Running typechecking..."

pnpm --filter frontend typecheck`

But I guess everything has to be 100% how you want it or it will never get merged to main, so I will remove all hooks and update PR.

@seanes
Copy link
Contributor

seanes commented Nov 4, 2024

But combining a bug fix with a change to a developer experience (Added pre push hook, running Playwright tests and Typescript checks) without having discussed the problem, is probably not optimal, don't you agree?

We should definitely find an agreement what suits best for all devs in the team, and I think it's better to address this in a separate issue / pull request.

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

Successfully merging this pull request may close these issues.

Søk i innboks gir feilaktig treff på tvers av innbokser
2 participants