72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { Loader2 } from "lucide-react";
|
|
|
|
export function DocxPreview({
|
|
document,
|
|
onError,
|
|
}: {
|
|
document: Blob;
|
|
onError: () => void;
|
|
}) {
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
const reportedRef = useRef(false);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
const container = containerRef.current;
|
|
reportedRef.current = false;
|
|
setLoading(true);
|
|
|
|
const reportError = () => {
|
|
if (cancelled || reportedRef.current) return;
|
|
reportedRef.current = true;
|
|
onError();
|
|
};
|
|
|
|
const render = async () => {
|
|
if (!container) return;
|
|
container.replaceChildren();
|
|
|
|
try {
|
|
const { renderAsync } = await import("docx-preview");
|
|
if (cancelled) return;
|
|
await renderAsync(document, container, undefined, {
|
|
className: "docx-preview-document",
|
|
inWrapper: true,
|
|
ignoreWidth: false,
|
|
ignoreHeight: false,
|
|
ignoreFonts: false,
|
|
breakPages: true,
|
|
});
|
|
if (!cancelled) setLoading(false);
|
|
} catch {
|
|
container.replaceChildren();
|
|
reportError();
|
|
}
|
|
};
|
|
|
|
void render();
|
|
return () => {
|
|
cancelled = true;
|
|
container?.replaceChildren();
|
|
};
|
|
}, [document, onError]);
|
|
|
|
return (
|
|
<div className="relative h-full overflow-auto rounded-md border border-border bg-muted/30 p-4">
|
|
<div
|
|
ref={containerRef}
|
|
className="min-h-full w-max min-w-full"
|
|
/>
|
|
{loading && (
|
|
<div className="absolute inset-0 flex items-center justify-center bg-[var(--color-surface)]">
|
|
<Loader2 className="size-5 animate-spin text-muted-foreground" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|