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 tooltip race condition #5030

Merged
merged 2 commits into from
Nov 2, 2024
Merged

fix tooltip race condition #5030

merged 2 commits into from
Nov 2, 2024

Conversation

sashankaryal
Copy link
Contributor

@sashankaryal sashankaryal commented Nov 1, 2024

What changes are proposed in this pull request?

Fixes a race condition relating to tooltip

How is this patch tested? If it is not, please explain why.

Smoke test locally.

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • New Features
    • Introduced a new hook for managing tooltip events, enhancing user interaction with tooltips.
  • Improvements
    • Enhanced keyboard event handling for better navigation and sidebar visibility.
    • Streamlined modal component by removing unused tooltip functionality.
  • Refactor
    • Updated prop names in modal components for clarity and consistency.
    • Simplified the modal context structure by removing unnecessary properties.

@sashankaryal sashankaryal self-assigned this Nov 1, 2024
Copy link
Contributor

coderabbitai bot commented Nov 1, 2024

Walkthrough

The changes in this pull request primarily affect the Modal component and its associated files, focusing on enhancing event handling and simplifying the structure. Key modifications include renaming the onNavigate prop to closePanels, updating event listener management for tooltips, and removing unused tooltip-related functionality from the ModalSamplePlugin. Additionally, a new hook for managing tooltip events is introduced, and the context structure is simplified by removing a subscriber mechanism.

Changes

File Path Change Summary
app/packages/core/src/components/Modal/Modal.tsx - Added import for useTooltipEventHandler.
- Replaced onNavigate with closePanels.
- Updated modalCloseHandler and keysHandler functions.
- Introduced addTooltipEventHandler and updated onLookerSet.
app/packages/core/src/components/Modal/ModalNavigation.tsx - Changed prop from onNavigate to closePanels.
- Updated nextNavigator and previousNavigator to use closePanels.
app/packages/core/src/components/Modal/ModalSamplePlugin.tsx - Removed tooltip-related functionality, including imports and event handlers.
- Simplified lifecycle management in useEffect.
app/packages/core/src/components/Modal/hooks.ts - Renamed onNavigate to closePanels.
- Added useTooltipEventHandler for managing tooltip events.
app/packages/core/src/components/Modal/modal-context.ts - Removed onLookerSetSubscribers from ModalContextT interface.

Possibly related PRs

Suggested labels

bug, app

Suggested reviewers

  • imanjra

🐇 In the modal, we play and hop,
With tooltips gone, we’ll never stop!
Close the panels, hear the cheer,
A cleaner code, let’s give a cheer!
With events in line, we dance and sway,
Hooray for changes, hip-hip-hooray! 🎉


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
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 and nitpick comments (2)
app/packages/core/src/components/Modal/ModalSamplePlugin.tsx (1)

Line range hint 31-39: Consider combining tooltip state resets

While the cleanup is good, consider combining both tooltip state resets for better consistency.

  useEffect(() => {
    // reset tooltip state when modal is closed
    setIsTooltipLocked(false);
+   setTooltipDetail(null);

    return () => {
-     setTooltipDetail(null);
+     setIsTooltipLocked(false);
+     setTooltipDetail(null);
    };
  }, []);

This ensures both states are reset together, both on mount and cleanup, preventing any potential race conditions if the component unmounts during state updates.

app/packages/core/src/components/Modal/Modal.tsx (1)

190-193: Optimize event listener cleanup with optional chaining.

The current null check can be simplified using optional chaining.

-      removeTooltipEventHanlderRef.current &&
-        removeTooltipEventHanlderRef.current();
+      removeTooltipEventHanlderRef.current?.();
🧰 Tools
🪛 Biome

[error] 191-192: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7b4e735 and 02fc70b.

📒 Files selected for processing (5)
  • app/packages/core/src/components/Modal/Modal.tsx (4 hunks)
  • app/packages/core/src/components/Modal/ModalNavigation.tsx (2 hunks)
  • app/packages/core/src/components/Modal/ModalSamplePlugin.tsx (1 hunks)
  • app/packages/core/src/components/Modal/hooks.ts (2 hunks)
  • app/packages/core/src/components/Modal/modal-context.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • app/packages/core/src/components/Modal/modal-context.ts
🧰 Additional context used
📓 Path-based instructions (4)
app/packages/core/src/components/Modal/Modal.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/components/Modal/ModalNavigation.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/components/Modal/ModalSamplePlugin.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/components/Modal/hooks.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🪛 Biome
app/packages/core/src/components/Modal/Modal.tsx

[error] 191-192: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (11)
app/packages/core/src/components/Modal/ModalSamplePlugin.tsx (1)

3-4: LGTM! Clean removal of tooltip-related imports

The removal of useModalContext and simplified imports align well with the centralization of tooltip handling in Modal.tsx, helping to prevent race conditions.

