Skip to content

Improve docx preview - #15907

Merged
yingfeng merged 4 commits into
infiniflow:mainfrom
yingfeng:docpreview
Jun 11, 2026
Merged

yingfeng merged 4 commits into
infiniflow:mainfrom
yingfeng:docpreview

Conversation

@yingfeng

Copy link
Copy Markdown
Member

No description provided.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026
@yingfeng yingfeng added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 10, 2026
@yingfeng
yingfeng marked this pull request as draft June 10, 2026 09:11
@yingfeng
yingfeng marked this pull request as ready for review June 10, 2026 09:11
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026
@yingfeng
yingfeng requested a review from cike8899 June 10, 2026 09:11
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • web/package-lock.json is excluded by !**/package-lock.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: aee94927-302e-4fb8-a384-58cd0addfba0

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

DocPreviewer and its hooks migrate from Mammoth-based DOCX→HTML rendering to an editor-based preview using @extend-ai/react-docx, adding ZIP signature checks, cancellation-safe fetching, zoom controls, and removing the old useFetchDocx hook.

Changes

DOCX Viewer Replacement

Layer / File(s) Summary
Dependency and viewer utilities
web/package.json, web/src/components/document-preview/doc-preview.tsx
Add @extend-ai/react-docx ^0.6.7 and remove mammoth from dependencies. Introduce ZIP-header detection, isZipLikeBlob, zoom step config, and clampZoom helper.
DOCX editor integration and fetch flow
web/src/components/document-preview/doc-preview.tsx
Replace HTML state with useDocxEditor integration. Rewrite fetchDocument to fetch Blob, verify ZIP signature, wrap as .docx File, load via importDocxFile, and set loading/error with cancellation guards.
Effects and state handlers
web/src/components/document-preview/doc-preview.tsx
Add cleanup-aware effect to trigger fetchDocument with unmount cancellation. Map editor status to component error/loading state. Memoize handleZoomIn/handleZoomOut and derive showContent/pageCount from editor state.
UI rendering with zoom toolbar
web/src/components/document-preview/doc-preview.tsx
Add zoom toolbar with in/out controls (disabled at bounds/loading/error). Replace dangerouslySetInnerHTML with read-only DocxEditorViewer and apply zoom via container style={{ zoom: zoomScale / 100 }}. Preserve loading spinner and unsupported-format overlay.
Hook cleanup
web/src/components/document-preview/hooks.ts
Remove mammoth import and delete exported useFetchDocx hook that used mammoth.convertToHtml; other preview hooks unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐇 A rabbit reads bytes and checks the ZIP,
swaps Mammoth for an editor — a gentler trip.
Zoom knobs click, cancellation stays neat,
pages render clean, no HTML sleight of feet.
Hooray for previews that now behave sweet. 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is completely empty. The required template sections asking for problem statement and type of change are missing entirely. Add a description following the template: explain the problem being solved (migrating from Mammoth to @extend-ai/react-docx), select the appropriate change type (likely Refactoring or Performance Improvement), and provide context for reviewers.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Improve docx preview' clearly summarizes the main change: replacing the Mammoth-based DOCX preview with a new react-docx editor-based implementation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
web/src/components/document-preview/doc-preview.tsx (3)

166-221: ⚖️ Poor tradeoff

User-facing strings should use i18n.

Multiple hardcoded English strings are not internationalized:

  • "Loading..." / "Page X" (toolbar)
  • "Zoom out" / "Zoom in" (aria-labels)
  • "Preview is not available for this Word document"
  • "@extend-ai/react-docx supports modern .docx files only."

As per coding guidelines, use useTranslation from react-i18next for all user-facing text.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/document-preview/doc-preview.tsx` around lines 166 - 221,
The component currently renders several hardcoded user-facing strings in
doc-preview.tsx (e.g., the toolbar texts "Loading...", `Page ${pageCount ||
'-'}`, aria-labels "Zoom out"/"Zoom in", and error panel strings "Preview is not
available for this Word document" and "`@extend-ai/react-docx` supports modern
.docx files only.")—replace these with i18n lookups by importing and calling
useTranslation from react-i18next at the top of the component, define keys
(e.g., toolbar.loading, toolbar.page, toolbar.zoomOut, toolbar.zoomIn,
error.previewUnavailable, error.supportNote) and use t('...') where loading,
pageCount, zoomScale, handleZoomOut, and handleZoomIn are used so all visible
text and aria-labels come from translation strings.

Source: Coding guidelines


166-169: 💤 Low value

Ambiguous page count label.

Page ${pageCount || '-'} displays "Page 5" for 5 total pages, which could be mistaken for "currently viewing page 5." Consider "5 pages" or "Page 1 of 5" for clarity.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/document-preview/doc-preview.tsx` around lines 166 - 169,
The page count label is ambiguous; update the JSX in the doc-preview component
(the span that currently renders {loading ? 'Loading...' : error ? '' : `Page
${pageCount || '-'}`}) to show a clearer total or context-aware label: either
render `${pageCount || '-'} pages` when only total is known, or if a current
page variable exists (e.g., currentPage or pageIndex), render `Page
${currentPage} of ${pageCount}`; keep the loading and error branches unchanged
and ensure you handle falsy pageCount by showing '-' as before.

