diff --git a/packages/grafana-ui/src/components/Input/AutoSizeInput.test.tsx b/packages/grafana-ui/src/components/Input/AutoSizeInput.test.tsx index f3372a6045d..148f35c6af3 100644 --- a/packages/grafana-ui/src/components/Input/AutoSizeInput.test.tsx +++ b/packages/grafana-ui/src/components/Input/AutoSizeInput.test.tsx @@ -58,6 +58,23 @@ describe('AutoSizeInput', () => { expect(getComputedStyle(inputWrapper).width).toBe('304px'); }); + it('should use placeholder for width if input is empty', () => { + render(); + + const inputWrapper: HTMLDivElement = screen.getByTestId('input-wrapper'); + expect(getComputedStyle(inputWrapper).width).toBe('304px'); + }); + + it('should use value for width even with a placeholder', () => { + render(); + + 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(); diff --git a/packages/grafana-ui/src/components/Input/AutoSizeInput.tsx b/packages/grafana-ui/src/components/Input/AutoSizeInput.tsx index 7d8eccee748..b6899a4caa3 100644 --- a/packages/grafana-ui/src/components/Input/AutoSizeInput.tsx +++ b/packages/grafana-ui/src/components/Input/AutoSizeInput.tsx @@ -24,6 +24,7 @@ export const AutoSizeInput = React.forwardRef((props, r onKeyDown, onBlur, value: controlledValue, + placeholder, ...restProps } = props; // Initialize internal state @@ -36,13 +37,16 @@ export const AutoSizeInput = React.forwardRef((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 ( {