Skip to content

[WC-2910] DocumentViewer #1529

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import React, { createElement, Fragment, PropsWithChildren, ReactElement, useCallback } from "react";
import { useZoomScale } from "../utils/useZoomScale";
import { DocumentViewerContainerProps } from "typings/DocumentViewerProps";
import { downloadFile } from "../utils/helpers";

type FileFormat = {
status: "available";
value: {
uri: string;
name: string;
};
};

interface BaseControlViewerProps extends PropsWithChildren {
file: DocumentViewerContainerProps["file"] | FileFormat;
CustomControl?: React.ReactNode;
}

interface BaseViewerProps extends PropsWithChildren {
fileName: string;
CustomControl?: React.ReactNode;
}

const BaseViewer = (props: BaseViewerProps): ReactElement => {
const { fileName, CustomControl, children } = props;
return (
<Fragment>
<div className="widget-document-viewer-controls">
<div className="widget-document-viewer-controls-left">
<div className="document-title">{fileName}</div>
</div>
<div className="widget-document-viewer-controls-icons">{CustomControl}</div>
</div>
<div className="widget-document-viewer-content">{children}</div>
</Fragment>
);
};

const BaseControlViewer = (props: BaseControlViewerProps): ReactElement => {
const { CustomControl, children, file } = props;
const { zoomLevel, zoomIn, zoomOut, reset } = useZoomScale();
const onDownloadClick = useCallback(() => {
downloadFile(file.value?.uri);
}, [file]);

return (
<BaseViewer
fileName={file.value?.name || ""}
CustomControl={
<Fragment>
{CustomControl}
<button
onClick={onDownloadClick}
className="icons icon-Download btn btn-icon-only"
aria-label={"Download"}
title={"Download"}
></button>
<div className="widget-document-viewer-zoom">
<button
onClick={zoomOut}
disabled={zoomLevel <= 0.3}
className="icons icon-ZoomOut btn btn-icon-only"
aria-label={"Zoom out"}
title={"Zoom out"}
></button>
<button
onClick={zoomIn}
disabled={zoomLevel >= 10}
className="icons icon-ZoomIn btn btn-icon-only"
aria-label={"Zoom in"}
title={"Zoom in"}
></button>
<button
onClick={reset}
disabled={zoomLevel >= 10}
className="icons icon-FitToWidth btn btn-icon-only"
aria-label={"Fit to width"}
title={"Fit to width"}
></button>
</div>
</Fragment>
}
>
<div
className="widget-document-viewer-zoom-container"
style={{ "--current-zoom-scale": zoomLevel } as React.CSSProperties}
>
{children}
</div>
</BaseViewer>
);
};

export default BaseViewer;
export { BaseControlViewer };
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.widget-document-viewer {
section.docx-viewer-content {
padding: var(--spacing-largest, 48pt) !important;
}
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,43 @@
import { createElement, Fragment, useCallback, useEffect, useState } from "react";
import mammoth from "mammoth";
import { DocumentViewerContainerProps } from "../typings/DocumentViewerProps";
import { DocRendererElement } from "./documentRenderer";
import { parseAsync, renderDocument, WordDocument, Options } from "docx-preview";
import { createElement, useCallback, useEffect, useRef } from "react";
import { BaseControlViewer } from "./BaseViewer";
import { DocRendererElement, DocumentRendererProps, DocumentStatus } from "./documentRenderer";
import "./DocxViewer.scss";

const DocxViewer: DocRendererElement = (props: DocumentViewerContainerProps) => {
const { file } = props;
const [docxHtml, setDocxHtml] = useState<string | null>(null);
const DOC_CONFIG: Partial<Options> = {
className: "docx-viewer-content",
ignoreWidth: true,
ignoreLastRenderedPageBreak: false,
inWrapper: false
};

const loadContent = useCallback(async (arrayBuffer: any) => {
try {
mammoth
.convertToHtml(
{ arrayBuffer: arrayBuffer },
{
includeDefaultStyleMap: true
}
)
.then((result: any) => {
if (result) {
setDocxHtml(result.value);
}
});
} catch (error) {}
}, []);
const DocxViewer: DocRendererElement = (props: DocumentRendererProps) => {
const { file, setDocumentStatus } = props;
const localRef = useRef<HTMLDivElement>(null);
const loadContent = useCallback(
async (arrayBuffer: any) => {
try {
parseAsync(arrayBuffer, DOC_CONFIG)
.then((wordDocument: WordDocument) => {
if (localRef.current) {
// create new dummy stylecontainer to be ignored
const styleContainer = document.createElement("div");
renderDocument(wordDocument, localRef.current, styleContainer, DOC_CONFIG).catch(
(_error: any) => {
setDocumentStatus(DocumentStatus.error);
}
);
}
})
.catch((_error: any) => {
setDocumentStatus(DocumentStatus.error);
});
} catch (_error: any) {
setDocumentStatus(DocumentStatus.error);
}
},
[setDocumentStatus]
);

useEffect(() => {
const controller = new AbortController();
Expand All @@ -38,25 +53,17 @@ const DocxViewer: DocRendererElement = (props: DocumentViewerContainerProps) =>
return () => {
controller.abort();
};
}, [file, file?.status, file?.value?.uri]);
}, [file, file.status, file.value?.uri, loadContent]);

return (
<Fragment>
<div className="widget-document-viewer-controls">
<div className="widget-document-viewer-controls-left">{file.value?.name}</div>
</div>
{docxHtml && (
<div className="widget-document-viewer-content" dangerouslySetInnerHTML={{ __html: docxHtml }}>
{/* {docHtmlStr} */}
</div>
)}
</Fragment>
<BaseControlViewer {...props} file={file}>
<div className="docx-viewer-container" ref={localRef}></div>
</BaseControlViewer>
);
};

