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

Add PillBadgeView to Python Panels #4909

Merged
merged 13 commits into from
Oct 10, 2024
Merged

Add PillBadgeView to Python Panels #4909

merged 13 commits into from
Oct 10, 2024

Conversation

Br2850
Copy link
Contributor

@Br2850 Br2850 commented Oct 10, 2024

Adds a PillBadgeView to Python Panels which is a MuiChip component capable of rendering itself as a dropdown menu of options, color-coded or not (if desired). The indicator icon is also optional and can be enabled or removed with a showIcon flag

Screen.Recording.2024-10-10.at.12.54.39.AM.mov
Screenshot 2024-10-10 at 12 38 22 AM
Screen.Recording.2024-10-10.at.12.37.11.AM.mov

Summary by CodeRabbit

  • New Features

    • Introduced the PillBadge component for displaying customizable pill-shaped badges.
    • Added the PillBadgeView component to render PillBadge within a structured layout.
  • Bug Fixes

    • Updated the persistence property in tests for correct dataset configuration.
  • Documentation

    • Exported new components for easier access in other modules.

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Walkthrough

The changes introduce a new React component named PillBadge, which allows for customizable properties such as text, color, variant, and showIcon. Additionally, a related component called PillBadgeView is created to render PillBadge within a Material-UI Box. The changes also include updates to export statements for both components and modifications to existing functions and classes in other files, enhancing their functionality and output structure.

Changes

File Path Change Summary
app/packages/components/src/components/PillBadge/PillBadge.tsx New component PillBadge added, managing state and rendering based on text prop type.
app/packages/components/src/components/PillBadge/index.ts Export statement added for PillBadge.
app/packages/core/src/plugins/SchemaIO/components/PillBadgeView.tsx New component PillBadgeView added, rendering PillBadge with props from schema.view.
app/packages/core/src/plugins/SchemaIO/components/index.ts Export statement added for PillBadgeView.
app/packages/core/src/components/Modal/use-looker.ts Modified useLooker function to update looker.updateSample with sample.sample.
e2e-pw/src/oss/specs/sidebar/frame-filtering.spec.ts Updated dataset property from dataset.persist to dataset.persistent in tests.
fiftyone/operators/types.py New class PillBadgeView added, inheriting from ReadOnlyView.
fiftyone/utils/sam.py Updated _forward_pass_boxes and _forward_pass_points methods to include scores in output.
fiftyone/utils/sam2.py Updated _forward_pass_boxes method to include scores in output.

Possibly related PRs

  • Render summary fields in modal sidebar #4851: The PillBadgeView component in PillBadgeView.tsx renders the PillBadge component, which is directly related to the changes made in the main PR that introduced the PillBadge component.
  • visual tweaks for menu and views in menu #4562: This PR introduces visual tweaks that may involve components like PillBadge, as it discusses updates to various views and components, potentially affecting how PillBadge is rendered in the UI.
  • Adding confidence to SAM predictions from box prompts #4904: While primarily focused on adding confidence scores to predictions, this PR may relate to the PillBadge component if it is used to display prediction results or statuses visually in the application.
  • Fix updateSample in useLooker #4905: This PR addresses updates in the useLooker hook, which may interact with UI components like PillBadge if they are part of the modal or sidebar where the looker is used.

Suggested labels

app

Suggested reviewers

  • imanjra
  • ritch

Poem

In a garden bright and fair,
A PillBadge blooms with flair.
Colors dance and icons gleam,
A badge of joy, a coder's dream!
With PillBadgeView by its side,
Together they take pride! 🌼✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1646a62 and c672a05.

📒 Files selected for processing (1)
  • app/packages/components/src/components/PillBadge/PillBadge.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/components/src/components/PillBadge/PillBadge.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
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: 6

🧹 Outside diff range and nitpick comments (4)
app/packages/core/src/plugins/SchemaIO/components/PillBadgeView.tsx (1)

11-22: LGTM: Implementation is solid, with a minor suggestion for improvement.

