GrafanaUI: AutoSizeInput uses placeholder for width calculation (#96458)

AutoSizeInput: Use placeholder for width calculation also
This commit is contained in:
Josh Hunt 2024-11-15 09:45:05 +00:00 committed by GitHub
parent 65b50b67c4
commit 9a4a17f338
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 2 deletions

View File

@ -58,6 +58,23 @@ describe('AutoSizeInput', () => {
expect(getComputedStyle(inputWrapper).width).toBe('304px');
});
it('should use placeholder for width if input is empty', () => {
render(<AutoSizeInput placeholder="very very long value" />);
const inputWrapper: HTMLDivElement = screen.getByTestId('input-wrapper');
expect(getComputedStyle(inputWrapper).width).toBe('304px');
});
it('should use value for width even with a placeholder', () => {
render(<AutoSizeInput value="less long value" placeholder="very very long value" />);
const input: HTMLInputElement = screen.getByTestId('autosize-input');
const inputWrapper: HTMLDivElement = screen.getByTestId('input-wrapper');
fireEvent.change(input, { target: { value: 'very very long value' } });
expect(getComputedStyle(inputWrapper).width).toBe('304px');
});
it('should call onBlur if set when blurring', () => {
const onBlur = jest.fn();
const onCommitChange = jest.fn();

View File

@ -24,6 +24,7 @@ export const AutoSizeInput = React.forwardRef<HTMLInputElement, Props>((props, r
onKeyDown,
onBlur,
value: controlledValue,
placeholder,
...restProps
} = props;
// Initialize internal state
@ -36,13 +37,16 @@ export const AutoSizeInput = React.forwardRef<HTMLInputElement, Props>((props, r
// Update input width when `value`, `minWidth`, or `maxWidth` change
const inputWidth = useMemo(() => {
const valueString = typeof value === 'string' ? value : value.toString();
const displayValue = value || placeholder || '';
const valueString = typeof displayValue === 'string' ? displayValue : displayValue.toString();
return getWidthFor(valueString, minWidth, maxWidth);
}, [value, minWidth, maxWidth]);
}, [placeholder, value, minWidth, maxWidth]);
return (
<Input
{...restProps}
placeholder={placeholder}
ref={ref}
value={value.toString()}
onChange={(event) => {