From 51bd7e9ced2bfaa19e219ac4699a459767f8bb28 Mon Sep 17 00:00:00 2001 From: Adam Haeger Date: Thu, 5 Dec 2024 12:36:34 +0100 Subject: [PATCH] Preventing paste when readOnly is true on input component (#2774) * preventing paste when readOnly is true --- src/app-components/Input/Input.tsx | 10 +++++++++- src/layout/Input/InputComponent.test.tsx | 22 +++++++++++++++++++++- src/layout/Input/InputComponent.tsx | 4 +++- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/app-components/Input/Input.tsx b/src/app-components/Input/Input.tsx index b459a21e55..99521a2620 100644 --- a/src/app-components/Input/Input.tsx +++ b/src/app-components/Input/Input.tsx @@ -34,7 +34,13 @@ export type InputProps = { >; export function Input(props: InputProps) { - const { size = 'sm', ...rest } = props; + const { size = 'sm', readOnly, ...rest } = props; + + const handlePaste = (event: React.ClipboardEvent) => { + if (readOnly) { + event.preventDefault(); + } + }; if (props.textonly) { const { value, id, className } = props; @@ -56,7 +62,9 @@ export function Input(props: InputProps) { return ( ); diff --git a/src/layout/Input/InputComponent.test.tsx b/src/layout/Input/InputComponent.test.tsx index b6ae34e268..50f761daf6 100644 --- a/src/layout/Input/InputComponent.test.tsx +++ b/src/layout/Input/InputComponent.test.tsx @@ -167,13 +167,33 @@ describe('InputComponent', () => { expect(inputComponent).toHaveValue(formattedValue); }); + it('should prevent pasting when readOnly is true', async () => { + const initialValue = 'initial value'; + await render({ + component: { + readOnly: true, + }, + queries: { + fetchFormData: () => Promise.resolve({ some: { field: initialValue } }), + }, + }); + + const inputComponent = screen.getByRole('textbox') as HTMLInputElement; + expect(inputComponent).toHaveValue(initialValue); + + await userEvent.click(inputComponent); + + await userEvent.paste('pasted text'); + + expect(inputComponent).toHaveValue(initialValue); + }); + const render = async ({ component, ...rest }: Partial> = {}) => await renderGenericComponentTest({ type: 'Input', renderer: (props) => , component: { id: 'mock-id', - readOnly: false, required: false, dataModelBindings: { simpleBinding: { dataType: defaultDataTypeMock, field: 'some.field' }, diff --git a/src/layout/Input/InputComponent.tsx b/src/layout/Input/InputComponent.tsx index 22ff674f7a..7d47a6ec56 100644 --- a/src/layout/Input/InputComponent.tsx +++ b/src/layout/Input/InputComponent.tsx @@ -97,7 +97,6 @@ export const InputVariant = ({ node, overrideDisplay }: Pick