| Total Complexity | 7 |
| Complexity/F | 3.5 |
| Lines of Code | 87 |
| Function Count | 2 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | import React, { Component } from "react"; |
||
| 2 | import _ from "lodash"; |
||
| 3 | import Input, { InputProps } from "./Input"; |
||
| 4 | |||
| 5 | export interface UpdatingInputProps extends InputProps { |
||
| 6 | updateDelay?: number | null; |
||
| 7 | handleSave: () => void; |
||
| 8 | } |
||
| 9 | |||
| 10 | export interface UpdatingInputState { |
||
| 11 | updateDelay: number | null | undefined; |
||
| 12 | } |
||
| 13 | |||
| 14 | class UpdatingInput extends Component<UpdatingInputProps, UpdatingInputState> { |
||
| 15 | public constructor(props) { |
||
| 16 | super(props); |
||
| 17 | |||
| 18 | const { updateDelay } = this.props; |
||
| 19 | |||
| 20 | if (updateDelay) { |
||
| 21 | const bounceDelay: number = updateDelay; |
||
| 22 | this.state = { |
||
| 23 | updateDelay: bounceDelay, |
||
| 24 | }; |
||
| 25 | // Lodash's debounce doesn't work properly if imported |
||
| 26 | // by itself... something to do with how it handles 'this' |
||
| 27 | this.triggerSave = _.debounce(this.triggerSave, bounceDelay); |
||
| 28 | } |
||
| 29 | } |
||
| 30 | |||
| 31 | public triggerSave(): void { |
||
| 32 | const { value, minLength, handleSave } = this.props; |
||
| 33 | if (value !== undefined) { |
||
| 34 | if ( |
||
| 35 | value.toString().length > (minLength || 3) || |
||
| 36 | value.toString().length === 0 |
||
| 37 | ) { |
||
| 38 | handleSave(); |
||
| 39 | } |
||
| 40 | } |
||
| 41 | } |
||
| 42 | |||
| 43 | public render(): React.ReactElement { |
||
| 44 | const { |
||
| 45 | id, |
||
| 46 | name, |
||
| 47 | label, |
||
| 48 | required, |
||
| 49 | placeholder, |
||
| 50 | type, |
||
| 51 | value, |
||
| 52 | onChange, |
||
| 53 | errorText, |
||
| 54 | handleSave, |
||
| 55 | minLength, |
||
| 56 | maxLength, |
||
| 57 | } = this.props; |
||
| 58 | return ( |
||
| 59 | <Input |
||
| 60 | id={id} |
||
| 61 | name={name} |
||
| 62 | label={label} |
||
| 63 | required={required} |
||
| 64 | placeholder={placeholder} |
||
| 65 | type={type} |
||
| 66 | value={value} |
||
| 67 | minLength={minLength} |
||
| 68 | maxLength={maxLength} |
||
| 69 | onChange={(event: React.ChangeEvent<HTMLInputElement>): void => { |
||
| 70 | onChange(event); |
||
| 71 | if (this.state) { |
||
| 72 | const { updateDelay } = this.state; |
||
| 73 | |||
| 74 | if (updateDelay) { |
||
| 75 | this.triggerSave(); |
||
| 76 | } |
||
| 77 | } |
||
| 78 | }} |
||
| 79 | onBlur={handleSave} |
||
| 80 | errorText={errorText} |
||
| 81 | /> |
||
| 82 | ); |
||
| 83 | } |
||
| 84 | } |
||
| 85 | |||
| 86 | export default UpdatingInput; |
||
| 87 |