app/packages/core/src/components/Modal/hooks.ts (2)

19-27: Well-implemented panel closure logic with proper ref handling!

The renaming from onNavigate to closePanels better reflects the function's purpose, and the use of refs properly handles the referential stability of the panel instances.


82-102: Effective race condition fix with atomic state updates!

The implementation properly handles the tooltip race condition by:

  • Using Recoil's atomic state updates
  • Checking tooltip lock status before updating coordinates
  • Properly managing tooltip state through a centralized handler
app/packages/core/src/components/Modal/ModalNavigation.tsx (4)

47-47: LGTM! Prop rename improves clarity.

The rename from onNavigate to closePanels better reflects the actual purpose of the callback, making the code more maintainable.


78-81: LGTM! Consistent navigation handling.

The nextNavigator implementation correctly calls closePanels before navigation starts, which should help prevent the tooltip race condition. The debouncing mechanism (150ms) will also help prevent rapid navigation issues.


89-92: LGTM! Symmetric implementation.

The previousNavigator implementation mirrors the nextNavigator, ensuring consistent behavior in both directions.


Line range hint 47-92: Verify tooltip race condition fix.

The changes look good and should address the tooltip race condition by ensuring panels are closed before navigation starts. Let's verify there are no other tooltip-related issues in the codebase.

✅ Verification successful

Based on the search results, I can now provide a definitive response about the tooltip race condition fix:

The tooltip race condition fix has been properly implemented and verified.

The code shows a robust implementation where:

  1. The closePanels function is properly integrated into the debounced navigation system via onNavigationStart callback
  2. The tooltip state is managed through a comprehensive system of atoms and selectors
  3. The tooltip cleanup is handled both in the navigation flow and when the modal is closed
  4. The debouncing mechanism includes proper cleanup and state management to prevent race conditions

Key evidence:

  • The createDebouncedNavigator ensures panels are closed before navigation starts through the onNavigationStart: closePanels callback
  • Tooltip state is properly managed through isTooltipLocked, tooltipCoordinates, and tooltipDetail atoms
  • The implementation includes proper event handling and cleanup for tooltip state
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tooltip-related race conditions or similar patterns
# Look for tooltip-related components and their cleanup
rg -g '*.{ts,tsx}' -i 'tooltip.*unmount|tooltip.*cleanup|tooltip.*effect' 

# Look for similar panel closing patterns that might need the same fix
ast-grep --pattern 'onNavigate($$$)' 

Length of output: 114


Script:

#!/bin/bash
# Search for tooltip components and their usage
rg -g '*.{ts,tsx}' -i 'tooltip' -A 5 -B 5

# Look for navigation-related components that might have similar patterns
rg -g '*.{ts,tsx}' 'createDebouncedNavigator|onNavigationStart' -A 5 -B 5

# Search for panel closing patterns
ast-grep --pattern 'closePanels($$$)'

Length of output: 238277

app/packages/core/src/components/Modal/Modal.tsx (4)

4-4: LGTM: Import changes align with new tooltip handling requirements.

The addition of useRef and useTooltipEventHandler imports supports the new tooltip event handling mechanism.

Also applies to: 10-10


181-196: LGTM: Proper event listener cleanup prevents memory leaks and race conditions.

The implementation correctly manages tooltip event listeners by:

  1. Storing the cleanup function in a ref
  2. Cleaning up previous listeners before adding new ones
  3. Using useCallback to maintain reference stability
🧰 Tools
🪛 Biome

[error] 191-192: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


222-222: LGTM: Prop rename improves code clarity.

Renaming onNavigate to closePanels better describes the function's purpose and follows React naming conventions.


186-196: Verify race condition fix effectiveness.

The implementation addresses tooltip race conditions through:

  1. Proper cleanup of previous event listeners before adding new ones
  2. Stable function references with useCallback
  3. Ref-based state tracking

However, let's verify there are no remaining race conditions in tooltip handling across the codebase.

✅ Verification successful

Race condition fix is properly implemented

The implementation effectively prevents tooltip-related race conditions through:

  1. Proper cleanup using removeTooltipEventHanlderRef to track and remove previous event listeners before adding new ones
  2. Stable function references with useCallback for both onLookerSet and setActiveLookerRef
  3. Proper event listener cleanup sequence in onLookerSet:
    • Remove previous tooltip event listener if it exists
    • Add new event listener
    • Store cleanup function for next update

The code follows React best practices for event listener management and race condition prevention.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other tooltip-related event listeners that might need similar race condition fixes
rg -l "addEventListener.*tooltip" --type ts --type tsx

# Search for potential tooltip-related cleanup patterns
rg -l "removeEventListener.*tooltip" --type ts --type tsx

Length of output: 172


Script:

#!/bin/bash
# Search for tooltip-related event listeners with correct file type flags
rg -l "addEventListener.*tooltip" -t typescript -t tsx

