previewPaneOfficeLegacyDocContent.tsx 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
  2. import {
  3. DocxEditorViewer,
  4. setWasmSource,
  5. useDocxEditor,
  6. useDocxModel,
  7. type DocModel,
  8. type DocxPageVirtualizationOptions,
  9. } from "@extend-ai/react-docx";
  10. import docxWasmUrl from "@extend-ai/react-docx/docx_wasm_bg.wasm?url";
  11. import {
  12. calculateDocxPreviewFit,
  13. installDocumentLinkSafety,
  14. type DocxPreviewFit,
  15. } from "@/lib/officeFilePreview.js";
  16. import { logger } from "@/logger.js";
  17. setWasmSource(docxWasmUrl);
  18. let nextDocxModelRenderKey = 0;
  19. const docxModelRenderKeys = new WeakMap<DocModel, number>();
  20. function getDocxModelRenderKey(model: DocModel): number {
  21. const existingKey = docxModelRenderKeys.get(model);
  22. if (existingKey !== undefined) {
  23. return existingKey;
  24. }
  25. nextDocxModelRenderKey += 1;
  26. docxModelRenderKeys.set(model, nextDocxModelRenderKey);
  27. return nextDocxModelRenderKey;
  28. }
  29. function isSameDocxPreviewFit(current: DocxPreviewFit | null, next: DocxPreviewFit): boolean {
  30. return (
  31. current !== null &&
  32. Math.abs(current.scale - next.scale) < 0.001 &&
  33. Math.abs(current.width - next.width) < 0.5 &&
  34. Math.abs(current.height - next.height) < 0.5
  35. );
  36. }
  37. function ResponsiveDocxEditorViewer({
  38. model,
  39. onOpenBrowserUrl,
  40. sourcePath,
  41. }: {
  42. model: DocModel;
  43. onOpenBrowserUrl?: (url: string) => void;
  44. sourcePath: string;
  45. }) {
  46. // 轻量 ReactDocxViewer 不走编辑器的完整分页与排版链路,预览结果会和编辑画布不一致。
  47. // 使用同一个 editor controller 驱动文档画布,但固定为只读模式,避免暴露任何编辑能力。
  48. const editor = useDocxEditor({
  49. starterModel: model,
  50. initialFileName: sourcePath,
  51. initialDocumentTheme: "light",
  52. });
  53. const viewportRef = useRef<HTMLDivElement | null>(null);
  54. const contentRef = useRef<HTMLDivElement | null>(null);
  55. const [fit, setFit] = useState<DocxPreviewFit | null>(null);
  56. // 外层使用 transform 缩放页面,但 react-docx 的虚拟列表不会自动识别 transform。
  57. // 必须同步传入相同 zoomScale,否则滚动坐标会按未缩放页高计算,导致闪白或末页无法挂载。
  58. const pageVirtualization = useMemo<DocxPageVirtualizationOptions>(
  59. () => ({ zoomScale: fit?.scale ?? 1 }),
  60. [fit?.scale],
  61. );
  62. const updateFit = useCallback(() => {
  63. const viewport = viewportRef.current;
  64. const content = contentRef.current;
  65. if (!viewport || !content) {
  66. return;
  67. }
  68. const next = calculateDocxPreviewFit({
  69. availableWidth: viewport.clientWidth,
  70. naturalHeight: content.offsetHeight,
  71. naturalWidth: content.offsetWidth,
  72. });
  73. if (!next) {
  74. return;
  75. }
  76. setFit((current) => {
  77. if (isSameDocxPreviewFit(current, next)) {
  78. return current;
  79. }
  80. // 调试说明:拖动 Preview Pane 时会按帧触发 ResizeObserver;高频尺寸轨迹只走 debug,
  81. // 生产构建不落盘,避免响应式布局把日志量放大到和 resize 事件同数量级。
  82. logger.debug("[PreviewPane] DOCX 预览宽度已同步", {
  83. path: sourcePath,
  84. availableWidth: viewport.clientWidth,
  85. naturalWidth: content.offsetWidth,
  86. scale: next.scale,
  87. });
  88. return next;
  89. });
  90. }, [sourcePath]);
  91. useLayoutEffect(() => {
  92. const content = contentRef.current;
  93. const disposeLinkSafety = content ? installDocumentLinkSafety(content, onOpenBrowserUrl) : null;
  94. updateFit();
  95. if (typeof ResizeObserver === "undefined") {
  96. return disposeLinkSafety ?? undefined;
  97. }
  98. const resizeObserver = new ResizeObserver(updateFit);
  99. if (viewportRef.current) {
  100. resizeObserver.observe(viewportRef.current);
  101. }
  102. if (contentRef.current) {
  103. resizeObserver.observe(contentRef.current);
  104. }
  105. return () => {
  106. resizeObserver.disconnect();
  107. disposeLinkSafety?.();
  108. };
  109. }, [onOpenBrowserUrl, updateFit]);
  110. return (
  111. <div ref={viewportRef} className="w-full min-w-0" data-docx-fit-viewport>
  112. <div
  113. className="relative mx-auto"
  114. data-docx-fit-frame
  115. style={fit ? { width: fit.width, height: fit.height } : undefined}
  116. >
  117. {/* react-docx 按纸张原始像素宽度渲染,窄 Preview Pane 会被 794px 页面撑破。
  118. 只缩小不放大,并同步包装层宽高,避免单独 transform 后仍保留未缩放的横向滚动区。 */}
  119. <div
  120. ref={contentRef}
  121. className="theme-zai-light min-w-max text-foreground"
  122. data-docx-fit-content
  123. style={
  124. fit
  125. ? {
  126. position: "absolute",
  127. left: 0,
  128. top: 0,
  129. transform: `scale(${fit.scale})`,
  130. transformOrigin: "top left",
  131. }
  132. : undefined
  133. }
  134. >
  135. <DocxEditorViewer
  136. className="min-w-max"
  137. editor={editor}
  138. mode="read-only"
  139. pageGapBackgroundColor="transparent"
  140. pageVirtualization={pageVirtualization}
  141. />
  142. </div>
  143. </div>
  144. </div>
  145. );
  146. }
  147. export function PreviewPaneOfficeLegacyDocContent({
  148. buffer,
  149. errorMessage,
  150. onOpenBrowserUrl,
  151. sourcePath,
  152. }: {
  153. buffer: ArrayBuffer;
  154. errorMessage: string;
  155. onOpenBrowserUrl?: (url: string) => void;
  156. sourcePath: string;
  157. }) {
  158. const { model, isLoading, error } = useDocxModel(buffer);
  159. useEffect(() => {
  160. if (!error) {
  161. return;
  162. }
  163. logger.error("[PreviewPane] DOCX 文件解析失败", {
  164. path: sourcePath,
  165. error: error.message,
  166. });
  167. }, [error, sourcePath]);
  168. if (isLoading) {
  169. return (
  170. <div
  171. aria-busy="true"
  172. className="h-full min-h-0 w-full bg-background"
  173. data-office-preview-pending
  174. />
  175. );
  176. }
  177. if (error || !model) {
  178. return (
  179. <div className="p-3 text-ui-base text-destructive" role="alert">
  180. {errorMessage}
  181. </div>
  182. );
  183. }
  184. return (
  185. <div
  186. className="h-full min-h-0 w-full min-w-0 overflow-auto bg-background p-4 max-sm:p-2"
  187. data-office-preview-kind="doc"
  188. >
  189. <ResponsiveDocxEditorViewer
  190. key={getDocxModelRenderKey(model)}
  191. model={model}
  192. onOpenBrowserUrl={onOpenBrowserUrl}
  193. sourcePath={sourcePath}
  194. />
  195. </div>
  196. );
  197. }