|
| 1 | +import * as React from 'react'; |
| 2 | + |
| 3 | +const DEFAULT_REQUEST_TIMEOUT_IN_MS = 5000; |
| 4 | + |
| 5 | +const generateRandomID = () => { |
| 6 | + return Math.random().toString(36).substring(2, 15); |
| 7 | +}; |
| 8 | + |
| 9 | +export type EmbedActions = { |
| 10 | + submit: (options: { downloadCopyOnDevice: boolean }) => Promise<Result['data']['result']>; |
| 11 | + selectTool: ( |
| 12 | + toolType: 'TEXT' | 'BOXED_TEXT' | 'CHECKBOX' | 'PICTURE' | 'SIGNATURE' | null, |
| 13 | + ) => Promise<Result['data']['result']>; |
| 14 | +}; |
| 15 | + |
| 16 | +export type EventPayload = { |
| 17 | + type: string; |
| 18 | + data: unknown; |
| 19 | +}; |
| 20 | + |
| 21 | +export function sendEvent(iframe: HTMLIFrameElement, payload: EventPayload) { |
| 22 | + const requestId = generateRandomID(); |
| 23 | + return new Promise<Result['data']['result']>((resolve) => { |
| 24 | + try { |
| 25 | + const handleMessage = (event: MessageEvent<string>) => { |
| 26 | + const parsedEvent: Result = (() => { |
| 27 | + try { |
| 28 | + const parsedEvent = JSON.parse(event.data); |
| 29 | + |
| 30 | + if (parsedEvent.type !== 'REQUEST_RESULT') { |
| 31 | + return { |
| 32 | + data: { |
| 33 | + request_id: null, |
| 34 | + }, |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + return parsedEvent; |
| 39 | + } catch (e) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + })(); |
| 43 | + const isTargetIframe = event.source === iframe.contentWindow; |
| 44 | + const isMatchingResponse = parsedEvent.data.request_id === requestId; |
| 45 | + |
| 46 | + if (isTargetIframe && isMatchingResponse) { |
| 47 | + resolve(parsedEvent.data.result); |
| 48 | + window.removeEventListener('message', handleMessage); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + window.addEventListener('message', handleMessage); |
| 53 | + |
| 54 | + iframe.contentWindow?.postMessage(JSON.stringify({ ...payload, request_id: requestId }), '*'); |
| 55 | + |
| 56 | + const timeoutId = setTimeout(() => { |
| 57 | + resolve({ |
| 58 | + success: false, |
| 59 | + error: { |
| 60 | + code: 'unexpected:request_timed_out', |
| 61 | + message: 'The request timed out: try again', |
| 62 | + }, |
| 63 | + } satisfies Result['data']['result']); |
| 64 | + window.removeEventListener('message', handleMessage); |
| 65 | + }, DEFAULT_REQUEST_TIMEOUT_IN_MS); |
| 66 | + |
| 67 | + const cleanup = () => clearTimeout(timeoutId); |
| 68 | + window.addEventListener('message', cleanup); |
| 69 | + } catch (e) { |
| 70 | + const error = e as Error; |
| 71 | + resolve({ |
| 72 | + success: false, |
| 73 | + error: { |
| 74 | + code: 'unexpected:failed_processing_request', |
| 75 | + message: `The following error happened: ${error.name}:${error.message}`, |
| 76 | + }, |
| 77 | + }); |
| 78 | + } |
| 79 | + }); |
| 80 | +} |
| 81 | + |
| 82 | +type ErrorCodePrefix = 'bad_request' | 'unexpected'; |
| 83 | + |
| 84 | +type Result = { |
| 85 | + type: 'REQUEST_RESULT'; |
| 86 | + data: { |
| 87 | + request_id: string; |
| 88 | + result: |
| 89 | + | { success: true } |
| 90 | + | { |
| 91 | + success: false; |
| 92 | + error: { code: `${ErrorCodePrefix}:${string}`; message: string }; |
| 93 | + }; |
| 94 | + }; |
| 95 | +}; |
| 96 | + |
| 97 | +export const useEmbed = (): { embedRef: React.RefObject<EmbedRefHandlers | null>; actions: EmbedActions } => { |
| 98 | + const embedRef = React.useRef<EmbedRefHandlers>(null); |
| 99 | + |
| 100 | + const handleSubmit: EmbedRefHandlers['submit'] = React.useCallback( |
| 101 | + async ({ downloadCopyOnDevice }): Promise<Result['data']['result']> => { |
| 102 | + if (embedRef.current === null) { |
| 103 | + return Promise.resolve({ |
| 104 | + success: false as const, |
| 105 | + error: { |
| 106 | + code: 'bad_request:embed_ref_not_available' as const, |
| 107 | + message: 'embedRef is not available: make sure to pass embedRef to the <Embed /> component', |
| 108 | + }, |
| 109 | + }); |
| 110 | + } |
| 111 | + |
| 112 | + const result = await embedRef.current.submit({ downloadCopyOnDevice }); |
| 113 | + |
| 114 | + return result; |
| 115 | + }, |
| 116 | + [], |
| 117 | + ); |
| 118 | + |
| 119 | + const handleSelectTool: EmbedRefHandlers['selectTool'] = React.useCallback( |
| 120 | + async (toolType): Promise<Result['data']['result']> => { |
| 121 | + if (embedRef.current === null) { |
| 122 | + return Promise.resolve({ |
| 123 | + success: false as const, |
| 124 | + error: { |
| 125 | + code: 'bad_request:embed_ref_not_available' as const, |
| 126 | + message: 'embedRef is not available: make sure to pass embedRef to the <Embed /> component', |
| 127 | + }, |
| 128 | + }); |
| 129 | + } |
| 130 | + |
| 131 | + const result = await embedRef.current.selectTool(toolType); |
| 132 | + |
| 133 | + return result; |
| 134 | + }, |
| 135 | + [], |
| 136 | + ); |
| 137 | + |
| 138 | + return { |
| 139 | + embedRef, |
| 140 | + actions: { |
| 141 | + submit: handleSubmit, |
| 142 | + selectTool: handleSelectTool, |
| 143 | + }, |
| 144 | + }; |
| 145 | +}; |
| 146 | + |
| 147 | +export type EmbedRefHandlers = EmbedActions; |
0 commit comments