-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.tsx
334 lines (308 loc) · 12 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import React from "react";
import { DefaultConfigs, FileMetaData, PreviewFileConfig, ReactViewAdobeProps } from "./types";
import AdobeDiv from "./AdobeDiv";
export {DefaultConfigs, FileMetaData, PreviewFileConfig, ReactViewAdobeProps} from "./types";
/**
* Renders the embedded Adobe PDF viewer using the Adobe Embed API.
*
* This function is particularly useful when using the `LIGHT_BOX` embed mode, where the PDF viewer
* is intended to be triggered by a user interaction, such as clicking a button or link. In `LIGHT_BOX`
* mode, the viewer typically occupies the entire screen and does not render by default on page load.
*
* ### Usage:
* ```tsx
* previewFile({
* divId: "pdf-viewer",
* viewerConfig: { embedMode: "LIGHT_BOX", showAnnotationTools: true },
* url: "https://example.com/sample.pdf",
* clientID: "your-client-id",
* _fileMeta: { fileName: "Sample.pdf", id: "unique-id" },
* });
* ```
*
* @param {Object} params - Parameters for rendering the PDF.
* @param {string} params.divId - The ID of the container div where the PDF viewer will be embedded.
* @param {Partial<PreviewFileConfig>} params.viewerConfig - Configuration options for the PDF viewer.
* @param {string} params.url - The URL of the PDF file to be rendered.
* @param {string} params.clientID - The client ID for accessing the Adobe Embed API.
* @param {Partial<FileMetaData>} [params._fileMeta] - Optional metadata for the PDF, such as file name and ID.
* @param {any} [params._dcView] - Optional pre-existing AdobeDC.View instance to reuse. If not provided, a new instance will be created.
*
* @returns A promise that resolves when the PDF is successfully rendered.
*/
export function previewFile({
divId,
viewerConfig,
url,
clientID,
_fileMeta,
_dcView,
}: {
divId: string;
viewerConfig: Partial<PreviewFileConfig>;
url: string;
clientID: string;
_dcView?: any;
_fileMeta?: Partial<FileMetaData>;
}) {
const config = {
clientId: clientID,
divId,
};
const dcView = _dcView || new (window as any).AdobeDC.View(config);
const previewFilePromise = dcView.previewFile(
{
content: {
location: {
url: url,
},
},
metaData: _fileMeta || DefaultConfigs.demoMetaData,
},
viewerConfig,
);
return previewFilePromise as Promise<any>;
}
export function log({
message,
prefix = "ReactViewAdobe",
type = "info",
}: {message: string, prefix: string, type: 'info' | 'warn' | 'error'}) {
// format the message and better colors, prefix in bold
const formattedMessage = `\x1b[1m${prefix}\x1b[0m: ${message}`;
// log the message to the console add prefix in bold
console[type](formattedMessage);
}
/**
* ReactViewAdobe
*
* A React component that acts as a wrapper around the Adobe PDF Viewer SDK, enabling seamless rendering of PDFs using Adobe's Embed API services.
* This component is designed to encapsulate and compartmentalize the Adobe Embed API's logic within the React lifecycle, providing robust
* configurability and dynamic behavior through customizable React hooks and props.
*
* ### Features:
* - Supports multiple embed modes (`LIGHT_BOX`, `FULL_WINDOW`, `SIZED_CONTAINER`, `IN_LINE`).
* - Dynamically loads the Adobe Embed SDK script into the DOM if not already present.
* - Enables advanced configurations for rendering, such as annotations, zoom controls, and fullscreen toggles.
* - Offers hooks-based extensibility to customize behavior when loading, rendering, or updating the component.
* - Provides detailed debug logging for development.
*
* @param {ReactViewAdobeProps} props - The properties for the ReactViewAdobe component.
* @property {string} url - The URL of the PDF to render. (Required)
* @property {string} clientId - The Adobe Embed API client ID. (Required)
* @property {Partial<PreviewFileConfig>} [previewConfig] - Configuration options for the Adobe Viewer (e.g., zoom controls, annotations).
* @property {Partial<FileMetaData>} [fileMeta] - Metadata for the PDF (e.g., file name, ID).
* @property {string} [id] - The ID for the PDF container element in the DOM.
* @property {React.ReactNode} [children] - Any child components to render inside the wrapper.
* @property {string} [className] - CSS class for styling the container.
* @property {string} [title] - Title for the container, typically used for accessibility.
* @property {React.CSSProperties} [style] - Inline styles for the container.
* @property {boolean} [debug] - Enables detailed logging for debugging purposes.
* @property {ReactHooks} [useReactHookWhenLoadingAdobeAPI] - Hook for managing the lifecycle of script loading (default: `useEffect`). Do not use unless necessary and you understand the implications.
* @property {ReactHooks} [useReactHookWhenCallingAdobeAPI] - Hook for managing API calls to Adobe services (default: `useEffect`). Do not use unless necessary and you understand the implications.
* @property {ReactHooks} [useReactHookForComponentDidUpdate] - Hook for managing component updates and re-renders (default: `useEffect`). Do not use unless necessary and you understand the implications.
* @property {boolean} [triggerAdobeDCViewRender] - Flag to trigger the rendering of the PDF, especially for `LIGHT_BOX` mode.
*
* @example
* ```tsx
* import { ReactViewAdobe } from './ReactViewAdobe';
*
* export default function App() {
* return (
* <ReactViewAdobe
* url="https://example.com/sample.pdf"
* clientId="your-client-id"
* previewConfig={{ embedMode: "FULL_WINDOW", showZoomControl: true }}
* debug
* />
* );
* }
* ```
*
* @summary
* - Ensure that the provided `clientId` is correctly configured for your domain, as Adobe verifies domain-clientID mappings.
* - This component dynamically injects the Adobe Embed SDK script into the DOM if not already loaded.
* - Use the `debug` flag to log lifecycle events and troubleshooting details during development.
*
* @returns {JSX.Element} A React component that renders the Adobe PDF Viewer.
*/
export function ReactViewAdobe(props: ReactViewAdobeProps) {
const [adobePDFProgrammeInstalled, setAdobePDFProgrammeInstalled] =
React.useState(false);
const [componentNeedsRendering, setComponentNeedsRendering] =
React.useState(false);
const [scriptViewerLoaded, setScriptViewerLoaded] = React.useState(false);
const useHooksForConfig =
React[props?.useReactHookForAdobeAPIConfigs || "useMemo"];
const renderAdobePDF = React.useCallback(() => {
const divId = props.id || DefaultConfigs.staticDivId;
const viewerConfig = props.previewConfig || DefaultConfigs.staticDefaultConfig;
const url = props.url || DefaultConfigs.demoUrl;
// For Lightbox, we only call if "triggerAdobeDCViewRender" is set
if (viewerConfig?.embedMode === "LIGHT_BOX") {
if (props.triggerAdobeDCViewRender) {
previewFile({
divId,
viewerConfig,
url,
clientID: props.clientId,
_fileMeta: props.fileMeta,
});
}
} else {
// Normal embed mode
const containerElm = document.getElementById(divId);
if (containerElm) {
if (props.debug) {
console.info("Adobe PDF Viewer: Attempting to preview the file");
}
previewFile({
divId,
viewerConfig,
url,
clientID: props.clientId,
_fileMeta: props.fileMeta,
});
}
}
}, [
props.id,
props.url,
props.clientId,
props.fileMeta,
props.debug,
props.triggerAdobeDCViewRender,
props.previewConfig,
]);
const adobeDCView = useHooksForConfig(() => {
if(props.debug) {
log({
message: `At hooks to check if Adobe DC View is available`,
prefix: "ReactViewAdobe:adobeDCView",
type: "info",
})
}
if (adobePDFProgrammeInstalled === true) {
const adobedcview = (window as any)["AdobeDC"]?.["View"];
if (props.debug) {
log({
message: `Adobe DC View is available`,
prefix: "ReactViewAdobe:adobeDCView",
type: "info",
})
}
return adobedcview;
}
}, [adobePDFProgrammeInstalled]);
const useHooksForLoading =
React[props?.useReactHookWhenLoadingAdobeAPI || "useEffect"];
useHooksForLoading(() => {
if (scriptViewerLoaded === false) {
const scriptExistsALready = document.querySelector(
`script.react-adobe-embed-handholding-adobe-api-loading-idiocy[data-adobe-pdf-id="${props.id || DefaultConfigs.staticDivId}"]`,
);
if (scriptExistsALready) {
if (props.debug) {
// console.info(`\x1b[1mAdobe SDK Check\x1b[0m`, 'Reloading and Rerendering Adobe SDK');
log({
message: `Reloading and Rerendering Adobe SDK`,
prefix: "ReactViewAdobe:AdobeSDK",
type: "info",
});
}
// Lightbox mode renders from ui event triggered by user, so no need to render
if (props.previewConfig?.embedMode !== "LIGHT_BOX") {
setComponentNeedsRendering(true);
}
scriptExistsALready.setAttribute(
"data-testid",
"react-adobe-embed-handholding-adobe-api-loading-idiocy-reused",
);
} else {
if (props.debug) {
log({
message: `Initial Adobe SDK Load`,
prefix: "ReactViewAdobe:AdobeSDK",
type: "info",
});
}
const script = document.createElement("script");
script.setAttribute(
"data-testid",
"react-adobe-embed-handholding-adobe-api-loading-idiocy-initial",
);
script.setAttribute(
"data-adobe-pdf-id",
props.id || DefaultConfigs.staticDivId,
);
script.setAttribute(
"class",
"react-adobe-embed-handholding-adobe-api-loading-idiocy",
);
script.src =
props.previewConfig?.viewSdkViewerScript ||
DefaultConfigs.staticDefaultConfig.viewSdkViewerScript;
script.async = true;
script.onload = () => {
setScriptViewerLoaded(true);
};
document.body.appendChild(script);
}
}
}, [props.id, scriptViewerLoaded, adobePDFProgrammeInstalled]);
const useHooksForCall =
React[props?.useReactHookWhenCallingAdobeAPI || "useEffect"];
useHooksForCall(() => {
if (adobePDFProgrammeInstalled === false && scriptViewerLoaded === true) {
document.addEventListener("adobe_dc_view_sdk.ready", () => {
setAdobePDFProgrammeInstalled(true);
});
}
const callAdobeApi = (props: {
id?: string;
className?: string;
title?: string;
style?: React.CSSProperties;
debug?: boolean;
triggerAdobeDCViewRender?: boolean;
previewConfig?: Partial<PreviewFileConfig>;
url: string;
clientId: string;
fileMeta?: { [key: string | "fileName" | "id"]: any };
}) => {
if (props.debug)
{
/*
console.info(
"Adobe PDF Viewer SDK Ready Event",
adobeDCView,
(window as any)["adobe_dc_view_sdk"],
);*/
log({
message: "At Calling Adobe API to render PDF - window.adobe_dc_view_sdk:" + (window as any)["adobe_dc_view_sdk"],
prefix: "ReactViewAdobe:callAdobeApi",
type: "info",
});
}
renderAdobePDF();
};
if (scriptViewerLoaded === true && adobePDFProgrammeInstalled === true) {
callAdobeApi(props);
}
}, [adobePDFProgrammeInstalled, scriptViewerLoaded, props, adobeDCView]);
//Listen if component needs rerendering due to page view change
const useReactHookForComponentDidUpdate =
React[props?.useReactHookForComponentDidUpdate || "useEffect"];
useReactHookForComponentDidUpdate(() => {
if (componentNeedsRendering === true) {
const divId = props.id || DefaultConfigs.staticDivId;
const divElm = document.getElementById(divId);
if (divElm) {
renderAdobePDF();
}
setComponentNeedsRendering(false);
}
}, [componentNeedsRendering, props]);
return <AdobeDiv {...props} />;
}
export default ReactViewAdobe;