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..040e3f8b --- /dev/null +++ b/packages/react-vanilla-components/__tests__/components/Scribble.test.tsx @@ -0,0 +1,276 @@ +/* + * 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. + * + * 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(); + }); +}); 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..7a3666ba --- /dev/null +++ b/packages/react-vanilla-components/src/components/Scribble.tsx @@ -0,0 +1,644 @@ +// ******************************************************************************* +// * 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, placeholder: placeholderProp, dispatchChange } = props; + + const dialogLabel = properties?.['fd:dialogLabel'] || 'Please sign 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( + 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') { + 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); + messageTimerRef.current = setTimeout(() => { + messageTimerRef.current = null; + setMessage(''); + }, 15000); + }, []); + + 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(); + canvasDrawnRef.current = true; + 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); + canvasDrawnRef.current = 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 => { + 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 }); + 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); + canvasDrawnRef.current = true; + } + + if (isCanvasEmpty()) {return;} + + const dataUrl = buildDataUrl(); + if (dataUrl) { + setSignatureDataUrl(dataUrl); + dispatchChange(dataUrl); + } + setModalOpen(false); + setTextMode(false); + setShowBrushList(false); + clearMessageTimer(); + setMessage(''); + }, [textMode, isCanvasEmpty, buildDataUrl, initCanvas, dispatchChange]); + + const handleClose = useCallback(() => { + eraseCanvas(); + setModalOpen(false); + setTextMode(false); + setShowBrushList(false); + clearMessageTimer(); + 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); + dispatchChange(undefined); + eraseCanvas(); + setShowClearConfirm(false); + }, [eraseCanvas, 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) => { + clearMessageTimer(); + setMessage(''); + 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()}: ${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) { + 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); + canvasDrawnRef.current = false; + clearMessageTimer(); + setMessage(''); + }, [enabled]); + + const isFilled = !!signatureDataUrl; + + return ( +
+ +
enabled && openModal()} + onKeyDown={(e) => { + if (!enabled) {return;} + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + openModal(); + } + }} + > + {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); 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 };