Skip to content

Fix overlapping CJK text lines in docx file preview - #17693

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
euvre:fix/docx-preview-line-spacing
Aug 3, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
euvre:fix/docx-preview-line-spacing

Conversation

@euvre

@euvre euvre commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Summary

In the file manager's document preview for .docx files, wrapped paragraphs render with overlapping text lines while short single-line paragraphs appear widely spaced, producing inconsistent line pitch across the document.

Root cause: @extend-ai/react-docx computes the line height of paragraphs that do not declare explicit line spacing as fontSize × 0.88. Each line is absolutely positioned with an inline line-height, so application CSS cannot compensate. For CJK text (e.g. 12pt 宋体 → 16px glyphs on a 14px line pitch) the glyphs of adjacent lines overlap. Word renders such paragraphs with the font's natural line height (~1.3× for CJK fonts).

This PR normalizes the document before handing it to the viewer: the docx package is unpacked, and a docDefaults-level line spacing (w:line="312", lineRule="auto", i.e. 1.3 lines) is injected into word/styles.xml only when the document does not already define a default line spacing. Because paragraph spacing is merged per field along the docDefaults → paragraph style → direct formatting chain, any explicit line spacing defined by styles or paragraphs is respected and left untouched. If anything fails during normalization, the original file is used as-is.

Verified with synthetic CJK documents: paragraphs without spacing inherit the injected default after the fix, documents that already define line spacing are unchanged, and the normalization is idempotent.

@extend-ai/react-docx renders paragraphs without explicit line spacing
at 0.88x the font size, which makes CJK glyph lines overlap in wrapped
paragraphs and produces visually inconsistent line pitch across the
document.

