From 9a4a17f3387b7a4929df6d83c154a031b4943e1c Mon Sep 17 00:00:00 2001 From: Josh Hunt Date: Fri, 15 Nov 2024 09:45:05 +0000 Subject: [PATCH] GrafanaUI: AutoSizeInput uses placeholder for width calculation (#96458) AutoSizeInput: Use placeholder for width calculation also --- .../src/components/Input/AutoSizeInput.test.tsx | 17 +++++++++++++++++ .../src/components/Input/AutoSizeInput.tsx | 8 ++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) 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 ( {