DocxViewer.contentTypes = [
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"application/vnd.ms-word",
"application/vnd.ms-word.document.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
Expand All @@ -66,4 +73,6 @@ DocxViewer.contentTypes = [
"application/octet-stream"
];

DocxViewer.fileTypes = ["docx"];

export default DocxViewer;
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
import { createElement, Fragment } from "react";
import { DocRendererElement } from "./documentRenderer";
import { createElement, useCallback } from "react";
import { DocRendererElement, DocumentRendererProps } from "./documentRenderer";
import BaseViewer from "./BaseViewer";
import { downloadFile } from "../utils/helpers";

const ErrorViewer: DocRendererElement = (props: DocumentRendererProps) => {
const { file } = props;
const onDownloadClick = useCallback(() => {
downloadFile(file.value?.uri);
}, [file]);

const ErrorViewer: DocRendererElement = () => {
return (
<Fragment>
<div className="widget-document-viewer-content">No document selected</div>
</Fragment>
<BaseViewer
{...props}
fileName={file.value?.name || ""}
CustomControl={
<button
onClick={onDownloadClick}
className="icons icon-Download btn btn-icon-only"
aria-label={"download"}
></button>
}
>
{file.status === "available" ? (
<div>{"Unsupported document type"}</div>
) : (
<div className="widget-document-viewer-loading"></div>
)}
</BaseViewer>
);
};

ErrorViewer.contentTypes = [];
ErrorViewer.fileTypes = [];

export default ErrorViewer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { createElement, useCallback, useEffect, useState } from "react";
import { read, utils } from "xlsx";
import { BaseControlViewer } from "./BaseViewer";
import { DocRendererElement, DocumentRendererProps, DocumentStatus } from "./documentRenderer";

const ExcelViewer: DocRendererElement = (props: DocumentRendererProps) => {
const { file, setDocumentStatus } = props;
const [xlsxHtml, setXlsxHtml] = useState<string | null>(null);

const loadContent = useCallback(
async (arrayBuffer: any) => {
try {
const wb = read(arrayBuffer);
const sheet = wb.Sheets[wb.SheetNames[0]];
const html = utils.sheet_to_html(sheet);
setXlsxHtml(html);
} catch (_error) {
setDocumentStatus(DocumentStatus.error);
}
},
[setDocumentStatus]
);

useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
if (file.status === "available" && file.value.uri) {
fetch(file.value.uri, { method: "GET", signal })
.then(res => res.arrayBuffer())
.then(response => {
loadContent(response);
});
}

return () => {
controller.abort();
};
}, [file, file.status, file.value?.uri, loadContent]);

return (
<BaseControlViewer {...props} file={file}>
{xlsxHtml && <div className="xlsx-viewer-content" dangerouslySetInnerHTML={{ __html: xlsxHtml }}></div>}
</BaseControlViewer>
);
};

ExcelViewer.contentTypes = [
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12",
"application/vnd.ms-excel.template.macroEnabled.12",
"application/vnd.ms-excel.addin.macroEnabled.12",
"application/octet-stream"
];

ExcelViewer.fileTypes = ["xlsx"];

export default ExcelViewer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createElement } from "react";
import { BaseControlViewer } from "./BaseViewer";
import { DocRendererElement, DocumentRendererProps } from "./documentRenderer";

const ImageViewer: DocRendererElement = (props: DocumentRendererProps) => {
const { file } = props;

return (
<BaseControlViewer {...props} file={file}>
<img src={file.value?.uri} alt="Image" className="image-viewer-content" />
</BaseControlViewer>
);
};

ImageViewer.contentTypes = ["image/*"];

ImageViewer.fileTypes = ["jpg", "jpe", "jpeg", "png", "gif", "bmp", "tif", "tiff", "webp"];

export default ImageViewer;
Loading
Loading