# Search for tooltip-related cleanup patterns
rg -l "removeEventListener.*tooltip" -t typescript -t tsx

# Search for tooltip event handler references
rg -l "TooltipEventHan[dl]" -t typescript -t tsx

# Look for similar race condition prevention patterns
ast-grep --pattern 'useCallback($$$, [$$$])'

Length of output: 260223


Script:

#!/bin/bash
# Search for tooltip-related event listeners and handlers
rg -A 5 "tooltip.*event.*handler" -t js -t jsx -t ts -t tsx

# Search for tooltip-related race condition fixes
rg -A 5 "removeTooltipEventHan[dl].*current" -t js -t jsx -t ts -t tsx

# Search for tooltip-related cleanup patterns
rg -A 5 "removeEventListener.*tooltip" -t js -t jsx -t ts -t tsx

Length of output: 285


Script:

#!/bin/bash
# Search for tooltip event handlers and cleanup patterns
rg -l "tooltip.*event.*handler|removeTooltipEventHan[dl]|removeEventListener.*tooltip"

# Look for race condition prevention patterns in Modal.tsx
rg -A 5 "removeTooltipEventHanlderRef" app/packages/core/src/components/Modal/Modal.tsx

# Search for tooltip-related useCallback hooks
ast-grep --pattern 'useCallback($$$, [$$$])' app/packages/core/src/components/Modal/Modal.tsx

Length of output: 2901

🧰 Tools
🪛 Biome

[error] 191-192: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +104 to +114
return useCallback(
(looker: fos.Lookers) => {
looker.removeEventListener("tooltip", tooltipEventHandler);
looker.addEventListener("tooltip", tooltipEventHandler);

return () => {
looker.removeEventListener("tooltip", tooltipEventHandler);
};
},
[tooltipEventHandler]
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider optimizing event listener cleanup pattern

The current implementation removes and adds the event listener on every call. This could be simplified to avoid unnecessary DOM operations.

Consider this alternative implementation:

  return useCallback(
    (looker: fos.Lookers) => {
-     looker.removeEventListener("tooltip", tooltipEventHandler);
      looker.addEventListener("tooltip", tooltipEventHandler);

      return () => {
        looker.removeEventListener("tooltip", tooltipEventHandler);
      };
    },
    [tooltipEventHandler]
  );

This change:

  • Removes the redundant initial removeEventListener call
  • Still maintains proper cleanup through the returned cleanup function
  • Reduces unnecessary DOM operations
📝 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
return useCallback(
(looker: fos.Lookers) => {
looker.removeEventListener("tooltip", tooltipEventHandler);
looker.addEventListener("tooltip", tooltipEventHandler);
return () => {
looker.removeEventListener("tooltip", tooltipEventHandler);
};
},
[tooltipEventHandler]
);
return useCallback(
(looker: fos.Lookers) => {
looker.addEventListener("tooltip", tooltipEventHandler);
return () => {
looker.removeEventListener("tooltip", tooltipEventHandler);
};
},
[tooltipEventHandler]
);

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)
app/packages/core/src/components/Modal/Modal.tsx (1)

181-184: Fix typo in ref name

The implementation is correct, but there's a typo in the ref name: removeTooltipEventHanlderRef should be removeTooltipEventHandlerRef (missing 'd' in 'Handler').

-  const removeTooltipEventHanlderRef = useRef<ReturnType<
+  const removeTooltipEventHandlerRef = useRef<ReturnType<
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02fc70b and 706c53e.

📒 Files selected for processing (1)
  • app/packages/core/src/components/Modal/Modal.tsx (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
app/packages/core/src/components/Modal/Modal.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (4)
app/packages/core/src/components/Modal/Modal.tsx (4)

4-4: LGTM: Import changes align with tooltip handling requirements

The addition of useTooltipEventHandler and reorganization of imports support the tooltip race condition fix.

Also applies to: 13-14


160-161: LGTM: Improved modal close handling with proper cleanup

The changes properly handle event listener cleanup and add a safeguard for the Escape key handling, which helps prevent race conditions.


186-195: LGTM: Robust tooltip event handling implementation

The implementation effectively prevents tooltip race conditions by:

  • Cleaning up previous event listeners before adding new ones
  • Properly managing cleanup functions with refs
  • Using correct React hooks patterns with appropriate dependencies

221-221: LGTM: Improved prop naming

The rename from onNavigate to closePanels better describes the prop's purpose and maintains consistency with the broader refactoring.

Copy link
Contributor

@benjaminpkane benjaminpkane left a comment

Choose a reason for hiding this comment

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

LGTM 🚀

@benjaminpkane benjaminpkane merged commit e54c7a7 into release/v1.0.2 Nov 2, 2024
11 checks passed
@benjaminpkane benjaminpkane deleted the fix/tooltip branch November 2, 2024 00:48
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.

2 participants