"use client"; import { useEffect, useRef, useState } from "react"; import { assertPreviewableDocx } from "@/lib/wiki-source-preview"; // No scripts, network requests, forms or navigation from source content. The // parent needs same-origin access only to render into this isolated document. const FRAME_DOCUMENT = `
`; export function SourceDocxPreview({ blob, scale, title, onSize, onReady, onError, }: { blob: Blob; scale: number; title: string; onSize: (size: { width: number; height: number }) => void; onReady: () => void; onError: () => void; }) { const frame = useRef(null); const [loaded, setLoaded] = useState(false); const [size, setSize] = useState({ width: 794, height: 1123 }); useEffect(() => { const doc = frame.current?.contentDocument; const container = doc?.getElementById("document"); if (!loaded || !container || !doc) return; let disposed = false; let observer: ResizeObserver | undefined; void (async () => { const data = new Uint8Array(await blob.arrayBuffer()); assertPreviewableDocx(data); const { renderAsync } = await import("docx-preview"); if (disposed) return; await renderAsync(data, container, doc.head, { inWrapper: false, useBase64URL: true, renderAltChunks: false, renderComments: false, renderChanges: false, ignoreLastRenderedPageBreak: false, }); if (disposed) return; const measure = () => { if (disposed) return; const pages = Array.from( container.querySelectorAll("section.docx"), ); const next = { width: Math.max( 1, ...pages.map((page) => page.offsetWidth), container.scrollWidth, ), height: Math.max(1, container.scrollHeight), }; setSize((current) => current.width === next.width && current.height === next.height ? current : next, ); onSize(next); }; // Keep links inert, including keyboard activation in the iframe. container.querySelectorAll("a").forEach((link) => { link.removeAttribute("href"); link.removeAttribute("target"); }); measure(); observer = new ResizeObserver(measure); observer.observe(container); onReady(); })().catch(() => { if (!disposed) onError(); }); return () => { disposed = true; observer?.disconnect(); }; }, [blob, loaded, onSize, onReady, onError]); return (