doc-preview.tsx


Overview

doc-preview.tsx defines a React functional component named DocPreviewer that fetches a document from a given URL, converts it from a binary Microsoft Word format (.docx) into sanitized HTML using the mammoth library, and renders the resulting content inside a styled container. It provides a loading spinner while the document is being fetched and parsed, and displays error messages on failure.

This component is primarily used for previewing Word documents directly in a web UI without requiring the user to download and open the file in an external application.


Detailed Explanation

DocPreviewer Component

interface DocPreviewerProps {
  className?: string;
  url: string;
}

export const DocPreviewer: React.FC<DocPreviewerProps> = ({ className, url }) => { ... }

Internal Function: fetchDocument

const fetchDocument = async () => { ... }

React useEffect Hook

useEffect(() => {
  if (url) {
    fetchDocument();
  }
}, [url]);

JSX Render Output

return (
  <div className={classNames(..., className)}>
    {loading && (
      <div className="absolute inset-0 flex items-center justify-center">
        <Spin />
      </div>
    )}
    {!loading && <div dangerouslySetInnerHTML={{ __html: htmlContent }} />}
  </div>
);

Important Implementation Details


Interaction with Other Parts of the System


Usage Example

import { DocPreviewer } from './doc-preview';

function DocumentPage() {
  const documentUrl = 'https://example.com/path/to/document.docx';

  return (
    <div className="max-w-4xl mx-auto my-8">
      <DocPreviewer url={documentUrl} className="h-[600px]" />
    </div>
  );
}

This example renders the DocPreviewer in a page with a fixed height, fetching and displaying the Word document from the given URL.


Mermaid Component Diagram

componentDiagram
    component DocPreviewer {
        +className?: string
        +url: string
        --
        +fetchDocument(): Promise<void>
        +render(): JSX.Element
    }
    component "Spin (Loader)" as Spin
    component "message (UI Notification)" as message
    component "request (HTTP Utility)" as request
    component "mammoth (Docx to HTML)" as mammoth

    DocPreviewer --> Spin : uses for loading state
    DocPreviewer --> message : uses for error display
    DocPreviewer --> request : fetches document blob
    DocPreviewer --> mammoth : converts docx to HTML

Summary

doc-preview.tsx provides a reusable React component for previewing Microsoft Word documents by fetching them from a URL, converting to clean HTML with mammoth, and rendering the content with consistent styling and loading/error feedback. It fits into an application as a document viewer UI element that integrates with shared utilities and components for requests, UI feedback, and spinners.