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 exec button to py panels #5119

Merged
merged 2 commits into from
Nov 15, 2024
Merged

add exec button to py panels #5119

merged 2 commits into from
Nov 15, 2024

Conversation

ritch
Copy link
Contributor

@ritch ritch commented Nov 15, 2024

Summary by CodeRabbit

  • New Features
    • Introduced a new button for executing operators within views.
    • Added multiple view classes for enhanced data representation, including OneOfView, ListView, TupleView, TreeSelectionView, FrameLoaderView, and TimelineView.
  • Improvements
    • Streamlined button properties handling for better interactivity and color management.

@ritch ritch requested a review from tom-vx51 November 15, 2024 00:46
Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes in this pull request involve modifications to the OperatorExecutionButtonView component in the SchemaIO plugin, specifically regarding prop handling and button behavior. The onClick prop has been removed, altering click event management. Additionally, the button's variant handling has been simplified, and the default color for the button has been adjusted. New classes have been introduced in the fiftyone/operators/types.py file, enhancing the functionality of operator types by adding various view components.

Changes

File Path Change Summary
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx - Removed onClick from destructured props.
- Updated getButtonProps to derive variant from getVariant(props).
- Changed default button color from "tertiary" to "primary" when variant is "contained".
fiftyone/operators/types.py - Added classes: OperatorExecutionButtonView, OneOfView, ListView, TupleView, TreeSelectionView, FrameLoaderView, TimelineView with respective functionalities.
app/packages/operators/src/types.ts - Added class: OperatorExecutionButtonView extending View, with constructor and fromJSON method.

Possibly related PRs

  • Feat/operator exec ctx menu #5099: This PR introduces the OperatorExecutionButtonView component, which is directly related to the changes made in the main PR, as both involve modifications to the OperatorExecutionButtonView component and its associated functionality.
  • fixes and enhancements for python panels and operators #4550: This PR includes enhancements to the ButtonView, which is relevant because it discusses modifications to button properties and variants, similar to the changes made in the main PR regarding button behavior and props handling.
  • StatusButton component #5105: The introduction of the StatusButtonView in this PR parallels the main PR's focus on button components, as both involve creating specialized button views that handle specific functionalities and props.

Suggested reviewers

  • imanjra
  • tom-vx51

🐰 In the meadow, a button did gleam,
With colors so bright, it sparked a new dream.
Clicks now are handled with care and delight,
While views spring to life, a wonderful sight!
Hopping along, the code feels so right,
A dance of new features, from morning to night! 🌼


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.

tom-vx51
tom-vx51 previously approved these changes Nov 15, 2024
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: 2

🧹 Outside diff range and nitpick comments (3)
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (3)

59-60: Fix typo in getVariant function parameter name

There's a typo in the getVariant function parameter name (pros instead of props). While it works, it affects code readability.

Apply this fix:

-function getVariant(pros: ViewPropsType) {
-  const variant = pros.schema.view.variant;
+function getVariant(props: ViewPropsType) {
+  const variant = props.schema.view.variant;

87-90: Consider improvements to variant and color handling

  1. The variant condition could be simplified
  2. Consider using theme type safety for better maintainability

Here's a suggested improvement:

-  if (isNullish(variant) || variant === "contained") {
+  if (!variant || variant === "contained") {
     baseProps.variant = "contained";
     baseProps.color = "primary";
-    baseProps.sx.color = (theme) => theme.palette.text.primary;
+    baseProps.sx.color = (theme: Theme) => theme.palette.text.primary;
   }

Don't forget to import the Theme type:

import { Theme } from '@mui/material/styles';

Line range hint 13-24: Consider adding error boundary for operator execution

While the component is well-structured, it might benefit from proper error handling for operator execution failures. This is particularly important as it's being used in py panels where Python execution could fail.

Consider wrapping the component with an error boundary to gracefully handle and display operator execution errors:

import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({error}: {error: Error}) {
  return (
    <Typography color="error">
      Error executing operator: {error.message}
    </Typography>
  );
}

// Usage
<ErrorBoundary FallbackComponent={ErrorFallback}>
  <OperatorExecutionButtonView {...props} />
</ErrorBoundary>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5dc1966 and c147a99.

📒 Files selected for processing (2)
  • app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (3 hunks)
  • fiftyone/operators/types.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.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 (2)
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (1)

13-13: LGTM: Props destructuring is clean and follows best practices

The removal of the onClick prop in favor of OperatorExecutionButton's built-in execution handling improves component encapsulation.

fiftyone/operators/types.py (1)

1373-1400: OperatorExecutionButtonView class is properly implemented

The OperatorExecutionButtonView class correctly extends the Button class and includes necessary validation for the operator parameter. The examples provided are clear and helpful.

Comment on lines +1392 to +1399
icon (str): an icon for the button. Defaults to "expand_more" if not provided.
label (str): a label for the button.
description (str): a description for the button.
title (str): a tooltip title for the button.
operator (str): the name of the operator to execute when the button is clicked.
params (dict): the parameters to pass to the operator.
prompt (str): a prompt for the operation.
disabled (bool): whether the button is disabled.
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

Correct parameter types and defaults in the docstring

There are discrepancies between the docstring and the method implementation:

  • The prompt parameter is documented as (str) but should be (bool).
  • Default values mentioned in the docstring (e.g., icon defaults to "expand_more") are not reflected in the code.

Suggested fix:

Update the docstring to accurately reflect parameter types and default values.

 Args:
     icon (str, optional): an icon for the button. Defaults to "expand_more".
     label (str, optional): a label for the button.
     description (str, optional): a description for the button.
     title (str, optional): a tooltip title for the button.
     operator (str): the name of the operator to execute when the button is clicked.
     params (dict, optional): the parameters to pass to the operator.
-    prompt (str): a prompt for the operation.
+    prompt (bool, optional): whether to prompt the user before executing the operator.
     disabled (bool, optional): whether the button is disabled.

Additionally, align the default values in the code with those specified in the docstring.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +1402 to +1407
def __init__(self, **kwargs):
if "operator" not in kwargs or not isinstance(kwargs["operator"], str):
raise ValueError(
"The 'operator' parameter of type str is required."
)
super().__init__(**kwargs)
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

Define explicit __init__ parameters for clarity and type safety

Explicitly defining parameters in the __init__ method enhances readability and allows for better type checking. It makes the expected inputs clear to users and improves maintainability. Consider replacing **kwargs with explicit parameters.

Proposed change:

-def __init__(self, **kwargs):
+def __init__(
+    self,
+    operator: str,
+    icon: str = "expand_more",
+    label: Optional[str] = None,
+    description: Optional[str] = None,
+    title: Optional[str] = None,
+    params: Optional[dict] = None,
+    prompt: bool = False,
+    disabled: bool = False,
+    **kwargs,
+):
     if not isinstance(operator, str):
         raise ValueError("The 'operator' parameter of type str is required.")
-    super().__init__(**kwargs)
+    super().__init__(
+        operator=operator,
+        icon=icon,
+        label=label,
+        description=description,
+        title=title,
+        params=params,
+        prompt=prompt,
+        disabled=disabled,
+        **kwargs,
+    )
📝 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
def __init__(self, **kwargs):
if "operator" not in kwargs or not isinstance(kwargs["operator"], str):
raise ValueError(
"The 'operator' parameter of type str is required."
)
super().__init__(**kwargs)
def __init__(
self,
operator: str,
icon: str = "expand_more",
label: Optional[str] = None,
description: Optional[str] = None,
title: Optional[str] = None,
params: Optional[dict] = None,
prompt: bool = False,
disabled: bool = False,
**kwargs,
):
if not isinstance(operator, str):
raise ValueError("The 'operator' parameter of type str is required.")
super().__init__(
operator=operator,
icon=icon,
label=label,
description=description,
title=title,
params=params,
prompt=prompt,
disabled=disabled,
**kwargs,
)

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: 2

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

1244-1246: Enhance JSDoc documentation for better clarity.

The current documentation is minimal. Consider adding more details about the purpose, usage, and parameters of this view.

 /**
- * Operator class for rendering a execution button.
+ * Operator class for rendering an execution button in the UI.
+ * This view can be used to create interactive buttons that trigger operator execution.
+ * 
+ * @example
+ * ```typescript
+ * const view = new OperatorExecutionButtonView({
+ *   label: "Execute Operation",
+ *   description: "Click to run the operation"
+ * });
+ * ```
  */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c147a99 and c755a45.

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

Comment on lines +1248 to +1256
class OperatorExecutionButtonView extends View {
constructor(options: ViewProps) {
super(options);
this.name = "OperatorExecutionButtonView";
}
static fromJSON(json) {
return new OperatorExecutionButtonView(json);
}
}
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

Export the OperatorExecutionButtonView class.

The class should be exported to make it available for use in other modules, following the pattern of other view classes in this file.

-class OperatorExecutionButtonView extends View {
+export class OperatorExecutionButtonView extends View {
📝 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
class OperatorExecutionButtonView extends View {
constructor(options: ViewProps) {
super(options);
this.name = "OperatorExecutionButtonView";
}
static fromJSON(json) {
return new OperatorExecutionButtonView(json);
}
}
export class OperatorExecutionButtonView extends View {
constructor(options: ViewProps) {
super(options);
this.name = "OperatorExecutionButtonView";
}
static fromJSON(json) {
return new OperatorExecutionButtonView(json);
}
}

return new OperatorExecutionButtonView(json);
}
}

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 OperatorExecutionButtonView to VIEWS constant.

The new view class needs to be added to the VIEWS constant to support proper JSON deserialization through the viewFromJSON function.

 const VIEWS = {
   View,
   InferredView,
   Form,
   ReadOnlyView,
   // ... other views
   PillBadgeView,
   ModalView,
   ToastView,
+  OperatorExecutionButtonView,
 };

Committable suggestion skipped: line range outside the PR's diff.

@ritch ritch merged commit 4ec4acc into release/v1.1.0 Nov 15, 2024
13 checks passed
@ritch ritch deleted the cleanup-exec-btn branch November 15, 2024 02:11
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