saleor-dashboard/src/components/EditableTableCell/EditableTableCell.tsx

100 lines
2.5 KiB
TypeScript
Raw Normal View History

2019-06-19 14:40:52 +00:00
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
2019-10-30 14:34:24 +00:00
import { makeStyles } from "@material-ui/core/styles";
2019-06-19 14:40:52 +00:00
import TableCell from "@material-ui/core/TableCell";
import TextField, { TextFieldProps } from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
2019-08-09 11:14:35 +00:00
import classNames from "classnames";
2019-08-09 10:26:22 +00:00
import React from "react";
2019-06-19 14:40:52 +00:00
2019-08-09 11:14:35 +00:00
import useForm from "@saleor/hooks/useForm";
2019-06-19 14:40:52 +00:00
2019-10-30 14:34:24 +00:00
const useStyles = makeStyles(theme => ({
card: {
border: `1px solid ${theme.palette.divider}`
},
container: {
position: "relative"
},
overlay: {
cursor: "pointer",
height: "100vh",
left: 0,
position: "fixed",
top: 0,
width: "100vw",
zIndex: 1
},
root: {
left: 0,
minWidth: theme.spacing(20),
position: "absolute",
top: 0,
width: `calc(100% + ${theme.spacing(4)}px)`,
zIndex: 2
},
text: {
cursor: "pointer",
fontSize: "0.8125rem"
}
}));
2019-06-19 14:40:52 +00:00
2019-10-30 14:34:24 +00:00
interface EditableTableCellProps {
2019-06-19 14:40:52 +00:00
className?: string;
defaultValue?: string;
focused?: boolean;
InputProps?: TextFieldProps;
value: string;
onConfirm(value: string): any;
}
2019-10-30 14:34:24 +00:00
export const EditableTableCell: React.FC<EditableTableCellProps> = props => {
const {
2019-06-19 14:40:52 +00:00
className,
defaultValue,
focused,
InputProps,
value,
onConfirm
2019-10-30 14:34:24 +00:00
} = props;
const classes = useStyles(props);
2019-06-19 14:40:52 +00:00
2019-10-30 14:34:24 +00:00
const handleConfirm = (data: { value: string }) => {
disable();
onConfirm(data.value);
};
2019-08-09 11:14:35 +00:00
2019-10-30 14:34:24 +00:00
const [opened, setOpenStatus] = React.useState(focused);
const { change, data } = useForm({ value }, [], handleConfirm);
const enable = () => setOpenStatus(true);
const disable = () => setOpenStatus(false);
return (
<TableCell className={classNames(classes.container, className)}>
{opened && <div className={classes.overlay} onClick={disable} />}
<Typography variant="caption" onClick={enable} className={classes.text}>
{value || defaultValue}
</Typography>
{opened && (
<div className={classes.root}>
<Card className={classes.card}>
<CardContent>
<TextField
name="value"
autoFocus
fullWidth
onChange={change}
value={data.value}
variant="standard"
{...InputProps}
/>
</CardContent>
</Card>
</div>
)}
</TableCell>
);
};
2019-06-19 14:40:52 +00:00
EditableTableCell.displayName = "EditableTableCell";
export default EditableTableCell;