Files
fleet/frontend/components/forms/fields/AutoSizeInputField/AutoSizeInputField.tsx
T
jacobshandlingandJacob Shandling 841a425bb0 UI – Display whitespace of existing, trim names on create/update of team and query names (#22524)
## #22212

- Trim whitespace from names on field blur, form submit, and in API
calls when:
   - Creating a team
   - Updating a team
   - Creating a query
   - Updating a query
- Refactor `AutoResizeInputField` to remove its internal state-based
management of its value, leaving its `value` prop as the single source
of truth for the field's value at all times.

[Loom
demo](https://www.loom.com/share/882f4a803b1540db985c987adbd9f441?sid=67caf100-4711-41a3-971f-bc8f67beeae7)

- [x] Changes file added for user-visible changes in `changes/`, 
- [x] Manual QA for all new/changed functionality

---------

Co-authored-by: Jacob Shandling <jacob@fleetdm.com>
2024-10-03 15:59:10 -07:00

94 lines
2.2 KiB
TypeScript

import React, { KeyboardEvent, useEffect, useRef } from "react";
import classnames from "classnames";
interface IAutoSizeInputFieldProps {
name: string;
placeholder: string;
value: string;
inputClassName?: string;
maxLength: number;
hasError?: boolean;
isDisabled?: boolean;
isFocused?: boolean;
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,
onFocus = () => null,
onBlur = () => null,
onChange,
onKeyPress,
}: IAutoSizeInputFieldProps): JSX.Element => {
const inputClasses = classnames(baseClass, inputClassName, "no-hover", {
[`${baseClass}--disabled`]: isDisabled,
[`${baseClass}--error`]: hasError,
[`${baseClass}__textarea`]: true,
});
const inputElement = useRef<any>(null);
useEffect(() => {
if (isFocused && inputElement.current) {
inputElement.current.focus();
inputElement.current.selectionStart = value.length;
inputElement.current.selectionEnd = value.length;
}
}, [isFocused]);
const onInputFocus = () => {
isFocused = true;
onFocus();
};
const onInputBlur = () => {
isFocused = false;
onBlur();
};
const onInputKeyPress = (event: KeyboardEvent<HTMLTextAreaElement>) => {
onKeyPress(event);
};
const onInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
onChange(event.target.value);
};
return (
<div className={baseClass}>
<label className="input-sizer" data-value={value} htmlFor={name}>
<textarea
name={name}
id={name}
onChange={onInputChange}
placeholder={placeholder}
value={value}
maxLength={maxLength}
className={inputClasses}
cols={1}
rows={1}
tabIndex={0}
onFocus={onInputFocus}
onBlur={onInputBlur}
onKeyPress={onInputKeyPress}
ref={inputElement}
/>
</label>
</div>
);
};
export default AutoSizeInputField;