/
TextEditor.tsx
113 lines (98 loc) · 2.88 KB
/
TextEditor.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { useRef, useLayoutEffect } from "react";
import { EditorProps } from "react-data-grid";
import { makeStyles, createStyles, TextField } from "@material-ui/core";
import { FieldType } from "constants/fields";
import { getCellValue } from "utils/fns";
import { useFiretableContext } from "contexts/FiretableContext";
const useStyles = makeStyles((theme) =>
createStyles({
root: {
margin: theme.spacing(0, -1.5),
width: `calc(100% + ${theme.spacing(1.5) * 2}px)`,
height: "100%",
backgroundColor:
theme.palette.background.elevation?.[8] ??
theme.palette.background.paper,
},
inputBase: {
padding: theme.spacing(0, 1.5),
height: "100%",
font: "inherit",
letterSpacing: "inherit", // Prevent text jumping
},
input: {
paddingBottom: theme.spacing(0.75), // Align baselines
letterSpacing: "inherit", // Prevent text jumping
height: "100%", // Stop text clipping
},
})
);
export default function TextEditor({ row, column }: EditorProps<any>) {
const { updateCell } = useFiretableContext();
const classes = useStyles();
const type = (column as any).config?.renderFieldType ?? (column as any).type;
const cellValue = getCellValue(row, column.key);
const defaultValue =
type === FieldType.percentage && typeof cellValue === "number"
? cellValue * 100
: cellValue;
const inputRef = useRef<HTMLInputElement>(null);
useLayoutEffect(() => {
return () => {
const newValue = inputRef.current?.value;
if (newValue !== undefined && updateCell) {
if (type === FieldType.number || type === FieldType.percentage) {
updateCell(row.ref, column.key, Number(newValue));
} else {
updateCell(row.ref, column.key, newValue);
}
}
};
}, []);
let inputType = "text";
switch (type) {
case FieldType.email:
inputType = "email";
break;
case FieldType.phone:
inputType = "tel";
break;
case FieldType.url:
inputType = "url";
break;
case FieldType.number:
case FieldType.percentage:
inputType = "number";
break;
default:
break;
}
const { maxLength } = (column as any).config;
return (
<TextField
defaultValue={defaultValue}
type={inputType}
fullWidth
variant="standard"
inputProps={{
ref: inputRef,
maxLength: maxLength,
}}
className={classes.root}
InputProps={{
classes: { root: classes.inputBase, input: classes.input },
endAdornment:
(column as any).type === FieldType.percentage ? "%" : undefined,
}}
autoFocus
onKeyDown={(e) => {
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.stopPropagation();
}
if (e.key === "Escape") {
(e.target as any).value = defaultValue;
}
}}
/>
);
}