Repack the docx before previewing and inject a docDefaults-level line
spacing (1.3 lines, matching Word's single spacing for CJK fonts) so
paragraphs that do not define their own line spacing render with a
consistent, readable line pitch. Paragraphs or styles with explicit
line spacing are left untouched, and any failure falls back to the
original file.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧰 typescript Pull requests that update Typescript code labels Aug 3, 2026
@euvre euvre added the ci Continue Integration label Aug 3, 2026
@euvre
euvre requested a review from wangq8 August 3, 2026 02:12
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The DOCX preview now parses and repacks document packages to apply default paragraph spacing. It preserves explicit spacing and uses the original blob when styles are unavailable or processing fails.

Changes

DOCX Preview Normalization

Layer / File(s) Summary
Normalize DOCX styles before preview import
web/src/components/document-preview/doc-preview.tsx
The preview adds DOCX package utilities, updates default paragraph spacing to 312 twips, preserves explicit line spacing, repacks the package, and passes the normalized blob to importDocxFile with failure fallback.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: jay77721

Sequence Diagram(s)

sequenceDiagram
  participant DocumentPreview
  participant DOCXPackageParser
  participant StylesXMLNormalizer
  participant DOCXSerializer
  participant importDocxFile
  DocumentPreview->>DOCXPackageParser: Parse validated DOCX blob
  DOCXPackageParser->>StylesXMLNormalizer: Normalize default paragraph spacing
  StylesXMLNormalizer-->>DOCXPackageParser: Updated styles XML
  DOCXPackageParser->>DOCXSerializer: Repack DOCX package
  DOCXSerializer-->>DocumentPreview: Normalized blob or original blob on failure
  DocumentPreview->>importDocxFile: Import preview file
Loading

Poem

A rabbit checks the DOCX style,
Adds spacing with a careful smile.
Explicit lines stay in their place,
Failed repairs keep the source file safe.
Then preview hops along its way.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main fix for overlapping CJK text lines in DOCX previews.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, cause, implementation, safeguards, and verification.
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.

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.

@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: 4

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

32-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rename the top-level constants and move the normalization logic out of the component file.

The coding guidelines require PascalCase for top-level constants. Rename DEFAULT_LINE_SPACING_TWIPS, DEFAULT_LINE_SPACING_TAG, and DEFAULT_LINE_SPACING_PPR_DEFAULT to PascalCase. The guidelines also ask you to keep components lean. Move ensureDefaultLineSpacing and normalizeDocxLineSpacing into a utility module, which also makes the XML rules unit-testable.

As per coding guidelines: "Use PascalCase for React component names and top-level constants" and "Extract complex logic into hooks or utility modules and keep components lean."

🤖 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 32 - 35,
Rename the top-level constants DEFAULT_LINE_SPACING_TWIPS,
DEFAULT_LINE_SPACING_TAG, and DEFAULT_LINE_SPACING_PPR_DEFAULT to PascalCase
equivalents, updating all references. Extract ensureDefaultLineSpacing and
normalizeDocxLineSpacing from the document preview component into a utility
module, then import and use them from the component while preserving their
existing XML normalization behavior.

Source: Coding guidelines

🤖 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 85-95: Update the spacing lookup around `spacingTag` so it
searches only direct `w:pPr` content, excluding any nested `w:rPr` subtree
before matching `w:spacing`. Preserve the existing behavior for paragraph-level
spacing while ensuring run-level character spacing is ignored and a valid
paragraph default is created when needed.
- Around line 59-60: Update replaceDocDefaults so document-derived XML is
inserted without String.prototype.replace interpreting dollar replacement
tokens; use a replacer function or escape dollar signs before replacement. Apply
the same correction to the corresponding replacement at the additional
referenced location, preserving the existing XML content.
- Around line 62-79: Update the document-default and paragraph-property
insertion logic in the relevant doc-preview helper: insert the generated
w:pPrDefault immediately before </w:docDefaults> so any existing w:rPrDefault
remains first, and insert w:spacing after existing CT_PPrBase predecessors such
as w:pStyle, w:numPr, w:pBdr, w:shd, and w:widowControl rather than after the
opening w:pPr tag. Prefer DOMParser/XMLSerializer or equivalent ordered-node
manipulation over regex insertion while preserving existing replacement
behavior.
- Around line 6-7: Update the DOCX loading flow around parseDocx to await its
returned Promise<OoxmlPackage> before accessing parts or passing the package to
packageToArrayBuffer, preserving the existing package-processing behavior after
resolution.

---

Nitpick comments:
In `@web/src/components/document-preview/doc-preview.tsx`:
- Around line 32-35: Rename the top-level constants DEFAULT_LINE_SPACING_TWIPS,
DEFAULT_LINE_SPACING_TAG, and DEFAULT_LINE_SPACING_PPR_DEFAULT to PascalCase
equivalents, updating all references. Extract ensureDefaultLineSpacing and
normalizeDocxLineSpacing from the document preview component into a utility
module, then import and use them from the component while preserving their
existing XML normalization behavior.
🪄 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 Plus

Run ID: 22340912-77b9-4702-8ada-52e7e72c6d12

📥 Commits

Reviewing files that changed from the base of the PR and between 288be80 and 65d576f.

📒 Files selected for processing (1)
  • web/src/components/document-preview/doc-preview.tsx

Comment on lines +6 to +7
packageToArrayBuffer,
parseDocx,

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate the package type declarations and inspect the exported API surface.
fd -t d 'react-docx' node_modules --max-depth 3 2>/dev/null
fd -e ts -e mts --full-path 'react-docx' node_modules 2>/dev/null | head -50 | while IFS= read -r f; do
  rg -n -C4 'parseDocx|packageToArrayBuffer|parts\s*:|content\s*:' "$f"
done
rg -n 'react-docx' web/package.json

Repository: infiniflow/ragflow

Length of output: 198


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== package references =="
rg -n '"`@extend-ai/react-docx`"' package-lock.json web/package-lock.json web/package.json 2>/dev/null || true

echo
echo "== lockfile package metadata if present =="
python3 - <<'PY'
import json, pathlib
for p in ["package-lock.json","web/package-lock.json"]:
    path=pathlib.Path(p)
    if not path.exists():
        continue
    data=json.loads(path.read_text())
    for k,v in data.get("packages",{}).items():
        if "node_modules/@extend-ai/react-docx" in k or k == "":
            if "`@extend-ai/react-docx`" in k or "dependencies" in v or "devDependencies" in v:
                print(k)
                for kk in ["name","version","resolved","dependencies","devDependencies"]:
                    if kk in v:
                        print(kk, v[kk])
PY

echo
echo "== try fetch package tarball metadata/listing =="
npm view `@extend-ai/react-docx`@0.6.7 dist.tarball version --json 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 6034


🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp="$(mktemp -d)"
tarball="$(npm view `@extend-ai/react-docx`@0.6.7 dist.tarball 2>/dev/null)" || exit 0
echo "== tarball: ${tarball}"
curl -LfsS "$tarball" -o "$tmp/react-docx-0.6.7.tgz"
tar -tzf "$tmp/react-docx-0.6.7.tgz"

echo
echo "== locate type declarations/source files =="
tar -xzf "$tmp/react-docx-0.6.7.tgz" -C "$tmp"
find "$tmp/package" -maxdepth 4 \( -name '*.ts' -o -name '*.tsx' -o -name '*.mts' -o -name 'package.json' \) -print | sort | sed -n '1,120p'

echo
echo "== search API symbols =="
rg -n -C3 'export .*parseDocx|export .*packageToArrayBuffer|parseDocx|packageToArrayBuffer|parts\s?:|content\s?:' "$tmp/package" 2>/dev/null || true

echo
echo "== package metadata exports =="
python3 - <<'PY'
import json
from pathlib import Path
p = Path("$tmp/package/package.json").expanduser()
# npm view resolves home, but package.json exists after tar extraction; use literal if unresolved variable.
p = Path("/tmp")
PY
# We need actual temp path, so rerun simpler.
python3 - "$tmp" <<'PY'
import json, sys
tmp = sys.argv[1]
pjson = json.load(open(f"{tmp}/package/package.json"))
for k in ["name","version","main","module","types","exports"]:
    if k in pjson:
        print(k, pjson[k])
PY

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp="$(mktemp -d)"
tarball="$(npm view `@extend-ai/react-docx`@0.6.7 dist.tarball 2>/dev/null)" || exit 0
curl -LfsS "$tarball" -o "$tmp/react-docx-0.6.7.tgz"
tar -xzf "$tmp/react-docx-0.6.7.tgz" -C "$tmp"

echo "== package.json =="
python3 - "$tmp" <<'PY'
import json, sys
with open(sys.argv[1] + "/package/package.json") as f:
    data=json.load(f)
for k in ["name","version","main","module","types","files","exports"]:
    if k in data:
        print(k, "=", data[k])
PY

echo
echo "== type source files =="
find "$tmp/package" -type f '(' -name '*.ts' -o -name '*.tsx' -o -name '*.mts' ')' | sort | sed -n '1,120p'

echo
echo "== type declarations matching API symbols =="
find "$tmp/package" -type f '(' -name '*.d.ts' -o -name '*.ts' ')' | sort | while read -r f; do
  if rg -q 'parseDocx|packageToArrayBuffer|interface .*Docx|type .*Docx|content\s*:' "$f"; then
    echo "--- $f"
    rg -n -C6 'parseDocx|packageToArrayBuffer|interface .*Docx|type .*Docx|parts\s*?:|content\s*?:' "$f"
  fi
done

Repository: infiniflow/ragflow

Length of output: 26561


Update the DOCX load flow to match parseDocx’s returned promise.

packageToArrayBuffer and the package shape are consistent with @extend-ai/[email protected], but parseDocx(ArrayBuffer) returns Promise<OoxmlPackage>. Await the parsed package before reading parts or calling packageToArrayBuffer.

🤖 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 6 - 7,
Update the DOCX loading flow around parseDocx to await its returned
Promise<OoxmlPackage> before accessing parts or passing the package to
packageToArrayBuffer, preserving the existing package-processing behavior after
resolution.

Comment on lines +59 to +60
const replaceDocDefaults = (next: string) =>
stylesXml.replace(docDefaults, next);

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Escape the replacement string in String.prototype.replace.

replace interprets $&, $`, $', and $1 in the replacement string. The replacement values here derive from document XML, so a document that contains such a sequence produces corrupted output. Escape $ in the replacement, or use a replacer function.

🛠️ Proposed fix
   const replaceDocDefaults = (next: string) =>
-    stylesXml.replace(docDefaults, next);
+    stylesXml.replace(docDefaults, () => next);
   const replacePprDefault = (next: string) =>
-    replaceDocDefaults(docDefaults.replace(pprDefault, next));
+    replaceDocDefaults(docDefaults.replace(pprDefault, () => next));

Also applies to: 82-83

🤖 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 59 - 60,
Update replaceDocDefaults so document-derived XML is inserted without
String.prototype.replace interpreting dollar replacement tokens; use a replacer
function or escape dollar signs before replacement. Apply the same correction to
the corresponding replacement at the additional referenced location, preserving
the existing XML content.

Comment on lines +62 to +79
const pprDefault = docDefaults.match(
/<w:pPrDefault\b[^>]*>[\s\S]*?<\/w:pPrDefault>/i,
)?.[0];
if (!pprDefault) {
const selfClosing = docDefaults.match(/<w:pPrDefault\b[^>]*\/>/i)?.[0];
if (selfClosing) {
return replaceDocDefaults(
docDefaults.replace(selfClosing, DEFAULT_LINE_SPACING_PPR_DEFAULT),
);
}
const docDefaultsOpen = docDefaults.match(/<w:docDefaults\b[^>]*>/i)?.[0];
if (!docDefaultsOpen) return stylesXml;
return replaceDocDefaults(
docDefaults.replace(
docDefaultsOpen,
`${docDefaultsOpen}${DEFAULT_LINE_SPACING_PPR_DEFAULT}`,
),
);

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Insert the new elements at schema-valid positions.

OOXML uses ordered sequences, not free-form children.

  • Line 74-79 inserts w:pPrDefault directly after the <w:docDefaults> open tag. CT_DocDefaults requires w:rPrDefault before w:pPrDefault. If the document already defines w:rPrDefault, the output order is invalid.
  • Line 107-109 inserts w:spacing directly after the <w:pPr> open tag. CT_PPrBase places w:spacing after elements such as w:pStyle, w:numPr, w:pBdr, w:shd, and w:widowControl. If any of those elements exist, the output order is invalid.

Insert w:pPrDefault before </w:docDefaults> instead, and place w:spacing after the preceding CT_PPrBase elements. A DOM-based edit with DOMParser and XMLSerializer would make the ordering rules easier to express than the current regex chain.

Also applies to: 97-110

🤖 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 62 - 79,
Update the document-default and paragraph-property insertion logic in the
relevant doc-preview helper: insert the generated w:pPrDefault immediately
before </w:docDefaults> so any existing w:rPrDefault remains first, and insert
w:spacing after existing CT_PPrBase predecessors such as w:pStyle, w:numPr,
w:pBdr, w:shd, and w:widowControl rather than after the opening w:pPr tag.
Prefer DOMParser/XMLSerializer or equivalent ordered-node manipulation over
regex insertion while preserving existing replacement behavior.

Comment on lines +85 to +95
const spacingTag = pprDefault.match(/<w:spacing\b[^>]*?\/?>/i)?.[0];
if (spacingTag) {
// A default line spacing already exists; respect the document.
if (/\bw:line\s*=/i.test(spacingTag)) return stylesXml;
let tag = spacingTag.replace(/\s*\/?>$/, '');
tag += ` w:line="${DEFAULT_LINE_SPACING_TWIPS}"`;
if (!/\bw:lineRule\s*=/i.test(spacingTag)) {
tag += ' w:lineRule="auto"';
}
return replacePprDefault(pprDefault.replace(spacingTag, `${tag}/>`));
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The w:spacing lookup can match a run-level spacing element.

pprDefault contains a w:pPr element. In OOXML, w:pPr may contain a w:rPr child that holds the paragraph mark run properties. w:rPr allows its own <w:spacing w:val="..."/> element for character spacing. If the paragraph properties define no w:spacing but the run properties do, the regex at Line 85 matches the run-level element. The code then adds w:line and w:lineRule to a run-level w:spacing, which is invalid, and the paragraph default spacing is never set.

Restrict the search to the w:pPr content and exclude the w:rPr subtree before you match w:spacing.

🤖 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 85 - 95,
Update the spacing lookup around `spacingTag` so it searches only direct `w:pPr`
content, excluding any nested `w:rPr` subtree before matching `w:spacing`.
Preserve the existing behavior for paragraph-level spacing while ensuring
run-level character spacing is ignored and a valid paragraph default is created
when needed.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this fix! The CJK text overlap issue in docx previews is a real UX problem, and the root cause analysis is spot-on — @extend-ai/react-docx computes line height as fontSize × 0.88 which is too tight for CJK glyphs.

What I like

  1. Conservative patching: Only injects w:line="312" when the document doesn't already define a default line spacing. Paragraphs and styles with explicit spacing are left untouched. This respects the document author's intent.

  2. Graceful fallback: The try/catch wrapping ensures that any unpacking/repacking failure returns the original blob — the preview still works (with the old rendering), rather than breaking entirely.

  3. Idempotent: The early return when patched === stylesPart.content avoids unnecessary repacking when the spacing already exists.

  4. Good PR description: Clear problem statement, root cause, and verification approach.

Suggestions

  1. Regex-based XML manipulation: The ensureDefaultLineSpacing function uses regexes against raw XML strings. OOXML styles.xml has a well-known structure and this is pragmatic, but it is inherently fragile. A few edge cases that could slip through:

    • XML with attributes quoted in single quotes (w:line='360')
    • Namespace prefix variations (unlikely in styles.xml but possible)
    • Comment or PI nodes between elements

    The fallback-to-original-blob pattern mitigates the risk. If you're open to a follow-up, a DOM-based approach (e.g., using the browser's DOMParser) would be more robust, but I won't block on this for the current fix.

  2. Performance: parseDocx → modify → packageToArrayBuffer adds overhead on every preview load. For large docx files, this could add noticeable latency. Consider whether the result could be cached (e.g., by URL or content hash) to avoid re-processing on re-renders. Not a blocker for the initial fix.

  3. Export scope: normalizeDocxLineSpacing and ensureDefaultLineSpacing are exported (export const) but only used within this file. Consider making them non-exported (const) unless they're intended to be part of the module's public API.

  4. DEFAULT_LINE_SPACING_TWIPS = 312: This is 1.3 lines (312÷240). Some CJK fonts' natural line height is closer to 1.5×. 1.3 is a reasonable default but might still feel tight for some documents. This is subjective — what you have is a good baseline.

Summary

Clean, well-scoped fix with proper safety nets. Approved with the minor suggestions above. Nice work!

@wangq8
wangq8 requested a review from dcc123456 August 3, 2026 03:18
@wangq8
wangq8 merged commit f9fd764 into infiniflow:main Aug 3, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants