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

Feat/operator exec ctx menu #5099

Merged
merged 3 commits into from
Nov 14, 2024
Merged

Conversation

ritch
Copy link
Contributor

@ritch ritch commented Nov 12, 2024

Ports the <OperatorExecutionButton /> and friends from teams to OSS.

fancy_button.mov

Example usage in python panel:

exec_button = types.OperatorExecutionButtonView(
    label="Simple Op",
    operator="@voxel51/panel-examples/simple_op"
)
menu.view("exec", view=exec_button)

Summary by CodeRabbit

  • New Features

    • Introduced OperatorExecutionButton, OperatorExecutionMenu, and OperatorExecutionTrigger components for enhanced operator execution functionality.
    • Enhanced Embeddings component with an operator placements feature for improved user interaction.
    • Added new type OperatorExecutionOption and hook useOperatorExecutionOptions for managing operator execution options.
  • Bug Fixes

    • Improved error handling and execution option management for better user experience.

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Walkthrough

The changes introduce several new React components related to operator execution within the user interface. The OperatorExecutionButtonView component renders a button for executing operators, while OperatorExecutionButton, OperatorExecutionMenu, and OperatorExecutionTrigger facilitate user interactions for executing operations. Additionally, new hooks and types enhance the management of execution options, improving the overall functionality and structure of the operator execution flow.

Changes

File Change Summary
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx New component OperatorExecutionButtonView added, along with several helper functions for button properties and styling.
app/packages/core/src/plugins/SchemaIO/components/index.ts Export statement for OperatorExecutionButtonView added.
app/packages/embeddings/src/Embeddings.tsx Added OperatorPlacements component to the Selectors section for executing operators.
app/packages/operators/src/components/OperatorExecutionButton/index.tsx New component OperatorExecutionButton created to trigger OperatorExecutionMenu.
app/packages/operators/src/components/OperatorExecutionMenu/index.tsx New component OperatorExecutionMenu added for displaying execution options.
app/packages/operators/src/components/OperatorExecutionTrigger/index.tsx New component OperatorExecutionTrigger introduced to manage the visibility of OperatorExecutionMenu.
app/packages/operators/src/index.ts Export statement for OperatorExecutionButton added.
app/packages/operators/src/state.ts New type OperatorExecutionOption and hook useOperatorExecutionOptions added, with updates to existing functions.

Possibly related PRs

Suggested labels

app, plugins

Suggested reviewers

  • imanjra
  • manivoxel51

Poem

🐰 In the meadow where buttons gleam,
New features bloom like a sweet dream.
With clicks and options, we now can play,
Executing tasks in a delightful way!
Hopping with joy, we celebrate this feat,
A UI so bright, it's truly a treat! 🌼


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 08dc93a and 58602ea.

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

@ritch ritch changed the base branch from develop to release/v1.1.0 November 12, 2024 23:22
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import TooltipProvider from "./TooltipProvider";

export default function ButtonView(props: ViewPropsType) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the filepath and the export function name divergence purposeful here? @ritch

The filepath is: app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx
But the export function name is regular ButtonView(...)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this, it should indeed match the file path!

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

🧹 Outside diff range and nitpick comments (14)
app/packages/operators/src/components/OperatorExecutionMenu/index.tsx (3)

5-14: Fix JSDoc parameter name inconsistency

The JSDoc parameter @param onClick should be @param onOptionClick to match the actual prop name.

  * @param onClose Callback for context menu close events
  * @param executionOptions List of operator execution options
- * @param onClick Callback for an option being clicked
+ * @param onOptionClick Callback for an option being clicked
  */

15-27: Consider extracting props interface

For better reusability and maintainability, consider extracting the props interface into a separate type definition.

+interface OperatorExecutionMenuProps {
+  anchor?: Element | null;
+  open: boolean;
+  onClose: () => void;
+  executionOptions: OperatorExecutionOption[];
+  onOptionClick?: (option: OperatorExecutionOption) => void;
+}

