/
number-overlay-editor.tsx
67 lines (58 loc) 路 2.51 KB
/
number-overlay-editor.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
import * as React from "react";
import { NumberOverlayEditorStyle } from "./number-overlay-editor-style";
import { NumericFormat } from "react-number-format";
import type { SelectionRange } from "../../data-grid/data-grid-types";
import type { NumberFormatValues } from "react-number-format/types/types";
interface Props {
readonly value: number | undefined;
readonly disabled?: boolean;
readonly onChange: (values: NumberFormatValues) => void;
readonly highlight: boolean;
readonly validatedSelection?: SelectionRange;
readonly fixedDecimals?: number;
readonly allowNegative?: boolean;
readonly thousandSeparator?: boolean | string;
readonly decimalSeparator?: string;
}
function getDecimalSeparator() {
const numberWithDecimalSeparator = 1.1;
const result = Intl.NumberFormat()
?.formatToParts(numberWithDecimalSeparator)
?.find(part => part.type === "decimal")?.value;
return result ?? ".";
}
function getThousandSeprator() {
return getDecimalSeparator() === "." ? "," : ".";
}
const NumberOverlayEditor: React.FunctionComponent<Props> = p => {
const { value, onChange, disabled, highlight, validatedSelection, fixedDecimals, allowNegative, thousandSeparator, decimalSeparator } = p;
const inputRef = React.useRef<HTMLInputElement>();
React.useLayoutEffect(() => {
if (validatedSelection !== undefined) {
const range = typeof validatedSelection === "number" ? [validatedSelection, null] : validatedSelection;
inputRef.current?.setSelectionRange(range[0], range[1]);
}
}, [validatedSelection]);
return (
<NumberOverlayEditorStyle>
<NumericFormat
autoFocus={true}
getInputRef={inputRef}
className="gdg-input"
onFocus={(e: React.FocusEvent<HTMLInputElement>) =>
e.target.setSelectionRange(highlight ? 0 : e.target.value.length, e.target.value.length)
}
disabled={disabled === true}
decimalScale={fixedDecimals}
allowNegative={allowNegative}
thousandSeparator={thousandSeparator ?? getThousandSeprator()}
decimalSeparator={decimalSeparator ?? getDecimalSeparator()}
value={Object.is(value, -0) ? "-" : value ?? ""}
// decimalScale={3}
// prefix={"$"}
onValueChange={onChange}
/>
</NumberOverlayEditorStyle>
);
};
export default NumberOverlayEditor;