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
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import React from "react";
import { MuiIconFont } from "@fiftyone/components";
import { OperatorExecutionButton, usePanelEvent } from "@fiftyone/operators";
import { usePanelId } from "@fiftyone/spaces";
import { isNullish } from "@fiftyone/utilities";
import { Box, ButtonProps, Typography } from "@mui/material";
import { getColorByCode, getComponentProps, getDisabledColors } from "../utils";
import { ViewPropsType } from "../utils/types";
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!

const { schema, path, onClick } = props;
const { view = {} } = schema;
const {
description,
icon,
icon_position = "right",
label,
operator,
params = {},
prompt,
title,
disabled = false,
} = view;
const panelId = usePanelId();
const handleClick = usePanelEvent();
const variant = getVariant(props);
const computedParams = { ...params, path };

const Icon = icon ? (
<MuiIconFont
name={icon}
{...getComponentProps(props, "icon", getIconProps(props))}
/>
) : (
<ExpandMoreIcon />
);

return (
<Box {...getComponentProps(props, "container")}>
<TooltipProvider title={title} {...getComponentProps(props, "tooltip")}>
<OperatorExecutionButton
operatorUri={operator}
variant={variant}
color="primary"
disabled={disabled}
startIcon={icon_position === "left" ? Icon : undefined}
endIcon={icon_position === "right" ? Icon : undefined}
title={description}
>
{label}
</OperatorExecutionButton>
</TooltipProvider>
</Box>
);
}

function getButtonProps(props: ViewPropsType): ButtonProps {
const { label, variant, color, disabled } = props.schema.view;
const baseProps: ButtonProps = getCommonProps(props);
if (isNullish(label)) {
baseProps.sx["& .MuiButton-startIcon"] = { mr: 0, ml: 0 };
baseProps.sx.minWidth = "auto";
baseProps.sx.p = "6px";
}
if (variant === "round") {
baseProps.sx.borderRadius = "1rem";
baseProps.sx.p = "3.5px 10.5px";
}
if (variant === "square") {
baseProps.sx.borderRadius = "3px 3px 0 0";
baseProps.sx.backgroundColor = (theme) => theme.palette.background.field;
baseProps.sx.borderBottom = "1px solid";
baseProps.sx.paddingBottom = "5px";
baseProps.sx.borderColor = (theme) => theme.palette.primary.main;
}
if (variant === "outlined") {
baseProps.sx.p = "5px";
}
if ((variant === "square" || variant === "outlined") && isNullish(color)) {
const borderColor =
"rgba(var(--fo-palette-common-onBackgroundChannel) / 0.23)";
baseProps.sx.borderColor = borderColor;
baseProps.sx.borderBottomColor = borderColor;
}
if (isNullish(variant)) {
baseProps.variant = "contained";
baseProps.color = "tertiary";
baseProps.sx["&:hover"] = {
backgroundColor: (theme) => theme.palette.tertiary.hover,
};
}

if (disabled) {
const [bgColor, textColor] = getDisabledColors();
baseProps.sx["&.Mui-disabled"] = {
backgroundColor: variant === "outlined" ? "inherit" : bgColor,
color: textColor,
};
if (["square", "outlined"].includes(variant)) {
baseProps.sx["&.Mui-disabled"].backgroundColor = (theme) =>
theme.palette.background.field;
}
}

return baseProps;
}

function getIconProps(props: ViewPropsType): ButtonProps {
return getCommonProps(props);
}

function getCommonProps(props: ViewPropsType): ButtonProps {
const color = getColor(props);
const disabled = props.schema.view?.disabled || false;

return {
sx: {
color,
fontSize: "1rem",
fontWeight: "bold",
borderColor: color,
"&:hover": {
borderColor: color,
},
...(disabled
? {
opacity: 0.5,
}
: {}),
},
};
}

function getColor(props: ViewPropsType) {
const {
schema: { view = {} },
} = props;
const { color } = view;
if (color) {
return getColorByCode(color);
}
const variant = getVariant(props);
return (theme) => {
return variant === "contained"
? theme.palette.common.white
: theme.palette.secondary.main;
};
}

const defaultVariant = ["contained", "outlined"];

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

if (defaultVariant.includes(variant)) return variant;
if (variant === "round") return "contained";
return "contained";
}
1 change: 1 addition & 0 deletions app/packages/core/src/plugins/SchemaIO/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export { default as ModalView } from "./ModalView";
export { default as NativeModelEvaluationView } from "./NativeModelEvaluationView";
export { default as ObjectView } from "./ObjectView";
export { default as OneOfView } from "./OneOfView";
export { default as OperatorExecutionButtonView } from "./OperatorExecutionButtonView";
export { default as PillBadgeView } from "./PillBadgeView";
export { default as PlotlyView } from "./PlotlyView";
export { default as PrimitiveView } from "./PrimitiveView";
Expand Down
15 changes: 14 additions & 1 deletion app/packages/embeddings/src/Embeddings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@ import { useWarnings } from "./useWarnings";
import { EmbeddingsPlot } from "./EmbeddingsPlot";
import { usePlotSelection } from "./usePlotSelection";
import { useResetPlotZoom } from "./useResetPlotZoom";
import { OperatorPlacements, types } from "@fiftyone/operators";
import {
OperatorExecutionButton,
OperatorPlacements,
types,
} from "@fiftyone/operators";
import ComputeVisualizationButton from "./ComputeVisualizationButton";
import EmptyEmbeddings from "./EmptyEmbeddings";
import useComputeVisualization from "./useComputeVisualization";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";

const Value: React.FC<{ value: string; className: string }> = ({ value }) => {
return <>{value}</>;
Expand Down Expand Up @@ -72,6 +77,14 @@ export default function Embeddings({ containerHeight, dimensions }) {
<EmbeddingsContainer ref={el} data-cy="embeddings-container">
<Selectors>
<div>
<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.

<Selector
cy="embeddings"
{...brainResultSelector.handlers}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Button } from "@mui/material";
import { OperatorExecutionTrigger } from "../OperatorExecutionTrigger";
import React from "react";
import {
ExecutionCallback,
ExecutionErrorCallback,
} from "../../types-internal";
import { OperatorExecutionOption } from "../../state";

/**
* 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
*/
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;
}) => {
return (
<OperatorExecutionTrigger
operatorUri={operatorUri}
onSuccess={onSuccess}
onError={onError}
executionParams={executionParams}
onOptionSelected={onOptionSelected}
disabled={disabled}
>
<Button disabled={disabled} {...props}>
{children}
</Button>
</OperatorExecutionTrigger>
);
};

export default OperatorExecutionButton;
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Menu, MenuItem, Stack, Typography } from "@mui/material";
import React from "react";
import { OperatorExecutionOption } from "../../state";

/**
* Component which provides a context menu for executing an operator using a
* specified execution target.
*
* @param anchor Element to use as context menu anchor
* @param open If true, context menu will be visible
* @param onClose Callback for context menu close events
* @param executionOptions List of operator execution options
* @param onClick Callback for an option being clicked
*/
export const OperatorExecutionMenu = ({
anchor,
open,
onClose,
executionOptions,
onOptionClick,
}: {
anchor?: Element | null;
open: boolean;
onClose: () => void;
executionOptions: OperatorExecutionOption[];
onOptionClick?: (option: OperatorExecutionOption) => void;
}) => {
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>
);
Comment on lines +28 to +48
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.

};

export default OperatorExecutionMenu;
Loading