forked from woowacourse-teams/2024-code-zap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInput.tsx
84 lines (66 loc) · 2.31 KB
/
Input.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
import {
Children,
HTMLAttributes,
InputHTMLAttributes,
isValidElement,
LabelHTMLAttributes,
PropsWithChildren,
ReactNode,
} from 'react';
import * as S from './Input.style';
export interface BaseProps extends HTMLAttributes<HTMLDivElement> {
size?: 'small' | 'medium';
variant?: 'filled' | 'outlined' | 'text';
isValid?: boolean;
}
export interface TextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
inputSize?: 'small' | 'medium';
}
export interface LabelProps extends LabelHTMLAttributes<HTMLLabelElement> {}
export interface AdornmentProps extends HTMLAttributes<HTMLDivElement> {}
export interface HelperTextProps extends HTMLAttributes<HTMLSpanElement> {}
const getChildOfType = (children: ReactNode, type: unknown) => {
const childrenArray = Children.toArray(children);
return childrenArray.find((child) => isValidElement(child) && child.type === type);
};
const getChildrenWithoutTypes = (children: ReactNode, types: unknown[]) => {
const childrenArray = Children.toArray(children);
return childrenArray.filter((child) => !(isValidElement(child) && types.includes(child.type)));
};
const TextField = ({ ...rests }: TextFieldProps) => <S.TextField {...rests} />;
const Label = ({ children, ...rests }: PropsWithChildren<LabelProps>) => <S.Label {...rests}>{children}</S.Label>;
const Adornment = ({ children, ...rests }: PropsWithChildren<AdornmentProps>) => (
<S.Adornment {...rests}>{children}</S.Adornment>
);
const HelperText = ({ children, ...rests }: PropsWithChildren<HelperTextProps>) => (
<S.HelperText {...rests}>{children}</S.HelperText>
);
const HelperTextType = (<HelperText />).type;
const LabelType = (<Label />).type;
const Base = ({
variant = 'filled',
size = 'medium',
isValid = true,
children,
...rests
}: PropsWithChildren<BaseProps>) => {
const inputWithAdornment = getChildrenWithoutTypes(children, [HelperTextType, LabelType]);
const helperText = getChildOfType(children, HelperTextType);
const label = getChildOfType(children, LabelType);
return (
<S.Container>
{label}
<S.Base variant={variant} size={size} isValid={isValid} {...rests}>
{inputWithAdornment}
</S.Base>
{helperText}
</S.Container>
);
};
const Input = Object.assign(Base, {
TextField,
Label,
Adornment,
HelperText,
});
export default Input;