Repository navigation
Fix overlapping CJK text lines in docx file preview - #17693
Conversation
@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.
📝 WalkthroughWalkthroughThe 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. ChangesDOCX Preview Normalization
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested reviewers: 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
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
web/src/components/document-preview/doc-preview.tsx (1)
32-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename 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, andDEFAULT_LINE_SPACING_PPR_DEFAULTto PascalCase. The guidelines also ask you to keep components lean. MoveensureDefaultLineSpacingandnormalizeDocxLineSpacinginto 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
📒 Files selected for processing (1)
web/src/components/document-preview/doc-preview.tsx
| packageToArrayBuffer, | ||
| parseDocx, |
There was a problem hiding this comment.
🗄️ 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.jsonRepository: 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 || trueRepository: 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])
PYRepository: 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
doneRepository: 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.
| const replaceDocDefaults = (next: string) => | ||
| stylesXml.replace(docDefaults, next); |
There was a problem hiding this comment.
🗄️ 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.
| 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}`, | ||
| ), | ||
| ); |
There was a problem hiding this comment.
🗄️ 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:pPrDefaultdirectly after the<w:docDefaults>open tag.CT_DocDefaultsrequiresw:rPrDefaultbeforew:pPrDefault. If the document already definesw:rPrDefault, the output order is invalid. - Line 107-109 inserts
w:spacingdirectly after the<w:pPr>open tag.CT_PPrBaseplacesw:spacingafter elements such asw:pStyle,w:numPr,w:pBdr,w:shd, andw: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.
| 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}/>`)); | ||
| } |
There was a problem hiding this comment.
🎯 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
left a comment
There was a problem hiding this comment.
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
-
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. -
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.
-
Idempotent: The early return when
patched === stylesPart.contentavoids unnecessary repacking when the spacing already exists. -
Good PR description: Clear problem statement, root cause, and verification approach.
Suggestions
-
Regex-based XML manipulation: The
ensureDefaultLineSpacingfunction uses regexes against raw XML strings. OOXMLstyles.xmlhas 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. - XML with attributes quoted in single quotes (
-
Performance:
parseDocx→ modify →packageToArrayBufferadds 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. -
Export scope:
normalizeDocxLineSpacingandensureDefaultLineSpacingare 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. -
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!
Summary
In the file manager's document preview for
.docxfiles, 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-docxcomputes the line height of paragraphs that do not declare explicit line spacing asfontSize × 0.88. Each line is absolutely positioned with an inlineline-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 intoword/styles.xmlonly 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.