-
Notifications
You must be signed in to change notification settings - Fork 126
/
Input.tsx
540 lines (475 loc) · 15.1 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import invariant from 'invariant';
import React from 'react';
import raf from 'raf';
import cn from 'classnames';
import { isIE11, isEdge } from '../../lib/client';
import { isKeyBackspace, isKeyDelete, someKeys } from '../../lib/events/keyboard/identifiers';
import { polyfillPlaceholder } from '../../lib/polyfillPlaceholder';
import { Nullable, Override } from '../../typings/utility-types';
import { MaskedInput } from '../../internal/MaskedInput';
import { ThemeContext } from '../../lib/theming/ThemeContext';
import { Theme } from '../../lib/theming/Theme';
import { CommonWrapper, CommonProps, CommonWrapperRestProps } from '../../internal/CommonWrapper';
import { jsStyles } from './Input.styles';
export type InputSize = 'small' | 'medium' | 'large';
export type InputAlign = 'left' | 'center' | 'right';
export type InputType = 'password' | 'text';
export type InputIconType = React.ReactNode | (() => React.ReactNode);
export interface InputProps
extends CommonProps,
Override<
React.InputHTMLAttributes<HTMLInputElement>,
{
/**
* Иконка слева
* Если `ReactNode` применяются дефолтные стили для иконки
* Если `() => ReactNode` применяются только стили для позиционирование
*/
leftIcon?: InputIconType;
/**
* Иконка справа
* Если `ReactNode` применяются дефолтные стили для иконки
* Если `() => ReactNode` применяются только стили для позиционирование
*/
rightIcon?: InputIconType;
/** Состояние ошибки */
error?: boolean;
/** Состояние предупреждения */
warning?: boolean;
/** Режим прозрачной рамки */
borderless?: boolean;
/** Выравнивание текста */
align?: InputAlign;
/** Паттерн маски */
mask?: Nullable<string>;
/** Символ маски */
maskChar?: Nullable<string>;
/**
* Словарь символов-регулярок для задания маски
* @default { '9': '[0-9]', 'a': '[A-Za-z]', '*': '[A-Za-z0-9]' }
*/
formatChars?: Record<string, string>;
/** Показывать символы маски */
alwaysShowMask?: boolean;
/** Размер */
size?: InputSize;
/** onValueChange */
onValueChange?: (value: string) => void;
/** Вызывается на label */
onMouseEnter?: React.MouseEventHandler<HTMLLabelElement>;
/** Вызывается на label */
onMouseLeave?: React.MouseEventHandler<HTMLLabelElement>;
/** Вызывается на label */
onMouseOver?: React.MouseEventHandler<HTMLLabelElement>;
/** Тип */
type?: InputType;
/** Значение */
value?: string;
capture?: boolean;
/**
* Префикс
* `ReactNode` перед значением, но после иконки
*/
prefix?: React.ReactNode;
/**
* Суффикс
* `ReactNode` после значения, но перед правой иконкой
*/
suffix?: React.ReactNode;
/** Выделять введенное значение при фокусе */
selectAllOnFocus?: boolean;
/**
* Обработчик неправильного ввода.
* По-умолчанию, инпут вспыхивает синим.
* Если передан - вызывается переданный обработчик,
* в таком случае вспыхивание можно вызвать
* публичным методом инстанса `blink()`.
*
* @param value значение инпута.
*/
onUnexpectedInput?: (value: string) => void;
}
> {}
export interface InputState {
blinking: boolean;
focused: boolean;
polyfillPlaceholder: boolean;
}
/**
* Интерфес пропсов наследуется от `React.InputHTMLAttributes<HTMLInputElement>`.
* Все пропсы кроме перечисленных, `className` и `style` передаются в `<input>`
*/
export class Input extends React.Component<InputProps, InputState> {
public static __KONTUR_REACT_UI__ = 'Input';
public static defaultProps: {
size: InputSize;
} = {
size: 'small',
};
public state: InputState = {
polyfillPlaceholder: false,
blinking: false,
focused: false,
};
private selectAllId: number | null = null;
private theme!: Theme;
private blinkTimeout = 0;
private input: HTMLInputElement | null = null;
public componentDidMount() {
if (polyfillPlaceholder) {
this.setState({ polyfillPlaceholder: true });
}
}
public componentWillUnmount() {
if (this.blinkTimeout) {
clearTimeout(this.blinkTimeout);
}
this.cancelDelayedSelectAll();
}
public UNSAFE_componentWillReceiveProps(nextProps: InputProps) {
if (polyfillPlaceholder && !nextProps.value) {
this.setState({ polyfillPlaceholder: true });
}
}
/**
* @public
*/
public focus() {
invariant(this.input, 'Cannot call "focus" because Input is not mounted');
this.input!.focus();
}
/**
* @public
*/
public blur() {
invariant(this.input, 'Cannot call "blur" because Input is not mounted');
this.input!.blur();
}
/**
* @public
*/
public blink() {
if (this.blinkTimeout) {
this.cancelBlink(() => {
// trigger reflow to restart animation
// @see https://css-tricks.com/restart-css-animation/#article-header-id-0
void (this.input && this.input.offsetWidth);
this.blink();
});
return;
}
this.setState({ blinking: true }, () => {
this.blinkTimeout = window.setTimeout(this.cancelBlink, 150);
});
}
/**
* @public
*/
public setSelectionRange(start: number, end: number) {
if (!this.input) {
throw new Error('Cannot call "setSelectionRange" on unmounted Input');
}
if (document.activeElement !== this.input) {
this.focus();
}
this.input.setSelectionRange(start, end);
}
public get isMaskVisible(): boolean {
const { mask, alwaysShowMask } = this.props;
const { focused } = this.state;
return Boolean(mask && (focused || alwaysShowMask));
}
public render(): JSX.Element {
return (
<ThemeContext.Consumer>
{theme => {
this.theme = theme;
return <CommonWrapper {...this.props}>{this.renderMain}</CommonWrapper>;
}}
</ThemeContext.Consumer>
);
}
/**
* @public
*/
public selectAll = (): void => {
if (this.input) {
this.setSelectionRange(0, this.input.value.length);
}
};
private delaySelectAll = (): number => (this.selectAllId = raf(this.selectAll));
private cancelDelayedSelectAll = (): void => {
if (this.selectAllId) {
raf.cancel(this.selectAllId);
this.selectAllId = null;
}
};
private cancelBlink = (callback?: () => void): void => {
if (this.blinkTimeout) {
clearTimeout(this.blinkTimeout);
this.blinkTimeout = 0;
if (this.state.blinking) {
this.setState({ blinking: false }, callback);
return;
}
}
if (callback) {
callback();
}
};
private renderMain = (props: CommonWrapperRestProps<InputProps>) => {
const {
onMouseEnter,
onMouseLeave,
onMouseOver,
onKeyDown,
onKeyPress,
onValueChange,
width,
error,
warning,
leftIcon,
rightIcon,
borderless,
value,
align,
type,
mask,
maskChar,
alwaysShowMask,
size,
placeholder,
selectAllOnFocus,
disabled,
onUnexpectedInput,
prefix,
suffix,
formatChars,
...rest
} = props;
const { blinking, focused } = this.state;
const labelProps = {
className: cn(jsStyles.root(this.theme), this.getSizeClassName(), {
[jsStyles.borderless()]: !!borderless,
[jsStyles.focus(this.theme)]: focused,
[jsStyles.blink(this.theme)]: !!blinking,
[jsStyles.warning(this.theme)]: !!warning,
[jsStyles.error(this.theme)]: !!error,
[jsStyles.disabled(this.theme)]: !!disabled,
[jsStyles.focusFallback(this.theme)]: focused && (isIE11 || isEdge),
[jsStyles.warningFallback(this.theme)]: !!warning && (isIE11 || isEdge),
[jsStyles.errorFallback(this.theme)]: !!error && (isIE11 || isEdge),
}),
style: { width },
onMouseEnter,
onMouseLeave,
onMouseOver,
};
const inputProps = {
...rest,
className: jsStyles.input(this.theme),
value,
onChange: this.handleChange,
onFocus: this.handleFocus,
onKeyDown: this.handleKeyDown,
onKeyPress: this.handleKeyPress,
onBlur: this.handleBlur,
style: { textAlign: align },
ref: this.refInput,
type: 'text',
placeholder: !this.isMaskVisible && !polyfillPlaceholder ? placeholder : undefined,
disabled,
};
if (type === 'password') {
inputProps.type = type;
}
const input = mask ? this.renderMaskedInput(inputProps, mask) : React.createElement('input', inputProps);
return (
<label {...labelProps}>
<span className={jsStyles.sideContainer()}>
{this.renderLeftIcon()}
{this.renderPrefix()}
</span>
<span className={jsStyles.wrapper()}>
{input}
{this.renderPlaceholder()}
</span>
<span className={cn(jsStyles.sideContainer(), jsStyles.rightContainer())}>
{this.renderSuffix()}
{this.renderRightIcon()}
</span>
</label>
);
};
private renderMaskedInput(
inputProps: React.InputHTMLAttributes<HTMLInputElement> & {
capture?: boolean;
},
mask: string,
) {
return (
<MaskedInput
{...inputProps}
mask={mask}
maskChar={this.props.maskChar}
alwaysShowMask={this.props.alwaysShowMask}
formatChars={this.props.formatChars}
onChange={this.props.onChange}
onValueChange={this.handleMaskedValueChange}
onUnexpectedInput={this.handleUnexpectedInput}
/>
);
}
private getIconSizeClassname(right = false) {
switch (this.props.size) {
case 'large':
return right ? jsStyles.rightIconLarge(this.theme) : jsStyles.leftIconLarge(this.theme);
case 'medium':
return right ? jsStyles.rightIconMedium(this.theme) : jsStyles.leftIconMedium(this.theme);
case 'small':
default:
return right ? jsStyles.rightIconSmall(this.theme) : jsStyles.leftIconSmall(this.theme);
}
}
private renderLeftIcon() {
return this.renderIcon(this.props.leftIcon, this.getIconSizeClassname());
}
private renderRightIcon() {
return this.renderIcon(this.props.rightIcon, this.getIconSizeClassname(true));
}
private renderIcon(icon: InputIconType, sizeClassName: string) {
if (!icon) {
return null;
}
if (icon instanceof Function) {
return <span className={cn(jsStyles.icon(), sizeClassName)}>{icon()}</span>;
}
return (
<span
className={cn(
cn(jsStyles.icon(), sizeClassName),
jsStyles.useDefaultColor(this.theme),
jsStyles.useDefaultColor(this.theme),
)}
>
{icon}
</span>
);
}
private renderPlaceholder() {
let placeholder = null;
if (this.state.polyfillPlaceholder && this.props.placeholder && !this.isMaskVisible && !this.props.value) {
placeholder = (
<div
className={cn(jsStyles.placeholder(this.theme), jsStyles.placeholder(this.theme))}
style={{ textAlign: this.props.align || 'inherit' }}
>
{this.props.placeholder}
</div>
);
}
return placeholder;
}
private getSizeClassName() {
switch (this.props.size) {
case 'large':
return {
[jsStyles.sizeLarge(this.theme)]: true,
[jsStyles.sizeLargeFallback(this.theme)]: isIE11 || isEdge,
};
case 'medium':
return {
[jsStyles.sizeMedium(this.theme)]: true,
[jsStyles.sizeMediumFallback(this.theme)]: isIE11 || isEdge,
};
case 'small':
default:
return {
[jsStyles.sizeSmall(this.theme)]: true,
[jsStyles.sizeSmallFallback(this.theme)]: isIE11 || isEdge,
};
}
}
private refInput = (element: HTMLInputElement | MaskedInput | null) => {
if (element instanceof MaskedInput) {
this.input = element.input;
} else {
this.input = element;
}
};
private handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (polyfillPlaceholder) {
const fieldIsEmpty = event.target.value === '';
if (this.state.polyfillPlaceholder !== fieldIsEmpty) {
this.setState({ polyfillPlaceholder: fieldIsEmpty });
}
}
if (this.props.onValueChange) {
this.props.onValueChange(event.target.value);
}
if (this.props.onChange) {
this.props.onChange(event);
}
};
private handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
this.setState({
focused: true,
});
if (this.props.selectAllOnFocus) {
// https://github.com/facebook/react/issues/7769
this.input && !isIE11 ? this.selectAll() : this.delaySelectAll();
}
if (this.props.onFocus) {
this.props.onFocus(event);
}
};
private handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
const isDeleteKey = someKeys(isKeyBackspace, isKeyDelete)(e);
if (!e.currentTarget.value && isDeleteKey && !e.repeat) {
this.handleUnexpectedInput();
}
};
private handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (this.props.onKeyPress) {
this.props.onKeyPress(event);
}
if (this.props.maxLength === event.currentTarget.value.length) {
this.handleUnexpectedInput(event.currentTarget.value);
}
};
private handleMaskedValueChange = (value: string) => {
if (this.props.onValueChange) {
this.props.onValueChange(value);
}
};
private handleUnexpectedInput = (value: string = this.props.value || '') => {
if (this.props.onUnexpectedInput) {
this.props.onUnexpectedInput(value);
} else {
this.blink();
}
};
private handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
this.setState({ focused: false });
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
private renderPrefix = () => {
const { prefix } = this.props;
if (!prefix) {
return null;
}
return <span className={jsStyles.prefix(this.theme)}>{prefix}</span>;
};
private renderSuffix = () => {
const { suffix } = this.props;
if (!suffix) {
return null;
}
return <span className={jsStyles.suffix(this.theme)}>{suffix}</span>;
};
}