-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Number.tsx
97 lines (83 loc) · 2.52 KB
/
Number.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
import type { FC, ChangeEvent } from 'react';
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { styled } from '@storybook/theming';
import { Form } from '@storybook/components';
import { getControlId, getControlSetterButtonId } from './helpers';
import type { ControlProps, NumberValue, NumberConfig } from './types';
const Wrapper = styled.label({
display: 'flex',
});
type NumberProps = ControlProps<NumberValue | null> & NumberConfig;
export const parse = (value: string) => {
const result = parseFloat(value);
return Number.isNaN(result) ? undefined : result;
};
export const format = (value: NumberValue) => (value != null ? String(value) : '');
export const NumberControl: FC<NumberProps> = ({
name,
value,
onChange,
min,
max,
step,
onBlur,
onFocus,
}) => {
const [inputValue, setInputValue] = useState(typeof value === 'number' ? value : '');
const [forceVisible, setForceVisible] = useState(false);
const [parseError, setParseError] = useState<Error>(null);
const handleChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
const result = parseFloat(event.target.value);
if (Number.isNaN(result)) {
setParseError(new Error(`'${event.target.value}' is not a number`));
} else {
onChange(result);
setParseError(null);
}
},
[onChange, setParseError]
);
const onForceVisible = useCallback(() => {
setInputValue('0');
onChange(0);
setForceVisible(true);
}, [setForceVisible]);
const htmlElRef = useRef(null);
useEffect(() => {
if (forceVisible && htmlElRef.current) htmlElRef.current.select();
}, [forceVisible]);
useEffect(() => {
const newInputValue = typeof value === 'number' ? value : '';
if (inputValue !== newInputValue) {
setInputValue(value);
}
if (!value && newInputValue === '') {
setForceVisible(false);
}
}, [value]);
if (!forceVisible && value === undefined) {
return (
<Form.Button id={getControlSetterButtonId(name)} onClick={onForceVisible}>
Set number
</Form.Button>
);
}
return (
<Wrapper>
<Form.Input
ref={htmlElRef}
id={getControlId(name)}
type="number"
onChange={handleChange}
size="flex"
placeholder="Edit number..."
value={inputValue}
valid={parseError ? 'error' : null}
autoFocus={forceVisible}
{...{ name, min, max, step, onFocus, onBlur }}
/>
</Wrapper>
);
};