36-55: 💤 Low value

clampZoom has a logic error for intermediate (non-step) scale values.

When scale isn't already in ZOOM_STEPS, findIndex locates the adjacent step, then direction is added again—resulting in skipping a step. For example, zooming in from 110% would jump to 150% instead of 125%.

This path is currently unreachable since zoomScale is always initialized and reset to step values, but the logic is incorrect if that invariant ever changes.

Suggested fix
 const clampZoom = (scale: number, direction: 1 | -1): number => {
   let idx = ZOOM_STEPS.indexOf(scale as (typeof ZOOM_STEPS)[number]);
   if (idx < 0) {
+    // scale is between steps: find adjacent step without adding direction again
     if (direction > 0) {
       idx = ZOOM_STEPS.findIndex((v) => v > scale);
+      if (idx < 0) idx = ZOOM_STEPS.length - 1;
+      return ZOOM_STEPS[idx];
     } else {
       for (let i = ZOOM_STEPS.length - 1; i >= 0; i--) {
         if (ZOOM_STEPS[i] < scale) {
-          idx = i;
-          break;
+          return ZOOM_STEPS[i];
         }
       }
+      return ZOOM_STEPS[0];
     }
   }
-  idx = Math.max(
-    0,
-    Math.min(ZOOM_STEPS.length - 1, idx < 0 ? 0 : idx + direction),
-  );
+  idx = Math.max(0, Math.min(ZOOM_STEPS.length - 1, idx + direction));
   return ZOOM_STEPS[idx] ?? scale;
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/document-preview/doc-preview.tsx` around lines 36 - 55,
clampZoom incorrectly computes the next zoom step when scale is not exactly in
ZOOM_STEPS because it finds an adjacent index then adds direction again (causing
a skip); change clampZoom to compute the target index directly: if scale exists
in ZOOM_STEPS use foundIndex + direction, otherwise if direction === 1 set
targetIndex = first index where ZOOM_STEPS[i] > scale, and if direction === -1
set targetIndex = last index where ZOOM_STEPS[i] < scale; then clamp targetIndex
between 0 and ZOOM_STEPS.length-1 and return ZOOM_STEPS[targetIndex] (use the
function name clampZoom and the constant ZOOM_STEPS to locate the code).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/components/document-preview/doc-preview.tsx`:
- Around line 140-145: The effect in useEffect that checks status === 'Only
.docx files are supported' is brittle; change the component to rely on a stable
flag or status code rather than a magic string: add or read a typed status value
(e.g., errorCode or UploadStatus enum) from the editor state or propagate a
constant like DOCX_UNSUPPORTED_CODE and update the effect to check that (or use
a deterministic helper like isDocxUnsupportedStatus(status)); then call
setError(...) and setLoading(false) when that code/helper indicates the
unsupported-docx condition (update any producers of status to emit the
code/constant as needed) using the existing setError and setLoading functions.

---

Nitpick comments:
In `@web/src/components/document-preview/doc-preview.tsx`:
- Around line 166-221: The component currently renders several hardcoded
user-facing strings in doc-preview.tsx (e.g., the toolbar texts "Loading...",
`Page ${pageCount || '-'}`, aria-labels "Zoom out"/"Zoom in", and error panel
strings "Preview is not available for this Word document" and
"`@extend-ai/react-docx` supports modern .docx files only.")—replace these with
i18n lookups by importing and calling useTranslation from react-i18next at the
top of the component, define keys (e.g., toolbar.loading, toolbar.page,
toolbar.zoomOut, toolbar.zoomIn, error.previewUnavailable, error.supportNote)
and use t('...') where loading, pageCount, zoomScale, handleZoomOut, and
handleZoomIn are used so all visible text and aria-labels come from translation
strings.
- Around line 166-169: The page count label is ambiguous; update the JSX in the
doc-preview component (the span that currently renders {loading ? 'Loading...' :
error ? '' : `Page ${pageCount || '-'}`}) to show a clearer total or
context-aware label: either render `${pageCount || '-'} pages` when only total
is known, or if a current page variable exists (e.g., currentPage or pageIndex),
render `Page ${currentPage} of ${pageCount}`; keep the loading and error
branches unchanged and ensure you handle falsy pageCount by showing '-' as
before.
- Around line 36-55: clampZoom incorrectly computes the next zoom step when
scale is not exactly in ZOOM_STEPS because it finds an adjacent index then adds
direction again (causing a skip); change clampZoom to compute the target index
directly: if scale exists in ZOOM_STEPS use foundIndex + direction, otherwise if
direction === 1 set targetIndex = first index where ZOOM_STEPS[i] > scale, and
if direction === -1 set targetIndex = last index where ZOOM_STEPS[i] < scale;
then clamp targetIndex between 0 and ZOOM_STEPS.length-1 and return
ZOOM_STEPS[targetIndex] (use the function name clampZoom and the constant
ZOOM_STEPS to locate the code).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e3649764-0a1d-4874-ab14-3f828ae87fb8

📥 Commits

Reviewing files that changed from the base of the PR and between ad63877 and af711ba.

⛔ Files ignored due to path filters (1)
  • web/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • web/package.json
  • web/src/components/document-preview/doc-preview.tsx
  • web/src/components/document-preview/hooks.ts
💤 Files with no reviewable changes (1)
  • web/src/components/document-preview/hooks.ts

Comment on lines 140 to +145
useEffect(() => {
if (url) {
fetchDocument();
if (status === 'Only .docx files are supported') {
setError(status);
setLoading(false);
}
}, [url]);
}, [status]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

@extend-ai/react-docx useDocxEditor status API values

💡 Result:

The @extend-ai/react-docx package (typically published under the scoped package name @eigenpal/docx-editor-react) does not have a single API called useDocxEditor that provides a status API value. Instead, the editor functionality is managed through various specialized hooks and a main component ref [1][2][3]. If you are looking for status information, it is typically accessed through specific hooks or component properties rather than a generic status API on a useDocxEditor hook: 1. AutoSave Status: The useAutoSave hook provides a status member, which returns an AutoSaveStatus type [1]. 2. Agent Status: If you are using the agent integration via @eigenpal/docx-editor-agents/react, the status field for agent messages can take the values 'streaming' or 'done' [4]. 3. Editor State/Ref: You can access editor state and methods via DocxEditorRef by passing a ref to the DocxEditor component [2][3]. This allows you to interact with the document, tracked changes, comments, and selection state directly [2][3]. For the most accurate technical implementation, please refer to the official API documentation for the specific hook or feature you are implementing, as functionality is modularized into subpaths like /hooks, /ui, and /plugin-api [1][2][5][3].

Citations:


Fragile magic-string comparison for editor status in doc preview.

In web/src/components/document-preview/doc-preview.tsx (lines ~140-145), the effect branches on status === 'Only .docx files are supported', coupling behavior to an exact error-message string. If the editor message changes, this error handling can silently stop working. Prefer an exposed typed status/error code (or a less brittle check) instead of exact string equality.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/document-preview/doc-preview.tsx` around lines 140 - 145,
The effect in useEffect that checks status === 'Only .docx files are supported'
is brittle; change the component to rely on a stable flag or status code rather
than a magic string: add or read a typed status value (e.g., errorCode or
UploadStatus enum) from the editor state or propagate a constant like
DOCX_UNSUPPORTED_CODE and update the effect to check that (or use a
deterministic helper like isDocxUnsupportedStatus(status)); then call
setError(...) and setLoading(false) when that code/helper indicates the
unsupported-docx condition (update any producers of status to emit the
code/constant as needed) using the existing setError and setLoading functions.

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (ad63877) to head (102134e).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15907   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread web/package.json
"@ant-design/icons": "^5.2.6",
"@antv/g2": "^5.2.10",
"@antv/g6": "^5.1.0",
"@extend-ai/react-docx": "^0.6.7",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is recommended to delete any remaining mammoth libraries.

@yingfeng
yingfeng merged commit bae8c6f into infiniflow:main Jun 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants