Files
fleet/frontend/components/forms/fields/AutoSizeInputField/AutoSizeInputField.tsx
T
Gabriel Hernandez 443153a5d5 UI polish and style fixes for query pages (#8643)
* polish manage query page styles

* fix pencil icon spacing on query and policy edit form

* increase gutter style for edtior

* truncate long table names in table dropdown on query sidebar

* add change file
2022-11-10 11:00:06 +00:00

111 lines
2.6 KiB
TypeScript

import React, {
ChangeEvent,
KeyboardEvent,
useEffect,
useRef,
useState,
} from "react";
import classnames from "classnames";
interface IAutoSizeInputFieldProps {
name: string;
placeholder: string;
value: string;
inputClassName?: string;
maxLength: string;
hasError?: boolean;
isDisabled?: boolean;
isFocused?: boolean;
/** The minimum number of columns the input is. This is ignored if the input
* has a value. Useful if you'd like to show placeholder text without the
* input cutting off the text. defaults to `12` */
minColumns?: number;
onFocus: () => void;
onBlur: () => void;
onChange: (newSelectedValue: string) => void;
onKeyPress: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
}
const baseClass = "component__auto-size-input-field";
const AutoSizeInputField = ({
name,
placeholder,
value,
inputClassName,
maxLength,
hasError,
isDisabled,
isFocused,
minColumns = 12,
onFocus,
onBlur,
onChange,
onKeyPress,
}: IAutoSizeInputFieldProps): JSX.Element => {
const [inputValue, setInputValue] = useState(value);
const inputClasses = classnames(baseClass, inputClassName, "no-hover", {
[`${baseClass}--disabled`]: isDisabled,
[`${baseClass}--error`]: hasError,
[`${baseClass}__textarea`]: true,
});
const inputElement = useRef<any>(null);
useEffect(() => {
onChange(inputValue);
}, [inputValue]);
useEffect(() => {
if (isFocused && inputElement.current) {
inputElement.current.focus();
inputElement.current.selectionStart = inputValue.length;
inputElement.current.selectionEnd = inputValue.length;
}
}, [isFocused]);
const onInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
setInputValue(event.currentTarget.value);
};
const onInputFocus = () => {
isFocused = true;
onFocus();
};
const onInputBlur = () => {
isFocused = false;
onBlur();
};
const onInputKeyPress = (event: KeyboardEvent<HTMLTextAreaElement>) => {
onKeyPress(event);
};
return (
<div className={baseClass}>
<label className="input-sizer" data-value={inputValue} htmlFor={name}>
<textarea
name={name}
id={name}
onChange={onInputChange}
placeholder={placeholder}
value={inputValue}
maxLength={parseInt(maxLength, 10)}
className={inputClasses}
cols={value ? 1 : minColumns}
rows={1}
tabIndex={0}
onFocus={onInputFocus}
onBlur={onInputBlur}
onKeyPress={onInputKeyPress}
ref={inputElement}
/>
</label>
</div>
);
};
export default AutoSizeInputField;