The component implementation is well-structured and follows React best practices. The use of getComponentProps for flexible styling is a good approach.

One minor suggestion for improvement:

Consider adding default values or null checks for the properties destructured from view to handle cases where these properties might be undefined.

Here's a suggested minor refactor:

const { text = '', color, variant, showIcon } = view;

return (
  <Box {...getComponentProps(props, "container")}>
    <PillBadge
      text={text}
      color={color}
      variant={variant}
      showIcon={showIcon}
      {...getComponentProps(props, "pillBadge")}
    />
  </Box>
);

This ensures that text will always have a value, even if it's not provided in the view object. You might want to add similar defaults for color, variant, and showIcon based on your specific requirements.

e2e-pw/src/oss/specs/sidebar/frame-filtering.spec.ts (1)

36-36: LGTM: Property name updated correctly.

The change from persist to persistent appears to be a correct update to the dataset API usage. This ensures that the datasets created for testing are properly saved.

Consider adding a brief comment explaining why persistence is necessary for these test datasets. This could improve code readability and maintainability.

+        # Ensure the dataset is saved persistently for the duration of the tests
         dataset.persistent = True
app/packages/core/src/plugins/SchemaIO/components/index.ts (1)

52-52: LGTM! The new PillBadgeView component is correctly exported.

The export statement for PillBadgeView is correctly added and follows the same pattern as other exports in this file. This change aligns with the PR objectives to introduce the new PillBadgeView component.

Consider maintaining alphabetical order for exports to improve readability and ease of maintenance. The PillBadgeView export could be moved up a few lines to keep the list alphabetized.

fiftyone/operators/types.py (1)

1478-1491: Implementation looks good, with a minor suggestion for improvement.

The PillBadgeView class is well-structured and inherits appropriately from ReadOnlyView. The docstring provides clear information about the class's purpose and parameters. However, to enhance clarity and maintainability, consider explicitly defining the class-specific attributes (text, color, variant, show_icon) in the __init__ method, even if they're handled by the parent class.

Example:

def __init__(self, text="Reviewed", color="primary", variant="outlined", show_icon=False, **kwargs):
    super().__init__(**kwargs)
    self.text = text
    self.color = color
    self.variant = variant
    self.show_icon = show_icon

This approach would make the class's specific properties more explicit and easier to understand for other developers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8ed8ca2 and c9f3dd4.

