From e0481ca1a661f5e27880582b2ca2ccb4ae814bf3 Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Tue, 17 Mar 2026 10:46:48 +0530 Subject: [PATCH 1/8] added scribble component in vanilla components --- .../src/components/Scribble.tsx | 600 ++++++++++++++++++ 1 file changed, 600 insertions(+) create mode 100644 packages/react-vanilla-components/src/components/Scribble.tsx diff --git a/packages/react-vanilla-components/src/components/Scribble.tsx b/packages/react-vanilla-components/src/components/Scribble.tsx new file mode 100644 index 00000000..3da2443d --- /dev/null +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -0,0 +1,600 @@ +// ******************************************************************************* +// * Copyright 2026 Adobe +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. + +// * The BEM markup is as per the AEM core form components guidelines. +// * LINK- https://github.com/adobe/aem-core-forms-components/blob/master/ui.af.apps/src/main/content/jcr_root/apps/core/fd/components/form/scribble/v1/scribble/scribble.html +// ****************************************************************************** + +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { withRuleEngine } from '../utils/withRuleEngine'; +import { PROPS } from '../utils/type'; + +import FieldWrapper from './common/FieldWrapper'; + +const BRUSH_SIZES = [2, 3, 4, 5, 6, 7, 8, 9, 10]; +const BEM = 'cmp-adaptiveform-scribble'; + +const Scribble = (props: PROPS) => { + const { id, label, value, enabled, visible, required, valid, appliedCssClassNames, properties } = props; + + const dialogLabel = properties?.['fd:dialogLabel'] || 'Please sign here'; + const placeholder = (props as any).placeholder || 'Type Your Signature Here'; + + const canvasRef = useRef(null); + const geoCanvasRef = useRef(null); + const keyboardInputRef = useRef(null); + const modalRef = useRef(null); + + const [modalOpen, setModalOpen] = useState(false); + const [signatureDataUrl, setSignatureDataUrl] = useState( + typeof value === 'string' ? value : null + ); + const [brushSize, setBrushSize] = useState(3); + const [showBrushList, setShowBrushList] = useState(false); + const [textMode, setTextMode] = useState(false); + const [message, setMessage] = useState(''); + const [hasContent, setHasContent] = useState(false); + const [showClearConfirm, setShowClearConfirm] = useState(false); + + const drawingRef = useRef(false); + const brushSizeRef = useRef(brushSize); + + useEffect(() => { + brushSizeRef.current = brushSize; + }, [brushSize]); + + useEffect(() => { + if (typeof value === 'string' && value !== signatureDataUrl) { + setSignatureDataUrl(value || null); + } + }, [value]); + + const showTemporaryMessage = useCallback((msg: string) => { + setMessage(msg); + const timer = setTimeout(() => setMessage(''), 15000); + return () => clearTimeout(timer); + }, []); + + const initCanvas = useCallback(() => { + const canvas = canvasRef.current; + if (!canvas) {return;} + const dpr = window.devicePixelRatio || 1; + const rect = canvas.getBoundingClientRect(); + canvas.width = rect.width * dpr; + canvas.height = rect.height * dpr; + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (ctx) { + ctx.scale(dpr, dpr); + ctx.lineWidth = brushSizeRef.current; + ctx.lineCap = 'round'; + ctx.lineJoin = 'round'; + ctx.strokeStyle = '#000'; + } + }, []); + + useEffect(() => { + if (modalOpen && !textMode) { + requestAnimationFrame(() => { + initCanvas(); + }); + } + }, [modalOpen, textMode, initCanvas]); + + useEffect(() => { + if (modalOpen && modalRef.current) { + modalRef.current.focus(); + } + }, [modalOpen]); + + useEffect(() => { + if (modalOpen) { + const originalOverflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + return () => { + document.body.style.overflow = originalOverflow; + }; + } + }, [modalOpen]); + + const getCoordinates = (e: React.MouseEvent | React.TouchEvent): { x: number; y: number } | null => { + const canvas = canvasRef.current; + if (!canvas) {return null;} + const rect = canvas.getBoundingClientRect(); + if ('touches' in e && e.touches.length > 0) { + const touch = e.touches[0]; + return { x: touch.clientX - rect.left, y: touch.clientY - rect.top }; + } else if ('clientX' in e) { + return { x: e.clientX - rect.left, y: e.clientY - rect.top }; + } + return null; + }; + + const startDrawing = useCallback((e: React.MouseEvent | React.TouchEvent) => { + e.preventDefault(); + const coords = getCoordinates(e); + if (!coords) {return;} + const canvas = canvasRef.current; + const ctx = canvas?.getContext('2d', { willReadFrequently: true }); + if (!ctx) {return;} + ctx.lineWidth = brushSizeRef.current; + ctx.beginPath(); + ctx.moveTo(coords.x, coords.y); + drawingRef.current = true; + }, []); + + const draw = useCallback((e: React.MouseEvent | React.TouchEvent) => { + e.preventDefault(); + if (!drawingRef.current) {return;} + const coords = getCoordinates(e); + if (!coords) {return;} + const canvas = canvasRef.current; + const ctx = canvas?.getContext('2d', { willReadFrequently: true }); + if (!ctx) {return;} + ctx.lineTo(coords.x, coords.y); + ctx.stroke(); + setHasContent(true); + }, []); + + const stopDrawing = useCallback(() => { + if (!drawingRef.current) {return;} + const ctx = canvasRef.current?.getContext('2d', { willReadFrequently: true }); + if (ctx) {ctx.closePath();} + drawingRef.current = false; + }, []); + + const eraseCanvas = useCallback(() => { + const canvas = canvasRef.current; + if (canvas) { + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (ctx) {ctx.clearRect(0, 0, canvas.width, canvas.height);} + } + const geoCanvas = geoCanvasRef.current; + if (geoCanvas) { + const geoCtx = geoCanvas.getContext('2d'); + if (geoCtx) {geoCtx.clearRect(0, 0, geoCanvas.width, geoCanvas.height);} + geoCanvas.width = 0; + geoCanvas.height = 0; + } + if (keyboardInputRef.current) { + keyboardInputRef.current.value = ''; + } + setHasContent(false); + setTextMode(false); + }, []); + + const buildDataUrl = useCallback((): string | null => { + const sigCanvas = canvasRef.current; + if (!sigCanvas) {return null;} + + const geoCanvas = geoCanvasRef.current; + const hasGeo = geoCanvas && geoCanvas.width > 0 && geoCanvas.height > 0; + + if (hasGeo) { + const merged = document.createElement('canvas'); + merged.width = Math.max(sigCanvas.width, geoCanvas!.width); + merged.height = sigCanvas.height + geoCanvas!.height; + const ctx = merged.getContext('2d'); + if (!ctx) {return null;} + ctx.drawImage(sigCanvas, 0, 0); + ctx.drawImage(geoCanvas!, 0, sigCanvas.height); + return merged.toDataURL('image/png').replace( + 'data:image/png;base64,', + 'data:image/png;name=fd_type_signature.png;base64,' + ); + } + + return sigCanvas.toDataURL('image/png').replace( + 'data:image/png;base64,', + 'data:image/png;name=fd_type_signature.png;base64,' + ); + }, []); + + const isCanvasEmpty = useCallback((): boolean => { + const canvas = canvasRef.current; + if (!canvas || canvas.width === 0 || canvas.height === 0) {return true;} + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (!ctx) {return true;} + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + for (let i = 0; i < imageData.data.length; i += 4) { + if (imageData.data[i + 3] > 0) {return false;} + } + return true; + }, []); + + const handleSave = useCallback(() => { + if (textMode) { + const textVal = keyboardInputRef.current?.value; + if (!textVal) {return;} + const canvas = canvasRef.current; + if (!canvas) {return;} + canvas.style.display = ''; + initCanvas(); + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + if (!ctx) {return;} + const rect = canvas.getBoundingClientRect(); + const fontFamily = 'sans-serif, Georgia'; + const fontStyle = 'italic'; + let fontSize = 10; + ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`; + let textWidth = ctx.measureText(textVal).width; + while (fontSize > 1 && textWidth > rect.width) { + fontSize -= 0.5; + ctx.font = `${fontStyle} ${fontSize}rem ${fontFamily}`; + textWidth = ctx.measureText(textVal).width; + } + ctx.fillText(textVal, 0, rect.height / 2); + } + + if (isCanvasEmpty()) {return;} + + const dataUrl = buildDataUrl(); + if (dataUrl) { + setSignatureDataUrl(dataUrl); + props.dispatchChange(dataUrl); + } + setModalOpen(false); + setTextMode(false); + setShowBrushList(false); + setMessage(''); + }, [textMode, isCanvasEmpty, buildDataUrl, initCanvas, props.dispatchChange]); + + const handleClose = useCallback(() => { + eraseCanvas(); + setModalOpen(false); + setTextMode(false); + setShowBrushList(false); + setMessage(''); + }, [eraseCanvas]); + + useEffect(() => { + const handleEscape = (e: KeyboardEvent) => { + if (e.key === 'Escape' && modalOpen) { + handleClose(); + } + }; + if (modalOpen) { + document.addEventListener('keydown', handleEscape); + return () => document.removeEventListener('keydown', handleEscape); + } + }, [modalOpen, handleClose]); + + const handleClearSignature = useCallback(() => { + setShowClearConfirm(true); + }, []); + + const handleConfirmClear = useCallback(() => { + setSignatureDataUrl(null); + props.dispatchChange(undefined); + eraseCanvas(); + setShowClearConfirm(false); + }, [eraseCanvas, props.dispatchChange]); + + const handleCancelClear = useCallback(() => { + setShowClearConfirm(false); + }, []); + + const handleTextSign = useCallback(() => { + eraseCanvas(); + setTextMode(true); + }, [eraseCanvas]); + + const handleBrushMode = useCallback(() => { + if (textMode) { + eraseCanvas(); + setTextMode(false); + requestAnimationFrame(() => initCanvas()); + } + setShowBrushList(prev => !prev); + }, [textMode, eraseCanvas, initCanvas]); + + const handleSelectBrush = useCallback((size: number) => { + setBrushSize(size); + brushSizeRef.current = size; + setShowBrushList(false); + }, []); + + const handleGeolocation = useCallback(() => { + if (!navigator.geolocation) { + showTemporaryMessage('Geolocation is not supported by this browser.'); + return; + } + showTemporaryMessage('Fetching geolocation...'); + navigator.geolocation.getCurrentPosition( + (position) => { + setMessage(''); + const { latitude, longitude } = position.coords; + const dateObj = new Date(); + const tZone = (dateObj.getTimezoneOffset() / 60) * -1; + const latStr = `Latitude: ${latitude}`; + const longStr = `Longitude: ${longitude}`; + const timeStr = `${dateObj.getTime()}: ${dateObj.getMonth() + 1}/${dateObj.getDate()}/${dateObj.getFullYear()} ${dateObj.getHours()}:${dateObj.getMinutes()}:${dateObj.getSeconds()}${tZone > 0 ? ' +' : ' '}${tZone}`; + + const geoCanvas = geoCanvasRef.current; + if (geoCanvas) { + geoCanvas.style.display = 'block'; + geoCanvas.width = 200; + geoCanvas.height = 50; + const ctx = geoCanvas.getContext('2d'); + if (ctx) { + ctx.font = 'bold 10px Arial'; + ctx.fillStyle = 'black'; + ctx.fillText(latStr, 0, 15); + ctx.fillText(longStr, 0, 30); + ctx.fillText(timeStr, 0, 45); + } + } + }, + (error) => { + let errorMsg = 'Error fetching geolocation.'; + switch (error.code) { + case error.PERMISSION_DENIED: + errorMsg = 'Location permission denied. Please allow location access.'; + break; + case error.POSITION_UNAVAILABLE: + errorMsg = 'Location unavailable. Please check GPS/network.'; + break; + case error.TIMEOUT: + errorMsg = 'Location request timed out. Please try again.'; + break; + } + showTemporaryMessage(errorMsg); + }, + { timeout: 10000 } + ); + }, [showTemporaryMessage]); + + const handleKeyboardInput = useCallback(() => { + const val = keyboardInputRef.current?.value; + setHasContent(!!val); + }, []); + + const openModal = useCallback(() => { + if (!enabled) {return;} + setModalOpen(true); + setHasContent(false); + setTextMode(false); + setShowBrushList(false); + setMessage(''); + }, [enabled]); + + const isFilled = !!signatureDataUrl; + + return ( +
+ +
+ {signatureDataUrl ? ( + Signature + ) : null} + + {signatureDataUrl && enabled && ( +
+ + {showClearConfirm && ( +
+
+ Erase Current Signature? +
+
+
+ This will permanently remove the signature you've drawn. Do you wish to proceed and begin again? +
+
+
+ + +
+
+ )} +
+ + {modalOpen && ( +
+
+ {dialogLabel} +
+
+
+
+ + {textMode && ( + + )} +
+ +
+ +
+
+
+ +
+ + +
+
+
+
+ )} + +
+ ); +}; + +export default withRuleEngine(Scribble); \ No newline at end of file From 6eade1cc6476b597d0fa3086fd2d03700cac99b4 Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Tue, 17 Mar 2026 10:49:24 +0530 Subject: [PATCH 2/8] added scribble in mappings --- packages/react-vanilla-components/src/index.ts | 2 ++ packages/react-vanilla-components/src/utils/mappings.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/react-vanilla-components/src/index.ts b/packages/react-vanilla-components/src/index.ts index 223fc90f..8e414725 100644 --- a/packages/react-vanilla-components/src/index.ts +++ b/packages/react-vanilla-components/src/index.ts @@ -29,6 +29,7 @@ import Form from './components/Form'; import mappings from './utils/mappings'; import ReCaptcha from './components/ReCaptcha'; import Image from './components/Image'; +import Scribble from './components/Scribble'; export * from './utils/withRuleEngine'; export * from './utils/type'; @@ -56,5 +57,6 @@ export { TelephoneInput, ReCaptcha, Image, + Scribble, Form }; diff --git a/packages/react-vanilla-components/src/utils/mappings.ts b/packages/react-vanilla-components/src/utils/mappings.ts index c792d930..614df5aa 100644 --- a/packages/react-vanilla-components/src/utils/mappings.ts +++ b/packages/react-vanilla-components/src/utils/mappings.ts @@ -37,6 +37,7 @@ import Switch from '../components/Switch'; import ReCaptcha from '../components/ReCaptcha'; import HCaptcha from '../components/HCaptcha'; import Image from '../components/Image'; +import Scribble from '../components/Scribble'; const mappings = { 'text-input': TextField, @@ -62,6 +63,7 @@ const mappings = { 'core/fd/components/form/hcaptcha/v1/hcaptcha': HCaptcha, captcha: ReCaptcha, image: Image, + signature: Scribble, form: Form }; From 8e77b92c79b208b6a310c30ea6ede64c50f89812 Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Tue, 17 Mar 2026 16:06:36 +0530 Subject: [PATCH 3/8] added testcases for the scribble component --- .../__tests__/components/Scribble.test.tsx | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 packages/react-vanilla-components/__tests__/components/Scribble.test.tsx diff --git a/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx b/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx new file mode 100644 index 00000000..8b080df6 --- /dev/null +++ b/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx @@ -0,0 +1,276 @@ +/* + * Copyright 2023 Adobe, Inc. + * + * Your access and use of this software is governed by the Adobe Customer Feedback Program Terms and Conditions or other Beta License Agreement signed by your employer and Adobe, Inc.. This software is NOT open source and may not be used without one of the foregoing licenses. Even with a foregoing license, your access and use of this file is limited to the earlier of (a) 180 days, (b) general availability of the product(s) which utilize this software (i.e. AEM Forms), (c) January 1, 2023, (d) Adobe providing notice to you that you may no longer use the software or that your beta trial has otherwise ended. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ADOBE NOR ITS THIRD PARTY PROVIDERS AND PARTNERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +import Scribble from '../../src/components/Scribble'; +import { renderComponent } from '../utils'; +import userEvent from '@testing-library/user-event'; +import '@testing-library/jest-dom/extend-expect'; + +const BEM = 'cmp-adaptiveform-scribble'; + +/** Mock canvas 2d context and element so isCanvasEmpty() returns false and toDataURL works in JSDOM */ +function mockCanvas2D() { + const imageData = new Uint8ClampedArray(4); + imageData[3] = 255; + const mockCtx = { + scale: jest.fn(), + clearRect: jest.fn(), + beginPath: jest.fn(), + moveTo: jest.fn(), + lineTo: jest.fn(), + stroke: jest.fn(), + closePath: jest.fn(), + fillText: jest.fn(), + drawImage: jest.fn(), + getImageData: jest.fn(() => ({ data: imageData })), + measureText: jest.fn(() => ({ width: 50 })), + lineWidth: 0, + lineCap: '', + lineJoin: '', + strokeStyle: '', + font: '', + fillStyle: '', + }; + const dataUrl = 'data:image/png;name=fd_type_signature.png;base64,mock'; + const getContext = HTMLCanvasElement.prototype.getContext; + const getBoundingClientRect = HTMLCanvasElement.prototype.getBoundingClientRect; + const toDataURL = HTMLCanvasElement.prototype.toDataURL; + HTMLCanvasElement.prototype.getContext = jest.fn(function (this: HTMLCanvasElement, type: string) { + if (type === '2d') return mockCtx as any; + return getContext.call(this, type as any); + }); + HTMLCanvasElement.prototype.getBoundingClientRect = jest.fn(() => ({ width: 200, height: 100, top: 0, left: 0, right: 200, bottom: 100, x: 0, y: 0, toJSON: () => ({}) })); + HTMLCanvasElement.prototype.toDataURL = jest.fn(() => dataUrl); + return () => { + HTMLCanvasElement.prototype.getContext = getContext; + HTMLCanvasElement.prototype.getBoundingClientRect = getBoundingClientRect; + HTMLCanvasElement.prototype.toDataURL = toDataURL; + }; +} +const IS = 'adaptiveFormScribble'; + +const field = { + name: 'scribble', + id: 'scribble-1', + visible: true, + enabled: true, + required: false, + valid: true, + label: { + value: 'Sign here', + }, + description: 'Please provide your signature.', + fieldType: 'scribble', + properties: { + 'fd:dialogLabel': 'Please sign here', + }, +}; + +const helper = renderComponent(Scribble); + +describe('Scribble', () => { + test('should render scribble field with label and container', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + expect(renderResponse.getByText(f.label.value)).toBeInTheDocument(); + const container = renderResponse.container.querySelector(`.${BEM}`); + expect(container).toBeInTheDocument(); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + expect(signedContainer).toBeInTheDocument(); + }); + + test('should have correct data attributes', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const scribble = renderResponse.container.querySelector(`[data-cmp-is="${IS}"]`); + expect(scribble).toBeInTheDocument(); + expect(scribble).toHaveAttribute('data-cmp-is', IS); + expect(scribble).toHaveAttribute('data-cmp-visible', 'true'); + expect(scribble).toHaveAttribute('data-cmp-enabled', 'true'); + }); + + test('should open the scribble modal when signed container is clicked', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + expect(signedContainer).toBeInTheDocument(); + userEvent.click(signedContainer!); + const modal = renderResponse.container.querySelector(`.${BEM}__container`); + expect(modal).toBeInTheDocument(); + expect(modal).toBeVisible(); + }); + + test('modal should have correct accessibility attributes when open', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + const modal = renderResponse.container.querySelector(`.${BEM}__container`); + expect(modal).toHaveAttribute('role', 'dialog'); + expect(modal).toHaveAttribute('aria-label', f.properties['fd:dialogLabel']); + expect(modal).toHaveAttribute('aria-modal', 'true'); + const canvas = renderResponse.container.querySelector(`.${BEM}__canvas`); + expect(canvas).toHaveAttribute('aria-label', 'Signature canvas'); + }); + + test('label should have for attribute linking to widget', async () => { + const f = { ...field, id: 'scribble-field-1' }; + const { renderResponse } = await helper(f); + const label = renderResponse.getByText(f.label.value); + expect(label).toHaveAttribute('for'); + const labelFor = label.getAttribute('for'); + expect(labelFor).toBeTruthy(); + }); + + test('should close the modal when close button is clicked', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + expect(renderResponse.container.querySelector(`.${BEM}__container`)).toBeInTheDocument(); + const closeButton = renderResponse.getByRole('button', { name: 'Close' }); + userEvent.click(closeButton); + expect(renderResponse.container.querySelector(`.${BEM}__container`)).not.toBeInTheDocument(); + }); + + test('should clear the signature content when clear is clicked in text mode', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + const textSignButton = renderResponse.getByRole('button', { name: 'Text sign' }); + userEvent.click(textSignButton); + const textInput = renderResponse.getByRole('textbox', { name: 'Signature text' }); + expect(textInput).toHaveValue(''); + await userEvent.type(textInput, 'test'); + expect(textInput).toHaveValue('test'); + const clearButton = renderResponse.getByRole('button', { name: 'Clear' }); + expect(clearButton).toBeEnabled(); + userEvent.click(clearButton); + expect(textInput).toHaveValue(''); + }); + + test('should not clear signature when clear is cancelled, then clear when confirmed', async () => { + const restore = mockCanvas2D(); + try { + const f = { ...field }; + const { renderResponse, element } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + const textSignButton = renderResponse.getByRole('button', { name: 'Text sign' }); + userEvent.click(textSignButton); + const textInput = renderResponse.getByRole('textbox', { name: 'Signature text' }); + await userEvent.type(textInput, 'test'); + const saveButton = renderResponse.getByRole('button', { name: 'Save' }); + userEvent.click(saveButton); + + const signedImage = renderResponse.container.querySelector(`.${BEM}__canvas-signed-image`); + expect(signedImage).toBeInTheDocument(); + expect(signedImage).toHaveAttribute('src'); + expect(signedImage).toHaveAttribute('alt', 'Signature'); + + const clearSignButton = renderResponse.getByRole('button', { name: 'Clear Signature' }); + expect(clearSignButton).toBeInTheDocument(); + userEvent.click(clearSignButton); + + const confirmDialog = renderResponse.container.querySelector(`.${BEM}__clearsign-container`); + expect(confirmDialog).toBeVisible(); + expect(confirmDialog).toHaveAttribute('aria-label', 'Erase Current Signature?'); + + const cancelButton = renderResponse.getByRole('button', { name: 'Cancel' }); + userEvent.click(cancelButton); + expect(renderResponse.container.querySelector(`.${BEM}__clearsign-container`)).not.toBeInTheDocument(); + expect(renderResponse.container.querySelector(`.${BEM}__canvas-signed-image`)).toBeInTheDocument(); + expect(renderResponse.container.querySelector(`.${BEM}__canvas-signed-image`)?.getAttribute('src')).toBeTruthy(); + + userEvent.click(clearSignButton); + const confirmClearButton = renderResponse.getByRole('button', { name: 'Clear' }); + userEvent.click(confirmClearButton); + expect(renderResponse.container.querySelector(`.${BEM}__clear-sign`)).not.toBeInTheDocument(); + expect(renderResponse.container.querySelector(`.${BEM}__canvas-signed-image`)).not.toBeInTheDocument(); + expect(element?.value == null).toBe(true); + } finally { + restore(); + } + }); + + test('should display brush list with correct accessibility when brush button is clicked', async () => { + const f = { ...field }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + expect(renderResponse.container.querySelector(`.${BEM}__brushlist`)).not.toBeInTheDocument(); + + const brushButton = renderResponse.getByRole('button', { name: 'Brushes' }); + userEvent.click(brushButton); + const brushListVisible = renderResponse.container.querySelector(`.${BEM}__brushlist`); + expect(brushListVisible).toBeInTheDocument(); + expect(brushListVisible).toHaveAttribute('aria-label', 'Brush size selection'); + const brushCanvases = renderResponse.container.querySelectorAll(`.${BEM}__brushlist canvas`); + brushCanvases.forEach((canvas, index) => { + const size = [2, 3, 4, 5, 6, 7, 8, 9, 10][index]; + expect(canvas).toHaveAttribute('aria-label', `Brush size ${size}`); + }); + + userEvent.click(brushButton); + expect(renderResponse.container.querySelector(`.${BEM}__brushlist`)).not.toBeInTheDocument(); + }); + + test('text sign flow: type text and save updates model and shows signed image', async () => { + const restore = mockCanvas2D(); + try { + const f = { ...field }; + const { renderResponse, element } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + expect(renderResponse.getByRole('button', { name: 'Save' })).toBeDisabled(); + const textSignButton = renderResponse.getByRole('button', { name: 'Text sign' }); + userEvent.click(textSignButton); + const textInput = renderResponse.getByRole('textbox', { name: 'Signature text' }); + await userEvent.type(textInput, 'My Signature'); + const saveButton = renderResponse.getByRole('button', { name: 'Save' }); + expect(saveButton).toBeEnabled(); + userEvent.click(saveButton); + expect(renderResponse.container.querySelector(`.${BEM}__container`)).not.toBeInTheDocument(); + expect(renderResponse.container.querySelector(`.${BEM}__canvas-signed-image`)).toBeInTheDocument(); + const dataUrl = element?.value; + expect(typeof dataUrl).toBe('string'); + expect(dataUrl).toMatch(/^data:image\/png;name=fd_type_signature\.png;base64/); + } finally { + restore(); + } + }); + + test('should not render when visible is false', async () => { + const f = { ...field, visible: false }; + const { renderResponse } = await helper(f); + const scribble = renderResponse.container.querySelector(`[data-cmp-is="${IS}"]`); + expect(scribble).not.toBeInTheDocument(); + }); + + test('should not open modal when disabled', async () => { + const f = { ...field, enabled: false }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + expect(renderResponse.container.querySelector(`.${BEM}__container`)).not.toBeInTheDocument(); + }); + + test('should use custom dialog label from properties', async () => { + const f = { + ...field, + properties: { 'fd:dialogLabel': 'Custom sign dialog' }, + }; + const { renderResponse } = await helper(f); + const signedContainer = renderResponse.container.querySelector(`.${BEM}__canvas-signed-container`); + userEvent.click(signedContainer!); + const modal = renderResponse.container.querySelector(`.${BEM}__container`); + expect(modal).toHaveAttribute('aria-label', 'Custom sign dialog'); + expect(renderResponse.getByRole('heading', { name: 'Custom sign dialog' })).toBeInTheDocument(); + }); +}); From e609e66decd3d73e163d49ba5d036d39e136ae47 Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Fri, 27 Mar 2026 10:46:07 +0530 Subject: [PATCH 4/8] updated year to 2026 --- .../__tests__/components/Scribble.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx b/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx index 8b080df6..040e3f8b 100644 --- a/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx +++ b/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx @@ -1,5 +1,5 @@ /* - * Copyright 2023 Adobe, Inc. + * Copyright 2026 Adobe, Inc. * * Your access and use of this software is governed by the Adobe Customer Feedback Program Terms and Conditions or other Beta License Agreement signed by your employer and Adobe, Inc.. This software is NOT open source and may not be used without one of the foregoing licenses. Even with a foregoing license, your access and use of this file is limited to the earlier of (a) 180 days, (b) general availability of the product(s) which utilize this software (i.e. AEM Forms), (c) January 1, 2023, (d) Adobe providing notice to you that you may no longer use the software or that your beta trial has otherwise ended. * From 775abf05232630eccf42ef291d2f8b406a23decb Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Fri, 27 Mar 2026 12:46:37 +0530 Subject: [PATCH 5/8] FORMS-24462: Address Scribble PR review (types, a11y, timers, perf) - Use typed placeholder and destructured dispatchChange (no any cast) - Sync signature from value via functional setState; only when value is string - Clear message timers on unmount and when dismissing messages manually - Track canvas strokes with canvasDrawnRef to skip full-pixel isCanvasEmpty scan - Add aria-level on dialog header; keyboard-accessible signed area (role=button) - Associate label with id-widget on signed container; avoid nested buttons Made-with: Cursor --- .../src/components/Scribble.tsx | 79 ++++++++++++++++--- 1 file changed, 67 insertions(+), 12 deletions(-) diff --git a/packages/react-vanilla-components/src/components/Scribble.tsx b/packages/react-vanilla-components/src/components/Scribble.tsx index 3da2443d..422785b9 100644 --- a/packages/react-vanilla-components/src/components/Scribble.tsx +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -27,15 +27,29 @@ const BRUSH_SIZES = [2, 3, 4, 5, 6, 7, 8, 9, 10]; const BEM = 'cmp-adaptiveform-scribble'; const Scribble = (props: PROPS) => { - const { id, label, value, enabled, visible, required, valid, appliedCssClassNames, properties } = props; + const { + id, + label, + value, + enabled, + visible, + required, + valid, + appliedCssClassNames, + properties, + placeholder: placeholderProp, + dispatchChange, + } = props; const dialogLabel = properties?.['fd:dialogLabel'] || 'Please sign here'; - const placeholder = (props as any).placeholder || 'Type Your Signature Here'; + const placeholder = placeholderProp || 'Type Your Signature Here'; const canvasRef = useRef(null); const geoCanvasRef = useRef(null); const keyboardInputRef = useRef(null); const modalRef = useRef(null); + const messageTimerRef = useRef | null>(null); + const canvasDrawnRef = useRef(false); const [modalOpen, setModalOpen] = useState(false); const [signatureDataUrl, setSignatureDataUrl] = useState( @@ -56,15 +70,28 @@ const Scribble = (props: PROPS) => { }, [brushSize]); useEffect(() => { - if (typeof value === 'string' && value !== signatureDataUrl) { - setSignatureDataUrl(value || null); + if (typeof value === 'string') { + const next = value || null; + setSignatureDataUrl((prev) => (prev === next ? prev : next)); } }, [value]); + const clearMessageTimer = () => { + if (messageTimerRef.current != null) { + clearTimeout(messageTimerRef.current); + messageTimerRef.current = null; + } + }; + + useEffect(() => () => clearMessageTimer(), []); + const showTemporaryMessage = useCallback((msg: string) => { + clearMessageTimer(); setMessage(msg); - const timer = setTimeout(() => setMessage(''), 15000); - return () => clearTimeout(timer); + messageTimerRef.current = setTimeout(() => { + messageTimerRef.current = null; + setMessage(''); + }, 15000); }, []); const initCanvas = useCallback(() => { @@ -144,6 +171,7 @@ const Scribble = (props: PROPS) => { if (!ctx) {return;} ctx.lineTo(coords.x, coords.y); ctx.stroke(); + canvasDrawnRef.current = true; setHasContent(true); }, []); @@ -172,6 +200,7 @@ const Scribble = (props: PROPS) => { } setHasContent(false); setTextMode(false); + canvasDrawnRef.current = false; }, []); const buildDataUrl = useCallback((): string | null => { @@ -202,6 +231,7 @@ const Scribble = (props: PROPS) => { }, []); const isCanvasEmpty = useCallback((): boolean => { + if (canvasDrawnRef.current) {return false;} const canvas = canvasRef.current; if (!canvas || canvas.width === 0 || canvas.height === 0) {return true;} const ctx = canvas.getContext('2d', { willReadFrequently: true }); @@ -235,6 +265,7 @@ const Scribble = (props: PROPS) => { textWidth = ctx.measureText(textVal).width; } ctx.fillText(textVal, 0, rect.height / 2); + canvasDrawnRef.current = true; } if (isCanvasEmpty()) {return;} @@ -242,19 +273,21 @@ const Scribble = (props: PROPS) => { const dataUrl = buildDataUrl(); if (dataUrl) { setSignatureDataUrl(dataUrl); - props.dispatchChange(dataUrl); + dispatchChange(dataUrl); } setModalOpen(false); setTextMode(false); setShowBrushList(false); + clearMessageTimer(); setMessage(''); - }, [textMode, isCanvasEmpty, buildDataUrl, initCanvas, props.dispatchChange]); + }, [textMode, isCanvasEmpty, buildDataUrl, initCanvas, dispatchChange]); const handleClose = useCallback(() => { eraseCanvas(); setModalOpen(false); setTextMode(false); setShowBrushList(false); + clearMessageTimer(); setMessage(''); }, [eraseCanvas]); @@ -276,10 +309,10 @@ const Scribble = (props: PROPS) => { const handleConfirmClear = useCallback(() => { setSignatureDataUrl(null); - props.dispatchChange(undefined); + dispatchChange(undefined); eraseCanvas(); setShowClearConfirm(false); - }, [eraseCanvas, props.dispatchChange]); + }, [eraseCanvas, dispatchChange]); const handleCancelClear = useCallback(() => { setShowClearConfirm(false); @@ -313,6 +346,7 @@ const Scribble = (props: PROPS) => { showTemporaryMessage('Fetching geolocation...'); navigator.geolocation.getCurrentPosition( (position) => { + clearMessageTimer(); setMessage(''); const { latitude, longitude } = position.coords; const dateObj = new Date(); @@ -366,6 +400,8 @@ const Scribble = (props: PROPS) => { setHasContent(false); setTextMode(false); setShowBrushList(false); + canvasDrawnRef.current = false; + clearMessageTimer(); setMessage(''); }, [enabled]); @@ -389,7 +425,26 @@ const Scribble = (props: PROPS) => { isError={props.isError} errorMessage={props.errorMessage} > -
+
enabled && openModal()} + onKeyDown={(e) => { + if (!enabled) {return;} + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + openModal(); + } + }} + > {signatureDataUrl ? ( { ref={modalRef} style={{ display: 'block' }} > -
+
{dialogLabel}
From 79c9b69bf1a14a9ff99c79cdc4b6d1f04c77c1bc Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Fri, 27 Mar 2026 12:57:45 +0530 Subject: [PATCH 6/8] FORMS-24462: Zero-pad geo timestamp; newline at EOF (PR review) Made-with: Cursor --- .../react-vanilla-components/src/components/Scribble.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/react-vanilla-components/src/components/Scribble.tsx b/packages/react-vanilla-components/src/components/Scribble.tsx index 422785b9..efa32da6 100644 --- a/packages/react-vanilla-components/src/components/Scribble.tsx +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -351,9 +351,10 @@ const Scribble = (props: PROPS) => { const { latitude, longitude } = position.coords; const dateObj = new Date(); const tZone = (dateObj.getTimezoneOffset() / 60) * -1; + const pad2 = (n: number) => String(n).padStart(2, '0'); const latStr = `Latitude: ${latitude}`; const longStr = `Longitude: ${longitude}`; - const timeStr = `${dateObj.getTime()}: ${dateObj.getMonth() + 1}/${dateObj.getDate()}/${dateObj.getFullYear()} ${dateObj.getHours()}:${dateObj.getMinutes()}:${dateObj.getSeconds()}${tZone > 0 ? ' +' : ' '}${tZone}`; + const timeStr = `${dateObj.getTime()}: ${pad2(dateObj.getMonth() + 1)}/${pad2(dateObj.getDate())}/${dateObj.getFullYear()} ${pad2(dateObj.getHours())}:${pad2(dateObj.getMinutes())}:${pad2(dateObj.getSeconds())}${tZone > 0 ? ' +' : ' '}${tZone}`; const geoCanvas = geoCanvasRef.current; if (geoCanvas) { @@ -652,4 +653,4 @@ const Scribble = (props: PROPS) => { ); }; -export default withRuleEngine(Scribble); \ No newline at end of file +export default withRuleEngine(Scribble); From d8b718e0baee876879f8c4f0a0dd25c51b57b488 Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Fri, 27 Mar 2026 15:36:39 +0530 Subject: [PATCH 7/8] code refactoring --- packages/react-vanilla-components/src/components/Scribble.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-vanilla-components/src/components/Scribble.tsx b/packages/react-vanilla-components/src/components/Scribble.tsx index efa32da6..80ca59e4 100644 --- a/packages/react-vanilla-components/src/components/Scribble.tsx +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -38,7 +38,7 @@ const Scribble = (props: PROPS) => { appliedCssClassNames, properties, placeholder: placeholderProp, - dispatchChange, + dispatchChange } = props; const dialogLabel = properties?.['fd:dialogLabel'] || 'Please sign here'; From ebf12501fb7539e0407400de877935d8c820a1ab Mon Sep 17 00:00:00 2001 From: Armaan Gupta Date: Sat, 28 Mar 2026 18:29:21 +0530 Subject: [PATCH 8/8] code refactoring --- .../src/components/Scribble.tsx | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/packages/react-vanilla-components/src/components/Scribble.tsx b/packages/react-vanilla-components/src/components/Scribble.tsx index 80ca59e4..7a3666ba 100644 --- a/packages/react-vanilla-components/src/components/Scribble.tsx +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -27,19 +27,7 @@ const BRUSH_SIZES = [2, 3, 4, 5, 6, 7, 8, 9, 10]; const BEM = 'cmp-adaptiveform-scribble'; const Scribble = (props: PROPS) => { - const { - id, - label, - value, - enabled, - visible, - required, - valid, - appliedCssClassNames, - properties, - placeholder: placeholderProp, - dispatchChange - } = props; + const { id, label, value, enabled, visible, required, valid, appliedCssClassNames, properties, placeholder: placeholderProp, dispatchChange } = props; const dialogLabel = properties?.['fd:dialogLabel'] || 'Please sign here'; const placeholder = placeholderProp || 'Type Your Signature Here';