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

Spotlight cleanup #5015

Merged
merged 12 commits into from
Nov 1, 2024
Merged

Conversation

benjaminpkane
Copy link
Contributor

@benjaminpkane benjaminpkane commented Oct 30, 2024

What changes are proposed in this pull request?

Adds event listener cleanup to Spotlight. Also adds destroy as an optional config for item cleanup, e.g. a Looker instance

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 destroy method in the Row and Section classes for improved resource management.
    • Added an optional destroy method to the SpotlightConfig interface.
  • Improvements

    • Enhanced event handling with named functions for clarity.
    • Streamlined cleanup processes in the Spotlight class.
    • Improved lifecycle management of Section instances to ensure proper resource release.

@benjaminpkane benjaminpkane self-assigned this Oct 30, 2024
Copy link
Contributor

coderabbitai bot commented Oct 30, 2024

Walkthrough

The pull request introduces several modifications across multiple files in the spotlight package. Key changes include refactoring event handling in the createScrollReader function to use named functions, enhancing the cleanup process in the Spotlight class by replacing remove() calls with destroy(), and adding a new destroy() method in both the Row and Section classes for better resource management. Additionally, the SpotlightConfig interface has been updated to include an optional destroy method. These changes collectively aim to improve code clarity and resource management.

Changes

File Path Change Summary
app/packages/spotlight/src/createScrollReader.ts Refactored scroll event handling to use named functions; updated destroy method for cleanup.
app/packages/spotlight/src/index.ts Updated destroy method to replace remove() calls with destroy() for backward and forward sections.
app/packages/spotlight/src/row.ts Added private member #aborter for event handling; introduced destroy() method for resource cleanup; modified hide() method.
app/packages/spotlight/src/section.ts Added destroy() method for section cleanup; removed remove() method; streamlined render logic.
app/packages/spotlight/src/types.ts Updated SpotlightConfig interface to include optional destroy method.

Possibly related PRs

  • don't throw in spotlight.destroy() #5017: The changes in the destroy method of the Spotlight class in both the main PR and this retrieved PR relate to enhancing the cleanup process, with the retrieved PR focusing on error handling improvements in the same method.

🐇 In the spotlight, changes abound,
With named functions, clarity found.
A destroy method here and there,
Cleanup's a breeze, without a care.
For rows and sections, all is neat,
In this code, we hop to our beat! 🐇


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.

@benjaminpkane benjaminpkane marked this pull request as ready for review October 31, 2024 15:15
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: 4

🧹 Outside diff range and nitpick comments (5)
app/packages/spotlight/src/types.ts (1)

60-60: Consider adding JSDoc documentation for the destroy method.

Adding documentation would help clarify:

  • When the destroy method is called
  • Whether it should be idempotent
  • What resources it's expected to clean up

Example documentation:

+/**
+ * Cleanup resources associated with an item
+ * @param id The ID of the item to cleanup
+ */
 destroy?: (id: ID) => void;
app/packages/spotlight/src/row.ts (1)

Line range hint 51-63: Add proper TypeScript event typing

The event parameter should be properly typed for better type safety.

