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 possibility for uncontrolled (promise-based) behavior to FeedbackButton #2425

Merged
merged 13 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions .changeset/quiet-kangaroos-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@comet/admin": minor
---

Add possibility for uncontrolled (promise-based) behavior to `FeedbackButton`

Previously the `FeedbackButton` was controlled by the props `loading` and `hasErrors`. To enable more use cases and easier usage, a promise-based way was added. If neither of the mentioned props are passed, the component uses the promise returned by `onClick` to evaluate the idle, loading and error state.
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ export interface FeedbackButtonProps
root: typeof LoadingButton;
tooltip: typeof CometTooltip;
}>,
LoadingButtonProps {
loading?: boolean;
Omit<LoadingButtonProps, "loading"> {
onClick?: () => void | Promise<void>;
hasErrors?: boolean;
loading?: boolean;
startIcon?: ReactNode;
endIcon?: ReactNode;
tooltipSuccessMessage?: ReactNode;
Expand All @@ -49,6 +50,7 @@ type FeedbackButtonDisplayState = "idle" | "loading" | "success" | "error";

export function FeedbackButton(inProps: FeedbackButtonProps) {
const {
onClick,
loading,
hasErrors,
children,
Expand All @@ -73,6 +75,8 @@ export function FeedbackButton(inProps: FeedbackButtonProps) {
displayState,
};

const isUncontrolled = loading === undefined && hasErrors === undefined;

const resolveTooltipForDisplayState = (displayState: FeedbackButtonDisplayState) => {
switch (displayState) {
case "error":
Expand All @@ -84,7 +88,26 @@ export function FeedbackButton(inProps: FeedbackButtonProps) {
}
};

const handleOnClick =
isUncontrolled && onClick
? async () => {
try {
setDisplayState("loading");
await onClick();
setDisplayState("success");
} catch (_) {
setDisplayState("error");
} finally {
setTimeout(() => {
setDisplayState("idle");
}, 3000);
}
}
: onClick;

useEffect(() => {
if (isUncontrolled) return;

let timeoutId: number | undefined;
let timeoutDuration: number | undefined;
let newDisplayState: FeedbackButtonDisplayState;
Expand All @@ -95,7 +118,7 @@ export function FeedbackButton(inProps: FeedbackButtonProps) {
timeoutDuration = 0;
newDisplayState = "error";
} else if (displayState === "loading" && !loading && !hasErrors) {
timeoutDuration = 500;
timeoutDuration = 50;
newDisplayState = "success";
} else if (displayState === "error") {
timeoutDuration = 5000;
Expand All @@ -115,7 +138,7 @@ export function FeedbackButton(inProps: FeedbackButtonProps) {
window.clearTimeout(timeoutId);
}
};
}, [displayState, loading, hasErrors]);
}, [displayState, loading, hasErrors, isUncontrolled]);

const tooltip = (
<Tooltip
Expand All @@ -131,11 +154,12 @@ export function FeedbackButton(inProps: FeedbackButtonProps) {

return (
<Root
onClick={handleOnClick}
ownerState={ownerState}
loading={loading !== undefined ? loading : displayState === "loading"}
variant={variant}
color={color}
disabled={disabled || loading || displayState === "loading"}
disabled={disabled || (loading !== undefined ? loading : displayState === "loading")}
loadingPosition={startIcon ? "start" : "end"}
loadingIndicator={<ThreeDotSaving />}
startIcon={startIcon && tooltip}
Expand Down
24 changes: 4 additions & 20 deletions packages/admin/admin/src/dataGrid/CrudContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ import { RowActionsMenu } from "../rowActions/RowActionsMenu";

interface DeleteDialogProps {
dialogOpen: boolean;
loading?: boolean;
hasErrors?: boolean;
onDelete: () => void;
onDelete: () => Promise<void>;
onCancel: () => void;
}

const DeleteDialog = (props: DeleteDialogProps) => {
const { dialogOpen, loading, hasErrors, onDelete, onCancel } = props;
const { dialogOpen, onDelete, onCancel } = props;

return (
<Dialog open={dialogOpen} onClose={onDelete}>
Expand All @@ -38,8 +36,6 @@ const DeleteDialog = (props: DeleteDialogProps) => {
<FeedbackButton
startIcon={<DeleteIcon />}
onClick={onDelete}
loading={loading}
hasErrors={hasErrors}
color="primary"
variant="contained"
tooltipErrorMessage={<FormattedMessage id="comet.common.deleteFailed" defaultMessage="Failed to delete" />}
Expand Down Expand Up @@ -68,24 +64,18 @@ export function CrudContextMenu<CopyData>({ url, onPaste, onDelete, refetchQueri
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [copyLoading, setCopyLoading] = useState(false);
const [pasting, setPasting] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const [hasDeleteErrors, setHasDeleteErrors] = useState(false);

const handleDeleteClick = async () => {
if (!onDelete) return;
setHasDeleteErrors(false);
setDeleteLoading(true);

try {
await onDelete({
client,
});
if (refetchQueries) await client.refetchQueries({ include: refetchQueries });
setDeleteDialogOpen(false);
} catch (_) {
setHasDeleteErrors(true);
throw new Error("Delete failed");
} finally {
setDeleteLoading(false);
}
};

Expand Down Expand Up @@ -186,13 +176,7 @@ export function CrudContextMenu<CopyData>({ url, onPaste, onDelete, refetchQueri
)}
</RowActionsMenu>
</RowActionsMenu>
<DeleteDialog
dialogOpen={deleteDialogOpen}
hasErrors={hasDeleteErrors}
loading={deleteLoading}
onCancel={() => setDeleteDialogOpen(false)}
onDelete={handleDeleteClick}
/>
<DeleteDialog dialogOpen={deleteDialogOpen} onCancel={() => setDeleteDialogOpen(false)} onDelete={handleDeleteClick} />
</>
);
}
Original file line number Diff line number Diff line change
@@ -1,38 +1,116 @@
import { FeedbackButton, Toolbar, ToolbarActions, ToolbarFillSpace, ToolbarTitleItem } from "@comet/admin";
import { Assets } from "@comet/admin-icons";
import { FeedbackButton } from "@comet/admin";
import { Check, Close } from "@comet/admin-icons";
import { Card, CardContent, Typography } from "@mui/material";
import { storiesOf } from "@storybook/react";
import * as React from "react";

import { storyRouterDecorator } from "../../../../story-router.decorator";
import { toolbarDecorator } from "../toolbar.decorator";

storiesOf("stories/components/Toolbar/Feedback Button", module)
.addDecorator(toolbarDecorator())
.addDecorator(storyRouterDecorator())
.add("Feedback", () => {
.add("Controlled", () => {
const [loading, setLoading] = React.useState(false);
const [loadingError, setLoadingError] = React.useState(false);
const [hasErrors, setHasErrors] = React.useState(false);

const onClick = () => {
setLoading(true);

setTimeout(() => {
setLoading(false);
}, 2000);
};

const onClickError = () => {
setLoadingError(true);

setTimeout(() => {
setHasErrors(true);
setLoadingError(false);
}, 2000);

setTimeout(() => {
setHasErrors(false);
}, 4000);
};

return (
<Toolbar>
<ToolbarTitleItem>Feedback Button</ToolbarTitleItem>
<ToolbarFillSpace />
<ToolbarActions>
<Card>
<CardContent>
<Typography variant="h2">Controlled FeedbackButton</Typography>
<Typography my={3}>
This FeedbackButton is controlled by the props loading and hasErrors. A promise returned by onClick will be ignored if one of
the props is defined.
</Typography>
<Typography variant="h3" mb={1}>
Success
</Typography>
<FeedbackButton
color="primary"
variant="contained"
loading={loading}
onClick={() => {
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 1000);
}}
startIcon={<Assets />}
onClick={onClick}
startIcon={<Check />}
tooltipSuccessMessage="Saving was successful"
tooltipErrorMessage="Error while saving"
>
Click me
</FeedbackButton>
<Typography variant="h3" mt={2} mb={1}>
Error
</Typography>
<FeedbackButton
color="primary"
variant="contained"
loading={loadingError}
hasErrors={hasErrors}
onClick={onClickError}
startIcon={<Close />}
tooltipSuccessMessage="Saving was successful"
tooltipErrorMessage="Error while saving"
>
Click me
</FeedbackButton>
</CardContent>
</Card>
);
})
.add("Uncontrolled", () => {
return (
<Card>
<CardContent>
<Typography variant="h2">Uncontrolled FeedbackButton</Typography>
<Typography my={3}>
This FeedbackButton is controlled by the promise returned by the onClick function. Both the loading and hasError props have to
be undefined.
</Typography>
<Typography variant="h3" mb={1}>
Success
</Typography>
<FeedbackButton
color="primary"
variant="contained"
onClick={async () => new Promise((resolve) => setTimeout(resolve, 2000))}
startIcon={<Check />}
tooltipSuccessMessage="Saving was successful"
tooltipErrorMessage="Error while saving"
>
Click me
</FeedbackButton>
<Typography variant="h3" mt={2} mb={1}>
Error
</Typography>
<FeedbackButton
color="primary"
variant="contained"
onClick={async () => new Promise((_, reject) => setTimeout(reject, 2000))}
startIcon={<Close />}
tooltipSuccessMessage="Saving was successful"
tooltipErrorMessage="Error while saving"
>
Feedback
Click me
</FeedbackButton>
</ToolbarActions>
</Toolbar>
</CardContent>
</Card>
);
});
Loading