|
| 1 | +import { useState, useRef } from 'react'; |
| 2 | +import { Box, Button, Form, FormControl, Paragraph } from '@contentful/f36-components'; |
| 3 | +import { PageAppSDK } from '@contentful/app-sdk'; |
| 4 | +import mammoth from 'mammoth'; |
| 5 | + |
| 6 | +interface DocumentFileUploaderProps { |
| 7 | + sdk: PageAppSDK; |
| 8 | + onSuccess: (title: string, html: string | null, isDocxRendered: boolean) => void; |
| 9 | + onError: (message: string) => void; |
| 10 | + isDisabled?: boolean; |
| 11 | + previewRef?: React.RefObject<HTMLDivElement>; |
| 12 | +} |
| 13 | + |
| 14 | +const convertDocxToHtml = async (file: File) => { |
| 15 | + const arrayBuffer = await file.arrayBuffer(); |
| 16 | + const result = await mammoth.convertToHtml({ arrayBuffer }); |
| 17 | + return result.value as string; |
| 18 | +}; |
| 19 | + |
| 20 | +const loadDocxPreview = async () => { |
| 21 | + if ((window as any).docx) return (window as any).docx; |
| 22 | + await new Promise<void>((resolve, reject) => { |
| 23 | + const script = document.createElement('script'); |
| 24 | + script.src = 'https://unpkg.com/docx-preview@0.3.4/dist/docx-preview.min.js'; |
| 25 | + script.async = true; |
| 26 | + script.onload = () => resolve(); |
| 27 | + script.onerror = () => reject(new Error('Failed to load docx-preview')); |
| 28 | + document.body.appendChild(script); |
| 29 | + }); |
| 30 | + const docx = (window as any).docx; |
| 31 | + if (!docx) { |
| 32 | + throw new Error('docx-preview failed to initialize'); |
| 33 | + } |
| 34 | + return docx; |
| 35 | +}; |
| 36 | + |
| 37 | +export const DocumentFileUploader = ({ |
| 38 | + sdk, |
| 39 | + onSuccess, |
| 40 | + onError, |
| 41 | + isDisabled, |
| 42 | + previewRef, |
| 43 | +}: DocumentFileUploaderProps) => { |
| 44 | + const [file, setFile] = useState<File | null>(null); |
| 45 | + const [fileError, setFileError] = useState<string | null>(null); |
| 46 | + const [isUploading, setIsUploading] = useState<boolean>(false); |
| 47 | + const [uploadProgress, setUploadProgress] = useState<number>(0); |
| 48 | + |
| 49 | + const onSelectFile = (fileList: FileList | null) => { |
| 50 | + setFile(null); |
| 51 | + setFileError(null); |
| 52 | + if (!fileList || fileList.length === 0) { |
| 53 | + return; |
| 54 | + } |
| 55 | + const file = fileList[0]; |
| 56 | + setFile(file); |
| 57 | + }; |
| 58 | + |
| 59 | + const simulateUpload = async () => { |
| 60 | + setIsUploading(true); |
| 61 | + setUploadProgress(0); |
| 62 | + // Simulate progress to 100% over ~1.5s |
| 63 | + await new Promise<void>((resolve) => { |
| 64 | + const start = Date.now(); |
| 65 | + const tick = () => { |
| 66 | + const elapsed = Date.now() - start; |
| 67 | + const percent = Math.min(100, Math.round((elapsed / 1500) * 100)); |
| 68 | + setUploadProgress(percent); |
| 69 | + if (percent >= 100) { |
| 70 | + resolve(); |
| 71 | + } else { |
| 72 | + requestAnimationFrame(tick); |
| 73 | + } |
| 74 | + }; |
| 75 | + requestAnimationFrame(tick); |
| 76 | + }); |
| 77 | + setIsUploading(false); |
| 78 | + }; |
| 79 | + |
| 80 | + const onSubmitDoc = async () => { |
| 81 | + if (!file) { |
| 82 | + setFileError('Please choose a document file to upload.'); |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + try { |
| 87 | + const lower = file.name.toLowerCase(); |
| 88 | + const isDocx = lower.endsWith('.docx'); |
| 89 | + |
| 90 | + if (isDocx && previewRef) { |
| 91 | + // Prefer higher-fidelity renderer |
| 92 | + try { |
| 93 | + const docx = await loadDocxPreview(); |
| 94 | + const buf = await file.arrayBuffer(); |
| 95 | + if (previewRef.current) { |
| 96 | + previewRef.current.innerHTML = ''; |
| 97 | + await docx.renderAsync(buf, previewRef.current, undefined, { |
| 98 | + inWrapper: true, |
| 99 | + ignoreLastRenderedPageBreak: true, |
| 100 | + experimental: true, |
| 101 | + }); |
| 102 | + onSuccess(file.name, null, true); |
| 103 | + sdk.notifier.success(`Rendered "${file.name}" successfully.`); |
| 104 | + return; |
| 105 | + } |
| 106 | + } catch { |
| 107 | + // Fallback to mammoth if docx-preview fails |
| 108 | + const html = await convertDocxToHtml(file); |
| 109 | + await simulateUpload(); |
| 110 | + onSuccess(file.name, html, false); |
| 111 | + sdk.notifier.success(`Uploaded "${file.name}" successfully.`); |
| 112 | + return; |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // Non-docx or unable to render with docx-preview; try mammoth fallback for best effort |
| 117 | + const html = await convertDocxToHtml(file); |
| 118 | + await simulateUpload(); |
| 119 | + onSuccess(file.name, html, false); |
| 120 | + sdk.notifier.success(`Uploaded "${file.name}" successfully.`); |
| 121 | + } catch (e: unknown) { |
| 122 | + const message = e instanceof Error ? e.message : 'Failed to parse document file.'; |
| 123 | + onError(message); |
| 124 | + sdk.notifier.error(message); |
| 125 | + } |
| 126 | + }; |
| 127 | + |
| 128 | + return ( |
| 129 | + <Form> |
| 130 | + <FormControl> |
| 131 | + <FormControl.Label>Document file (.doc, .docx)</FormControl.Label> |
| 132 | + <Box marginTop="spacingS"> |
| 133 | + <input type="file" accept=".doc,.docx" onChange={(e) => onSelectFile(e.target.files)} /> |
| 134 | + </Box> |
| 135 | + <FormControl.HelpText>Choose a document file from your computer</FormControl.HelpText> |
| 136 | + {fileError && <FormControl.ValidationMessage>{fileError}</FormControl.ValidationMessage>} |
| 137 | + <Box marginTop="spacingS"> |
| 138 | + <Button isDisabled={isDisabled || isUploading || !file} onClick={onSubmitDoc}> |
| 139 | + {isUploading ? 'Uploading...' : 'Upload Document File'} |
| 140 | + </Button> |
| 141 | + </Box> |
| 142 | + |
| 143 | + {isUploading && ( |
| 144 | + <Box marginTop="spacingS"> |
| 145 | + <Paragraph>Uploading... {uploadProgress}%</Paragraph> |
| 146 | + <progress max={100} value={uploadProgress} style={{ width: '100%' }} /> |
| 147 | + </Box> |
| 148 | + )} |
| 149 | + </FormControl> |
| 150 | + </Form> |
| 151 | + ); |
| 152 | +}; |
0 commit comments