-        const handler = (event) => {
+        const handler = (event: MouseEvent) => {
app/packages/spotlight/src/section.ts (1)

111-115: Consider adding safeguards against post-destruction usage.

The current destroy implementation could benefit from additional architectural safeguards:

  1. Add a destroyed flag to prevent reuse of destroyed instances:
 class Section<K, V> {
+  #destroyed = false;
+
   destroy() {
+    if (this.#destroyed) return;
+    this.#destroyed = true;
     this.#section.remove();
     // ... rest of destroy implementation
   }
+
+  #assertNotDestroyed() {
+    if (this.#destroyed) {
+      throw new Error('Section has been destroyed');
+    }
+  }
 }
  1. Add checks in key methods:
render(...) {
  this.#assertNotDestroyed();
  // ... existing implementation
}

next(...) {
  this.#assertNotDestroyed();
  // ... existing implementation
}

This ensures:

  1. Safe cleanup by preventing multiple destroy calls
  2. Early detection of usage after destruction
  3. Clear error messages for debugging
app/packages/spotlight/src/index.ts (2)

111-112: LGTM: Improved cleanup with proper null checks.

The change from remove() to destroy() aligns with the PR's cleanup objectives. The optional chaining operator (?.) properly handles potential null references.

Consider adding a comment explaining the cleanup sequence, especially since this is a critical cleanup method:

  destroy(): void {
    if (!this.attached) {
      console.error("spotlight is not attached");
      return;
    }

+   // Clean up sections before removing the element
    this.#backward?.destroy();
    this.#forward?.destroy();

275-275: LGTM: Consistent cleanup in backward navigation.

The change to destroy() maintains consistency with the new cleanup pattern while properly handling section swapping during backward navigation.

Consider adding error handling for the destroy operation:

-              this.#forward.destroy();
+              try {
+                this.#forward.destroy();
+              } catch (error) {
+                console.error('Failed to destroy forward section:', error);
+                // Continue with section swap despite cleanup failure
+              }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5922bcd and 33a0040.

📒 Files selected for processing (5)
  • app/packages/spotlight/src/createScrollReader.ts (2 hunks)
  • app/packages/spotlight/src/index.ts (4 hunks)
  • app/packages/spotlight/src/row.ts (5 hunks)
  • app/packages/spotlight/src/section.ts (1 hunks)
  • app/packages/spotlight/src/types.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
app/packages/spotlight/src/createScrollReader.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.

app/packages/spotlight/src/index.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.

app/packages/spotlight/src/row.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.

app/packages/spotlight/src/section.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.

app/packages/spotlight/src/types.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.

🔇 Additional comments (9)
app/packages/spotlight/src/types.ts (1)

60-61: LGTM! The destroy method is a good addition for resource cleanup.

The optional destroy method is well-typed and integrates cleanly with the existing interface structure.

app/packages/spotlight/src/createScrollReader.ts (4)

18-20: LGTM! Clean extraction of scroll handler.

The named function improves code readability and maintains the same functionality.


23-26: LGTM! Well-structured scrollEnd handler.

The named function improves maintainability while correctly handling the scroll end state and render scheduling.


74-75: LGTM! Comprehensive event listener cleanup.

The destroy method now properly removes both event listeners using the named function references, preventing potential memory leaks.


77-77: LGTM! Proper TypeScript style.

The addition of a trailing comma follows TypeScript best practices and improves git diff readability for future changes.

app/packages/spotlight/src/row.ts (2)

16-16: LGTM: Good use of AbortController for event listener cleanup

The addition of #aborter follows TypeScript best practices for managing event listener lifecycles.


65-69: Verify shared handler for click and contextmenu events

The same handler is used for both click and contextmenu events. Please verify if this is intentional and if both events should trigger the same onItemClick behavior.

✅ Verification successful

Let me check the handler implementation and its usage to better understand the behavior.


Let me check the implementation in the flashlight package for comparison.


Shared handler for click and contextmenu events is intentional and correct

The shared handler implementation is consistent across both packages (spotlight and flashlight). In both cases:

  • Both events trigger the same item click behavior
  • Both handlers prevent default event behavior when needed
  • Both implementations check for modifier keys (meta/shift) or call the click handler directly
  • This pattern ensures consistent behavior for both left-click and right-click interactions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other contextmenu handlers in the codebase to verify consistent behavior
rg -A 5 "addEventListener.*contextmenu"

Length of output: 829


Script:

#!/bin/bash
# Get the full context of the row.ts file to understand the handler implementation
cat app/packages/spotlight/src/row.ts

Length of output: 5493


Script:

#!/bin/bash
# Get the full context of the section.ts file to understand its handler implementation
cat app/packages/flashlight/src/section.ts

Length of output: 6666

app/packages/spotlight/src/section.ts (1)

111-115: Verify event listener cleanup.

The destroy method removes DOM elements but doesn't explicitly handle event listener cleanup. Let's verify if there are any event listeners that need cleanup:

If event listeners are found, they should be properly cleaned up in the destroy method.

app/packages/spotlight/src/index.ts (1)

21-21: LGTM: Constant import addition is correct.

The ZOOMING_COEFFICIENT constant is properly imported and utilized in the zoom calculation logic.

app/packages/spotlight/src/row.ts Outdated Show resolved Hide resolved
app/packages/spotlight/src/row.ts Outdated Show resolved Hide resolved
app/packages/spotlight/src/section.ts Show resolved Hide resolved
app/packages/spotlight/src/index.ts Show resolved Hide resolved
Copy link
Contributor

@tom-vx51 tom-vx51 left a comment

Choose a reason for hiding this comment

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

lgtm 🚀

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/spotlight/src/row.ts (1)

Line range hint 51-69: Consider adding TypeScript types for the event parameter.

The event handler implementation looks good with proper key checks and prevention of default behavior. However, the event parameter could benefit from explicit typing.

-        const handler = (event) => {
+        const handler = (event: MouseEvent) => {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 33a0040 and fbc57eb.

📒 Files selected for processing (1)
  • app/packages/spotlight/src/row.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
app/packages/spotlight/src/row.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.

📓 Learnings (1)
app/packages/spotlight/src/row.ts (1)
Learnt from: tom-vx51
PR: voxel51/fiftyone#5015
File: app/packages/spotlight/src/row.ts:122-125
Timestamp: 2024-10-31T16:22:03.523Z
Learning: In the `Row` class of `app/packages/spotlight/src/row.ts`, ensure that the `destroy` method includes error handling to prevent memory leaks due to cleanup errors.
🔇 Additional comments (4)
app/packages/spotlight/src/row.ts (4)

16-16: LGTM: Good use of AbortController for event listener cleanup.

The addition of a readonly AbortController field provides a clean way to manage event listener lifecycles.


122-125: LGTM: Clean implementation of the destroy method.

The method properly handles cleanup by first destroying items and then aborting event listeners.


142-142: Duplicate cleanup concern already addressed in previous review.


231-249: LGTM: Robust implementation with proper error handling.

The implementation includes:

  • Null check for optional destroy method
  • Try-catch blocks to prevent cleanup interruption
  • Error aggregation and logging

This aligns well with the previous feedback about preventing memory leaks.

Copy link
Contributor

@ritch ritch left a comment

Choose a reason for hiding this comment

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

Tooltip is not being displayed. It is on dev.fiftyone.ai.

@ritch ritch self-requested a review October 31, 2024 20:32
@benjaminpkane benjaminpkane merged commit 7b4e735 into release/v1.0.2 Nov 1, 2024
11 checks passed
@benjaminpkane benjaminpkane deleted the bugfix/spotlight-event-listeners branch November 1, 2024 15:17
@coderabbitai coderabbitai bot mentioned this pull request Nov 20, 2024
5 tasks
@coderabbitai coderabbitai bot mentioned this pull request Dec 2, 2024
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.

4 participants