mirror of
https://github.com/coder/coder.git
synced 2026-11-12 20:50:29 +08:00
In v1, we had a quick and easy way to leave creation forms - an escape button (and key handler) in the top right corner. This was especially helpful in cases where the form was long enough that the 'Cancel' button was off-screen. This ports over that component into v2 and hooks up into our two existing forms: <img width="977" alt="Screen Shot 2022-02-09 at 5 48 03 PM" src="https://user-images.githubusercontent.com/88213859/153321503-af957f2b-d674-4ebf-9ac5-97939cb9153f.png"> In addition, this adds test cases + a storybook story for it.
56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
import IconButton from "@material-ui/core/IconButton"
|
|
import { makeStyles } from "@material-ui/core/styles"
|
|
import Typography from "@material-ui/core/Typography"
|
|
import React, { useEffect } from "react"
|
|
import { CloseIcon } from "../Icons/Close"
|
|
|
|
export interface FormCloseButtonProps {
|
|
onClose: () => void
|
|
}
|
|
|
|
export const FormCloseButton: React.FC<FormCloseButtonProps> = ({ onClose }) => {
|
|
const styles = useStyles()
|
|
|
|
useEffect(() => {
|
|
const handleKeyPress = (event: KeyboardEvent) => {
|
|
if (event.key === "Escape") {
|
|
onClose()
|
|
}
|
|
}
|
|
|
|
document.body.addEventListener("keydown", handleKeyPress, false)
|
|
|
|
return () => {
|
|
document.body.removeEventListener("keydown", handleKeyPress, false)
|
|
}
|
|
}, [])
|
|
|
|
return (
|
|
<IconButton className={styles.closeButton} onClick={onClose} size="medium">
|
|
<CloseIcon />
|
|
<Typography variant="caption" className={styles.label}>
|
|
ESC
|
|
</Typography>
|
|
</IconButton>
|
|
)
|
|
}
|
|
|
|
const useStyles = makeStyles((theme) => ({
|
|
closeButton: {
|
|
position: "fixed",
|
|
top: theme.spacing(3),
|
|
right: theme.spacing(6),
|
|
opacity: 0.5,
|
|
color: theme.palette.text.primary,
|
|
"&:hover": {
|
|
opacity: 1,
|
|
},
|
|
},
|
|
label: {
|
|
position: "absolute",
|
|
left: "50%",
|
|
top: "100%",
|
|
transform: "translate(-50%, 50%)",
|
|
},
|
|
}))
|