📒 Files selected for processing (9)
  • app/packages/components/src/components/PillBadge/PillBadge.tsx (1 hunks)
  • app/packages/components/src/components/PillBadge/index.ts (1 hunks)
  • app/packages/core/src/components/Modal/use-looker.ts (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/PillBadgeView.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts (1 hunks)
  • e2e-pw/src/oss/specs/sidebar/frame-filtering.spec.ts (1 hunks)
  • fiftyone/operators/types.py (1 hunks)
  • fiftyone/utils/sam.py (1 hunks)
  • fiftyone/utils/sam2.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • app/packages/components/src/components/PillBadge/index.ts
🧰 Additional context used
📓 Path-based instructions (5)
app/packages/components/src/components/PillBadge/PillBadge.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/use-looker.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/core/src/plugins/SchemaIO/components/PillBadgeView.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/plugins/SchemaIO/components/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.

e2e-pw/src/oss/specs/sidebar/frame-filtering.spec.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 (6)
app/packages/core/src/plugins/SchemaIO/components/PillBadgeView.tsx (1)

1-4: LGTM: Import statements are appropriate and concise.

The import statements are well-organized and include all necessary dependencies for the component's functionality.

e2e-pw/src/oss/specs/sidebar/frame-filtering.spec.ts (1)

Line range hint 1-78: Overall file structure and content look good.

The test file is well-structured and follows good testing practices:

  • It uses Playwright's test framework with custom extensions.
  • Creates two datasets with different frame filtering configurations for comprehensive testing.
  • Includes separate tests for asserting enabled and disabled frame filtering behaviors.
  • Follows TypeScript best practices with appropriate typing.
app/packages/core/src/components/Modal/use-looker.ts (1)

59-59: LGTM. Verify consistency across the codebase.

The change from looker.updateSample(sample) to looker.updateSample(sample.sample) looks correct and intentional. It suggests that the ModalSample type now has a nested sample property containing the actual sample data.

To ensure consistency, let's verify the usage of ModalSample across the codebase:

This will help us confirm that the change is consistent with other parts of the codebase and identify any potential areas that might need similar updates.

✅ Verification successful

Verified: Change is consistent across the codebase.

The update from looker.updateSample(sample) to looker.updateSample(sample.sample) aligns with the ModalSample type structure and is consistently applied throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the usage of ModalSample and updateSample method across the codebase

# Search for ModalSample type usage
echo "ModalSample type usage:"
rg --type typescript "ModalSample"

# Search for updateSample method calls
echo "\nupdateSample method calls:"
rg --type typescript "updateSample"

Length of output: 264


Script:

#!/bin/bash
# Description: Check the usage of ModalSample and updateSample method across the codebase

# Search for ModalSample type usage
echo "ModalSample type usage:"
rg --type ts "ModalSample"

# Search for updateSample method calls
echo "\nupdateSample method calls:"
rg --type ts "updateSample"

Length of output: 9487

fiftyone/utils/sam.py (1)

274-286: Excellent addition of prediction scores!

The inclusion of scores in the output dictionary enhances the model's output by providing confidence metrics for each prediction. This addition aligns well with best practices in machine learning, offering users valuable information about the reliability of each prediction.

fiftyone/utils/sam2.py (1)

Line range hint 204-219: LGTM: Enhanced output with prediction scores

The changes correctly implement the addition of scores to the output of the _forward_pass_boxes method. This enhancement provides valuable confidence information for the predictions.

To ensure these changes are fully integrated, please run the following script to check if the scores are being used elsewhere in the codebase:

If the script doesn't return any results, consider updating other parts of the codebase to utilize these scores for improved functionality.

✅ Verification successful

Action Required: Re-verify Usage of 'scores' in SAM2 Predictions

The previous attempt to search for scores usage failed due to an unrecognized file type. Please run the updated script below to accurately locate any references to scores related to SAM2 predictions:


Verification Completed: 'scores' Usage Confirmed

The scores variable is correctly utilized within fiftyone/utils/sam2.py at lines 214-222. There are no additional references to scores elsewhere in the codebase, ensuring that the integration is appropriate and isolated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of 'scores' in relation to SAM2 predictions

# Search for potential uses of 'scores' in Python files
rg --type python -g '!test_*' -g '!*_test.py' -i '(sam2.*scores|scores.*sam2)'

# Search for any modifications to the output structure of SAM2 predictions
rg --type python -g '!test_*' -g '!*_test.py' -i '(sam2.*output|output.*sam2)'

Length of output: 223


Script:

# 
#!/bin/bash
# Description: Check for usage of 'scores' in relation to SAM2 predictions

# Find all Python files excluding tests and search for 'scores' usage
fd --extension py --exclude 'test_*' --exclude '*_test.py' | xargs rg -i '(sam2.*scores|scores.*sam2)'

# Alternatively, using rg to search within .py files directly
rg -t py -g '!test_*' -g '!*_test.py' -i '(sam2.*scores|scores.*sam2)'

Length of output: 501

app/packages/components/src/components/PillBadge/PillBadge.tsx (1)

51-71: Component correctly handles string text prop.

The rendering logic for when text is a string is appropriately implemented and follows best practices.

Comment on lines +6 to +9
export default function PillBadgeView(props) {
const { schema } = props;
const { view = {} } = schema;
const { text, color, variant, showIcon } = view;
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 adding TypeScript types and using a named export.

While the component structure is good, it could benefit from the following improvements:

  1. Add TypeScript type annotations for props and destructured values to enhance type safety and developer experience.
  2. Consider using a named export instead of a default export for better refactoring capabilities and explicit imports.

Here's a suggested refactor:

import { Box } from "@mui/material";
import React from "react";
import { getComponentProps } from "../utils";
import PillBadge from "@fiftyone/components/src/components/PillBadge/PillBadge";

interface PillBadgeViewProps {
  schema: {
    view?: {
      text?: string;
      color?: string;
      variant?: string;
      showIcon?: boolean;
    };
  };
}

export function PillBadgeView({ schema }: PillBadgeViewProps) {
  const { view = {} } = schema;
  const { text, color, variant, showIcon } = view;

  // ... rest of the component
}

Comment on lines +5 to +15
const PillBadge = ({
text,
color = "default",
variant = "filled",
showIcon = true,
}: {
text: string | string[] | [string, string][];
color?: string;
variant?: "filled" | "outlined";
showIcon?: boolean;
}) => {
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 simplifying the text prop to improve maintainability.

The text prop accepts multiple types (string, string[], and [string, string][]), which increases complexity in the component logic and can lead to potential errors. Simplifying the prop to accept a single data type or splitting the component into separate components for each case could enhance readability and maintainability.

Comment on lines +85 to +91
onChange={(event) => {
const selectedText = text.find(
(t) => t[0] === event.target.value
);
setChipSelection(event.target.value);
setChipColor(selectedText?.[1] ?? "default");
}}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add checks for selectedText to prevent undefined access.

In the onChange handler, selectedText may be undefined if text.find does not find a matching element. Accessing selectedText[1] without checking if selectedText exists could lead to runtime errors. Consider adding a check to ensure selectedText is defined before using it.

Here's an example of how to adjust the code:

 onChange={(event) => {
   const selectedText = text.find(
     (t) => t[0] === event.target.value
   );
   setChipSelection(event.target.value);
-  setChipColor(selectedText?.[1] ?? "default");
+  if (selectedText) {
+    setChipColor(selectedText[1]);
+  } else {
+    setChipColor("default");
+  }
 }}
📝 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
onChange={(event) => {
const selectedText = text.find(
(t) => t[0] === event.target.value
);
setChipSelection(event.target.value);
setChipColor(selectedText?.[1] ?? "default");
}}
onChange={(event) => {
const selectedText = text.find(
(t) => t[0] === event.target.value
);
setChipSelection(event.target.value);
if (selectedText) {
setChipColor(selectedText[1]);
} else {
setChipColor("default");
}
}}

Comment on lines +35 to +42
const COLORS: { [key: string]: string } = {
default: "#999999",
primary: "#FFB682",
error: "error",
warning: "warning",
info: "info",
success: "#8BC18D",
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure COLORS object contains valid CSS color values.

In the COLORS object, the values for 'error', 'warning', and 'info' are strings that may not correspond to valid CSS color values. Assigning these strings to the color style property may not produce the desired effect. Consider replacing them with appropriate color codes or ensuring that the component interprets these string values correctly.

For example, you can update the COLORS object with valid color codes:

 const COLORS: { [key: string]: string } = {
   default: "#999999",
   primary: "#FFB682",
-  error: "error",
-  warning: "warning",
-  info: "info",
+  error: "#f44336",
+  warning: "#ff9800",
+  info: "#2196f3",
   success: "#8BC18D",
 };
📝 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
const COLORS: { [key: string]: string } = {
default: "#999999",
primary: "#FFB682",
error: "error",
warning: "warning",
info: "info",
success: "#8BC18D",
};
const COLORS: { [key: string]: string } = {
default: "#999999",
primary: "#FFB682",
error: "#f44336",
warning: "#ff9800",
info: "#2196f3",
success: "#8BC18D",
};

Br2850 and others added 2 commits October 10, 2024 09:22
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@Br2850 Br2850 merged commit fd70ada into feat/fo-assistant Oct 10, 2024
8 of 11 checks passed
@Br2850 Br2850 deleted the patch/badge branch October 10, 2024 15:46
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.

1 participant