-export const OperatorExecutionMenu = ({
-  anchor,
-  open,
-  onClose,
-  executionOptions,
-  onOptionClick,
-}: {
-  anchor?: Element | null;
-  open: boolean;
-  onClose: () => void;
-  executionOptions: OperatorExecutionOption[];
-  onOptionClick?: (option: OperatorExecutionOption) => void;
-}) => {
+export const OperatorExecutionMenu = ({
+  anchor,
+  open,
+  onClose,
+  executionOptions,
+  onOptionClick,
+}: OperatorExecutionMenuProps) => {

51-51: Consider using only named exports

Having both named and default exports can lead to confusion. Consider sticking to named exports for consistency across the codebase.

-export default OperatorExecutionMenu;
app/packages/operators/src/components/OperatorExecutionButton/index.tsx (4)

1-8: Consider reorganizing imports for better maintainability

Consider reorganizing imports in the following order:

  1. React (should be first)
  2. External libraries (@mui/material)
  3. Internal components and types
-import { Button } from "@mui/material";
-import { OperatorExecutionTrigger } from "../OperatorExecutionTrigger";
-import React from "react";
-import {
-  ExecutionCallback,
-  ExecutionErrorCallback,
-} from "../../types-internal";
-import { OperatorExecutionOption } from "../../state";
+import React from "react";
+import { Button } from "@mui/material";
+import { OperatorExecutionTrigger } from "../OperatorExecutionTrigger";
+import { OperatorExecutionOption } from "../../state";
+import {
+  ExecutionCallback,
+  ExecutionErrorCallback,
+} from "../../types-internal";

10-19: Add return type to JSDoc documentation

The JSDoc is well-written but missing the @returns tag to document the component's return type.

 /**
  * Button which acts as a trigger for opening an `OperatorExecutionMenu`.
  *
  * @param operatorUri Operator URI
  * @param onSuccess Callback for successful operator execution
  * @param onError Callback for operator execution error
  * @param executionParams Parameters to provide to the operator's execute call
  * @param onOptionSelected Callback for execution option selection
  * @param disabled If true, disables the button and context menu
+ * @returns A React component that renders a button with operator execution functionality
  */

20-37: Extract props interface for better reusability

Consider extracting the props interface to improve code organization and enable reuse.

+interface OperatorExecutionButtonProps {
+  operatorUri: string;
+  onSuccess?: ExecutionCallback;
+  onError?: ExecutionErrorCallback;
+  executionParams?: object;
+  onOptionSelected?: (option: OperatorExecutionOption) => void;
+  disabled?: boolean;
+  children: React.ReactNode;
+}

-export const OperatorExecutionButton = ({
+export const OperatorExecutionButton = ({
   operatorUri,
   onSuccess,
   onError,
   executionParams,
   onOptionSelected,
   disabled,
   children,
   ...props
-}: {
-  operatorUri: string;
-  onSuccess?: ExecutionCallback;
-  onError?: ExecutionErrorCallback;
-  executionParams?: object;
-  onOptionSelected?: (option: OperatorExecutionOption) => void;
-  disabled?: boolean;
-  children: React.ReactNode;
-}) => {
+}: OperatorExecutionButtonProps) => {

54-54: Consider using only named exports

Having both named and default exports can lead to inconsistent import patterns across the codebase. Consider sticking with named exports only, which is a common practice in modern React applications.

-export default OperatorExecutionButton;
app/packages/embeddings/src/Embeddings.tsx (1)

80-87: Enhance UI integration and accessibility

While the button integration looks clean, consider these improvements:

  1. Add consistent spacing with other selector components
  2. Add ARIA labels for better accessibility
  <OperatorExecutionButton
    operatorUri="@voxel51/panel-examples/simple_op"
    variant="contained"
    color="primary"
    endIcon={<ExpandMoreIcon />}
+   style={{ marginRight: '0.25rem' }}
+   aria-label="Execute operator"
  >
    Execute
  </OperatorExecutionButton>
app/packages/operators/src/components/OperatorExecutionTrigger/index.tsx (5)

51-61: Consider defining a separate interface for the component props.

Defining a dedicated Props interface improves readability and maintainability. It clearly separates type definitions from the component logic, which is a best practice in TypeScript.

Apply this diff to create a OperatorExecutionTriggerProps interface:

+interface OperatorExecutionTriggerProps {
+  operatorUri: string;
+  children: React.ReactNode;
+  onClick?: () => void;
+  onSuccess?: ExecutionCallback;
+  onError?: ExecutionErrorCallback;
+  executionParams?: object;
+  executorOptions?: OperatorExecutorOptions;
+  onOptionSelected?: (option: OperatorExecutionOption) => void;
+  disabled?: boolean;
+}

 export const OperatorExecutionTrigger = ({
   operatorUri,
   onClick,
   onSuccess,
   onError,
   executionParams,
   executorOptions,
   onOptionSelected,
   disabled,
   children,
   ...props
-}: {
-  operatorUri: string;
-  children: React.ReactNode;
-  onClick?: () => void;
-  onSuccess?: ExecutionCallback;
-  onError?: ExecutionErrorCallback;
-  executionParams?: object;
-  executorOptions?: OperatorExecutorOptions;
-  onOptionSelected?: (option: OperatorExecutionOption) => void;
-  disabled?: boolean;
-}) => {
+}: OperatorExecutionTriggerProps) => {

68-70: Simplify by removing unnecessary useMemo for operatorHandlers.

Since operatorHandlers is a simple object and its dependencies are already handled, using useMemo here adds unnecessary complexity without significant performance benefits. You can define operatorHandlers directly.

Apply this diff to simplify the code:

-const operatorHandlers = useMemo(() => {
-  return { onSuccess, onError };
-}, [onSuccess, onError]);
+const operatorHandlers = { onSuccess, onError };

16-39: Enhance JSDoc comments with proper @param annotations.

Adding @param tags improves code documentation and assists developers using IDEs or documentation generators.

Apply this diff to include @param annotations:

  * This component registers a click handler which will manage the
  * `OperatorExecutionMenu` lifecycle.
  *
- * @param operatorUri Operator URI
- * @param onClick Callback for click events
- * @param onSuccess Callback for successful operator execution
- * @param onError Callback for operator execution error
- * @param executionParams Parameters to provide to the operator's execute call
- * @param executorOptions Operator executor options
- * @param onOptionSelected Callback for execution option selection
- * @param disabled If true, context menu will never open
+ * @param {string} operatorUri - Operator URI
+ * @param {() => void} [onClick] - Callback for click events
+ * @param {ExecutionCallback} [onSuccess] - Callback for successful operator execution
+ * @param {ExecutionErrorCallback} [onError] - Callback for operator execution error
+ * @param {object} [executionParams] - Parameters for the operator's execute call
+ * @param {OperatorExecutorOptions} [executorOptions] - Operator executor options
+ * @param {(option: OperatorExecutionOption) => void} [onOptionSelected] - Callback for execution option selection
+ * @param {boolean} [disabled] - If true, context menu will never open
+ * @param {React.ReactNode} children - Interactable component(s) to trigger execution
  */

92-99: Simplify the clickHandler logic for clarity.

Refactoring the clickHandler to return early when disabled improves readability.

Apply this diff to simplify the function:

 const clickHandler = useCallback(() => {
   if (disabled) {
     setIsMenuOpen(false);
+    return;
   }
-  } else {
-    onClick?.();
-    setIsMenuOpen(true);
-  }
+  onClick?.();
+  setIsMenuOpen(true);
 }, [setIsMenuOpen, onClick, disabled]);

74-84: Optimize dependency array in onExecute callback.

To prevent unnecessary re-renders, ensure that all dependencies in onExecute are correctly specified. If executorOptions or executionParams are objects that change frequently, consider memoizing them.

Memoize executorOptions and executionParams if appropriate:

+const memoizedExecutorOptions = useMemo(() => executorOptions, [executorOptions]);
+const memoizedExecutionParams = useMemo(() => executionParams, [executionParams]);

 const onExecute = useCallback(
   (options?: OperatorExecutorOptions) => {
     const resolvedOptions = {
-      ...executorOptions,
+      ...memoizedExecutorOptions,
       ...options,
     };

-    return operator.execute(executionParams ?? {}, resolvedOptions);
+    return operator.execute(memoizedExecutionParams ?? {}, resolvedOptions);
   },
-  [executorOptions, operator, executionParams]
+  [memoizedExecutorOptions, operator, memoizedExecutionParams]
 );
app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (1)

61-110: Consider using getVariant(props) within getButtonProps for consistency

In the getButtonProps function, variant is destructured directly from props.schema.view. Since variant is derived using getVariant(props) elsewhere, using the same method here would ensure consistency and centralize the variant logic.

Apply this diff to update getButtonProps:

 function getButtonProps(props: ViewPropsType): ButtonProps {
-  const { label, variant, color, disabled } = props.schema.view;
+  const { label, color, disabled } = props.schema.view;
+  const variant = getVariant(props);
   const baseProps: ButtonProps = getCommonProps(props);
   // Rest of the code remains the same
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b28b83 and 08dc93a.

📒 Files selected for processing (8)
  • app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/index.ts (1 hunks)
  • app/packages/embeddings/src/Embeddings.tsx (2 hunks)
  • app/packages/operators/src/components/OperatorExecutionButton/index.tsx (1 hunks)
  • app/packages/operators/src/components/OperatorExecutionMenu/index.tsx (1 hunks)
  • app/packages/operators/src/components/OperatorExecutionTrigger/index.tsx (1 hunks)
  • app/packages/operators/src/index.ts (1 hunks)
  • app/packages/operators/src/state.ts (8 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
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.

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.

app/packages/embeddings/src/Embeddings.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/operators/src/components/OperatorExecutionButton/index.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/operators/src/components/OperatorExecutionMenu/index.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/operators/src/components/OperatorExecutionTrigger/index.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/operators/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/operators/src/state.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 (15)
app/packages/operators/src/index.ts (1)

7-7: LGTM! Verify component exports

The new export follows the established patterns in the codebase and maintains proper organization.

Let's verify the component's existence and exports:

✅ Verification successful

Component exports verified successfully

The verification confirms:

  • Component file exists in the expected location
  • Component has a proper default export
  • No conflicting exports found in the codebase
  • Export pattern in index.ts matches the component's implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the OperatorExecutionButton component exists and exports correctly

# Check if the component file exists
fd -t f "OperatorExecutionButton" app/packages/operators/src/components

# Verify the default export in the component
ast-grep --pattern 'export default $_' app/packages/operators/src/components/OperatorExecutionButton/index.tsx

# Check for any potential duplicate exports of OperatorExecutionButton
rg "export.*OperatorExecutionButton" app/packages/operators/src

Length of output: 718

app/packages/operators/src/components/OperatorExecutionMenu/index.tsx (1)

1-3: LGTM: Clean and well-organized imports

The imports are minimal, necessary, and well-organized between external and internal dependencies.

app/packages/operators/src/components/OperatorExecutionButton/index.tsx (1)

38-51: Consider filtering button props for better type safety

The spread operator {...props} might pass unwanted props to the MUI Button component. Consider explicitly passing only valid button props.

-      <Button disabled={disabled} {...props}>
+      <Button
+        disabled={disabled}
+        {...(props as Omit<ButtonProps, keyof OperatorExecutionButtonProps>)}
+      >
app/packages/core/src/plugins/SchemaIO/components/index.ts (1)

41-41: LGTM! Export statement follows established conventions.

The new export for OperatorExecutionButtonView maintains consistency with the existing codebase by:

  • Following the established naming convention with the "View" suffix
  • Using the same export pattern as other components
  • Maintaining alphabetical ordering in the exports list
app/packages/embeddings/src/Embeddings.tsx (2)

26-30: LGTM! Clean import structure

The new imports from @fiftyone/operators are well-organized and necessary for the operator execution functionality.


80-87: Verify operator execution integration

Let's verify the integration of the operator execution functionality with the existing codebase.

✅ Verification successful

Let me gather more information about the operator execution components and their integration.


Let me check one more aspect about the OperatorExecutionTrigger component and its integration.


Operator execution integration is properly implemented

The implementation shows a well-structured operator execution flow:

  • OperatorExecutionButton is correctly imported from @fiftyone/operators
  • The component is properly integrated with OperatorExecutionTrigger which handles the execution menu lifecycle
  • The operator URI @voxel51/panel-examples/simple_op is properly referenced
  • All necessary props for execution handling (success/error callbacks, execution params) are supported
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for proper operator execution integration
echo "Checking for operator execution related files..."

# Look for operator execution related files
fd -e tsx -e ts . | rg -i "operator.*execution"

# Check for proper imports of OperatorExecutionButton
rg -l "import.*OperatorExecutionButton.*from.*@fiftyone/operators"

# Look for other usages of the operator URI
rg "@voxel51/panel-examples/simple_op"

Length of output: 748


Script:

#!/bin/bash
# Check the implementation of OperatorExecutionButton
ast-grep --pattern 'export $_ function OperatorExecutionButton' -l ts,tsx

# Look for the operator execution component implementations
cat app/packages/operators/src/components/OperatorExecutionButton/index.tsx

# Check for operator execution related types and interfaces
rg -A 5 "interface.*OperatorExecution" --type ts
rg -A 5 "type.*OperatorExecution" --type ts

Length of output: 2256


Script:

#!/bin/bash
# Check the implementation of OperatorExecutionTrigger
cat app/packages/operators/src/components/OperatorExecutionTrigger/index.tsx

# Look for any other usages of OperatorExecutionTrigger
rg -l "import.*OperatorExecutionTrigger"

Length of output: 3613

app/packages/operators/src/components/OperatorExecutionTrigger/index.tsx (2)

81-81: Confirm default execution parameters handling.

When executionParams is undefined, an empty object {} is passed to operator.execute. Ensure that this is the expected behavior and that the operator can handle empty parameters.

Verify that the operator's execute method can safely accept {} as parameters without causing errors or unexpected behavior.


86-89: Ensure useOperatorExecutionOptions updates when operatorUri changes.

If operatorUri can change dynamically, verify that useOperatorExecutionOptions correctly updates executionOptions to reflect the new operator.

Confirm that the hook handles changes to operatorUri and that executionOptions remain accurate.

app/packages/core/src/plugins/SchemaIO/components/OperatorExecutionButtonView.tsx (1)

12-59: Component OperatorExecutionButtonView is well-implemented

The main component correctly renders the operator execution button with appropriate props and styling. It follows React and TypeScript best practices, making effective use of hooks and conditional rendering.

app/packages/operators/src/state.ts (6)

228-242: Well-defined OperatorExecutionOption type enhances type safety.

The addition of the OperatorExecutionOption type provides a clear structure for operator execution options, improving code readability and maintainability.


333-335: Ensure fallbackId accurately reflects execution capabilities.

The calculation of fallbackId depends on executionOptions.allowImmediateExecution. Confirm that this flag accurately represents whether immediate execution is allowed to prevent unexpected behavior in selecting the default execution option.


388-410: Introduction of useOperatorExecutionOptions hook improves code modularity.

The new useOperatorExecutionOptions hook neatly encapsulates the logic for managing operator execution options, promoting reusability and clearer separation of concerns.


545-545: Verify the precedence of execution options in the execute function.

In the execute function, spreading ...options before ...promptingOperator.options means that promptingOperator.options will override any overlapping properties in options. Confirm that this is the intended behavior.


1031-1033: Ensure availability of ctx.executor when constructing OperatorResult.

When calling the callback with a new OperatorResult, verify that ctx.executor is defined to prevent potential runtime errors.


352-355: ⚠️ Potential issue

Handle empty options array to prevent errors when setting selectedID.

In the useEffect, if options is empty, accessing options[0].id may result in an error. Ensure the code safely handles cases where options is empty.

Apply this diff to handle empty options:

if (options.length === 1) {
  setSelectedID(options[0].id);
} else if (!selectedOptionExists) {
  const nextSelectedID =
    options.find((option) => option.default)?.id ||
-   options[0]?.id ||
+   (options.length > 0 ? options[0].id : fallbackId) ||
    fallbackId;
  setSelectedID(nextSelectedID);
}

Likely invalid or redundant comment.

Comment on lines +28 to +48
return (
<Menu anchorEl={anchor} open={open} onClose={onClose}>
{executionOptions.map((target) => (
<MenuItem
key={target.id}
onClick={() => {
onClose?.();
onOptionClick?.(target);
target.onClick();
}}
>
<Stack direction="column" spacing={1}>
<Typography fontWeight="bold">
{target.choiceLabel ?? target.label}
</Typography>
<Typography color="secondary">{target.description}</Typography>
</Stack>
</MenuItem>
))}
</Menu>
);
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 these improvements for robustness and accessibility

  1. The menu items should have proper ARIA labels for better accessibility.
  2. Consider memoizing the click handler to prevent unnecessary re-renders.
  3. Add error boundaries to handle potential rendering errors.
+const MenuItemContent = React.memo(({ target }: { target: OperatorExecutionOption }) => (
+  <Stack direction="column" spacing={1}>
+    <Typography fontWeight="bold">
+      {target.choiceLabel ?? target.label}
+    </Typography>
+    <Typography color="secondary">{target.description}</Typography>
+  </Stack>
+));

 return (
-  <Menu anchorEl={anchor} open={open} onClose={onClose}>
+  <Menu 
+    anchorEl={anchor} 
+    open={open} 
+    onClose={onClose}
+    role="menu"
+    aria-label="Operator execution options"
+  >
     {executionOptions.map((target) => (
       <MenuItem
         key={target.id}
+        role="menuitem"
+        aria-label={target.choiceLabel ?? target.label}
         onClick={() => {
           onClose?.();
           onOptionClick?.(target);
           target.onClick();
         }}
       >
-        <Stack direction="column" spacing={1}>
-          <Typography fontWeight="bold">
-            {target.choiceLabel ?? target.label}
-          </Typography>
-          <Typography color="secondary">{target.description}</Typography>
-        </Stack>
+        <MenuItemContent target={target} />
       </MenuItem>
     ))}
   </Menu>

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

Comment on lines 80 to 87
<OperatorExecutionButton
operatorUri="@voxel51/panel-examples/simple_op"
variant="contained"
color="primary"
endIcon={<ExpandMoreIcon />}
>
Execute
</OperatorExecutionButton>
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 making the operator URI configurable

The hardcoded operator URI "@voxel51/panel-examples/simple_op" limits the component's reusability. Consider:

  1. Making it configurable through props or context
  2. Adding error handling and loading states
  3. Adding TypeScript type safety for the operatorUri
+ interface EmbeddingsProps {
+   containerHeight: number;
+   dimensions: any;
+   operatorUri?: string;
+ }

- export default function Embeddings({ containerHeight, dimensions }) {
+ export default function Embeddings({ 
+   containerHeight, 
+   dimensions,
+   operatorUri = "@voxel51/panel-examples/simple_op"
+ }: EmbeddingsProps) {

  // ... existing code ...

  <OperatorExecutionButton
-   operatorUri="@voxel51/panel-examples/simple_op"
+   operatorUri={operatorUri}
+   onError={(error) => console.error('Operator execution failed:', error)}
+   loading={false}
    variant="contained"
    color="primary"
    endIcon={<ExpandMoreIcon />}
  >
    Execute
  </OperatorExecutionButton>

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

Comment on lines +156 to +157
function getVariant(pros: ViewPropsType) {
const variant = pros.schema.view.variant;
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

Fix typo in the function parameter name pros

There's a typo in the getVariant function parameter. It should be props instead of pros, and the same correction applies within the function body.

Apply this diff to fix the typo:

-function getVariant(pros: ViewPropsType) {
-  const variant = pros.schema.view.variant;
+function getVariant(props: ViewPropsType) {
+  const variant = props.schema.view.variant;
   if (defaultVariant.includes(variant)) return variant;
   if (variant === "round") return "contained";
   return "contained";
 }
📝 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
function getVariant(pros: ViewPropsType) {
const variant = pros.schema.view.variant;
function getVariant(props: ViewPropsType) {
const variant = props.schema.view.variant;
if (defaultVariant.includes(variant)) return variant;
if (variant === "round") return "contained";
return "contained";
}

app/packages/operators/src/state.ts Show resolved Hide resolved
tom-vx51
tom-vx51 previously approved these changes Nov 14, 2024
@ritch ritch merged commit 5dc1966 into release/v1.1.0 Nov 14, 2024
9 of 10 checks passed
@ritch ritch deleted the feat/operator-exec-ctx-menu branch November 14, 2024 23:17
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.

3 participants