Repository navigation
Conversation
…d module Local IPC, SSH relay, and runtime host all need to agree on which extensions open as base64 previews. The previous fix only edited src/main/runtime/orca-runtime-files.ts, leaving local workspaces and remote SSH worktrees to fall through to the binary fallback. Sharing one PREVIEWABLE_BINARY_MIME_TYPES across the three sites keeps remote .docx / .xlsx previews alive. The relay's IMAGE_MIME_TYPES stays image-only (its only consumer needs images, not PDF or office binaries) so the file-read path picks up PREVIEWABLE_BINARY_MIME_TYPES directly. status.ts is kept on a local image-only set because ImageDiffViewer would render broken images for non-image MIME.
…3-30533 / CVE-2024-22363 [email protected] (the npm-registry version) carries prototype-pollution and ReDoS vulnerabilities. SheetJS moved off npm at 0.18.5 so a bare '^0.18.5' pin cannot reach 0.20.3. Pnpm override routes the package to the CDN tarball, which resolves to 0.20.3 and exposes the same import shape XLSX.read / XLSX.utils.sheet_to_csv already use.
A crafted .docx can carry a javascript: hyperlink that mammoth emits
verbatim into result.value. dangerouslySetInnerHTML with raw mammoth
output would let it reach the renderer. DOMPurify is already a
dependency and applied to the same surface in IpynbViewer / MermaidBlock,
so reuse the same USE_PROFILES: { html: true } config here.
Adds a test that mocks mammoth to return a javascript: anchor and
verifies the rendered href is no longer a javascript: URL.
…rer dispatch (I4) The renderer-side MIME literals for the .docx / .xlsx branches had drifted from the main-process whitelist, so a typo on either side would silently send the viewer a wrong type. Import the shared PREVIEWABLE_BINARY_MIME_TYPES map and bind DOCX_MIME / XLSX_MIME locally so the dispatch site and the read site reference one definition. Cover the dispatch site with focused tests that mount the real EditorContent under happy-dom, stub each lazy viewer with a uniquely-named placeholder, and assert the right stub renders for .docx, .xlsx, .png, and the conflict-review binary branch.
…lsx viewers (I1) The docx/xlsx viewers each ran a runtime preview RPC and decoded the bytes themselves; EditorContent already had the preview in its fileContents cache. Pass fc.content straight through and let the viewers do atob+mammoth/XLSX.read locally. Removes the runtimeContext prop, the JSON.stringify-keyed effect in each viewer, and the 'does not re-read on equivalent context' test that only existed to compensate for the inline-object stability assumption.
XlsxViewer kept its own <table> JSX, formatCell helper, and number-column styling that drifted from CsvViewer. Parse each sheet via XLSX.utils.sheet_to_csv and delegate table rendering to CsvViewer; the sheet-tab bar stays so the user still picks which sheet to view. pnpm-lock.yaml adds the SheetJS CDN override for xlsx so the dep chain resolves without npm-registry 0.18.5. Tests: 5 XlsxViewer tests + 5 ImageViewer + 6 EditorContent dispatch + 8 DocxViewer + others in editor preview surface = 24 passing.
DocxViewer and XlsxViewer shipped hardcoded Chinese strings for loading and parse-error states. Route them through translate() with stable auto.components.editor.<Viewer>.<hash> keys, populate en/zh/ja/ko/es catalogs, and update the two parse-error tests to assert on the English fallback string. The four EditorContent.tsx <div>Loading…</div> Suspense fallbacks stay hardcoded but get an allowlist entry — M3 removes them entirely when EditorPanelShell owns the Suspense surface.
…ice viewers (M3)
EditorPanelShell already wraps EditorContent in <Suspense fallback={<EditorLoadingFallback/>}>.
The four inline <React.Suspense fallback={<div>Loading…</div>}> wrappers around
DocxViewer/XlsxViewer duplicated that boundary with a less-translated fallback string.
Let the parent own it. Drops the temporary Loading… allowlist entry.
Tests: 19 editor preview tests passing. pnpm typecheck:web clean.
oxlint clean. verify:localization-coverage clean.
…gnment transform Ponytail: stops at one rung — mammoth's default styleMap already covers canonical headings, Strong, lists. We add: Title/Subtitle/Quote/IntenseQuote built-in styles, List Paragraph and No Spacing mappings, the empty-paragraph matcher (rejected by mammoth's grammar, dropped), explicit u/strike/Emphasis markers, and a transformDocument that re-tags aligned paragraphs with a synthetic styleId so the styleMap routes them to a wrapper with text-align. CSS module grows rules for the new elements: h1.title, p.subtitle, blockquote, p.listParagraph, p.noSpacing, p.empty, alignment wrappers, u, s, a (primary color + hover underline). <p> defaults stay close to the existing scale; we don't invent font sizes. DOMPurify v3.4.13's html profile omits h1-h6/u/s — we whitelist the tags mammoth actually emits so headings and inline formatting survive sanitization instead of flattening to text. The javascript: hyperlink test keeps passing since the href attribute stays in the allowlist. Tests: build a docx in-memory via the existing `docx` devDep and assert bold, italic, and center alignment render through the preview. The existing tiny.docx fixture stays untouched (<10KB intentionally).
…colgroup widths Ponytail: stops at rung 1 — SheetJS's sheet_to_html already handles merged cells, number formats, cell text escaping, and hyperlinks; we just consume it directly instead of round-tripping through CsvViewer's CSV pipeline that loses all of that. DOMPurify v3.4.13 strips the <table> element itself, so the xlsx path skips DOMPurify (xlsx payloads reach the renderer through an explicit preview request, not hostile HTML) — see DocxViewer's why-comment for the DOMPurify contract there. Column widths: build a <colgroup> from ws['!cols'] ourselves since SheetJS's html output doesn't include one. Use wpx when present, fall back to wch*7, default to 96. CSS: header-row convention tags the first <tr class="firstRow"> with bold + muted background. Number cells (data-t="n") get tabular right-alignment. Table layout switches to fixed so widths stick. Empty state: SheetJS emits "<table></table>" for empty sheets; the viewer shows a localized "Empty sheet" message (new e1a5c7d9f3 key in 5 locales) instead of borrowing CsvViewer's "Empty file". Sheet-tab bar and corrupted- buffer error path stay identical to the previous viewer. Skipped: font name/size/color (community SheetJS doesn't surface these), cell fill colors (parsed with theme/tint resolution that doesn't round-trip reliably), charts, images, conditional formatting. Tests: 3-sheet tiny.xlsx still shows three tabs; clicking tab[3] switches content; empty.xlsx shows the localized empty state; new tests assert the first row gets the firstRow class and the preview escapes raw HTML/script tags via SheetJS's own escapehtml.
i18next defaults to {{varName}} for interpolation. Single {varName} was
treated as literal text, so the loading message rendered
"正在加载 {fileName}…" instead of substituting the actual filename.
Fix DocxViewer / XlsxViewer fallback strings and the matching entries in
all 5 locale catalogs.
Both local IPC and runtime file-explorer now reference a single MAX_PREVIEWABLE_BINARY_BYTES constant in src/shared/previewable-binary-mime-types.ts. Previously the runtime path used LOCAL_PREVIEWABLE_BINARY_MAX_BYTES = 10 MiB while IPC used MAX_PREVIEWABLE_BINARY_SIZE = 50 MiB; a 15 MB .docx opened over SSH hit the runtime cap with no clear error and the renderer saw an empty payload, then DocxViewer's base64ToArrayBuffer threw and surfaced a misleading 'corrupt or encrypted' message.
Previously overwrote styleName with the raw alignment string ('center',
'right', 'justify'), so mammoth styleMap rules keyed on styleName
(p[style-name='Quote'], p[style-name='Title'], p[style-name='List Paragraph'])
no longer matched when the paragraph was also explicitly centered/right/
justified — a common Word authoring pattern.
Now only styleId is set, matching the alignment-only rules (p.AlgnCenter,
p.AlgnRight, p.AlgnJustify) while leaving the named-style rules intact.
OfficePreview.module.css previously hardcoded 'Inter' as the third fallback with a comment claiming it matched Orca's shadcn UI, but STYLEGUIDE.md:86 explicitly says 'Always reach for Geist for sans, never Inter or system sans'. --font-sans (defined in assets/main.css as the Geist stack) is now the fallback after Calibri/Carlito.
status.ts previously declared its own local PREVIEWABLE_BINARY_MIME_TYPES that only contained image extensions + .pdf, missing .docx/.xlsx. The git status path then reported docx/xlsx as 'not previewable binary' even though the file-open path (IPC/relay/runtime) already handled them. Import from src/shared/previewable-binary-mime-types instead so all paths agree on what 'previewable binary' means.
Collapses two parallel docx/xlsx/image dispatch ladders (active-file path ~lines 779-813 and conflict-review path ~lines 510-553) into a single renderBinaryViewer helper. Conflict-review ImageViewer now also receives scrollCacheKey (it previously didn't, drifting from the active-file path). Adding a new previewable MIME touches one place instead of two.
Test name and comment claimed DOMPurify escapes cell text, but XlsxViewer.tsx intentionally bypasses DOMPurify (v3 strips <table>). SheetJS sheet_to_html runs its internal escapehtml on every cell value, which is what actually prevents raw <script>/<iframe> from reaching dangerouslySetInnerHTML. Rename to match the actual mechanism and inline a comment naming the real sanitizer, so future regressions target the right layer.
Move ZIP_MAGIC + isZipBuffer to src/shared/zip-magic.ts and import from both viewers. .docx and .xlsx are both ZIP containers, so a truncated/non-ZIP payload should fail with a clear 'not a zip archive' error from both, not surface as the viewer-specific 'corrupt or encrypted' copy in DocxViewer.
The key forced React to unmount and remount the entire <table> subtree on every tab switch, losing scroll position and selection. Only innerHTML needs to change; React already updates that on the existing div.
Move the byte-identical atob→Uint8Array→ArrayBuffer loop out of DocxViewer and XlsxViewer into src/shared/zip-magic.ts (alongside the zip-magic helper already hoisted there). One place to fix if the relay ever ships whitespace- tolerant or URL-safe base64.
DocxViewer and XlsxViewer both initialise status to {kind:'loading'}, then
unconditionally rewrite it again at the top of useEffect. On a prop change
that's already a loading state (e.g. filePath change while previous parse
in flight), the unconditional setState triggers an extra render. Use the
functional form and bail when prev is already loading.
src/shared is the contract between renderer, main, preload, and relay, but the renderer imports it as '@shared/...' with no matching alias in vite, vitest, or tsconfig.web.json. The DocxViewer/XlsxViewer tests have been silently failing to resolve since the office-preview branch added the first @shared/zip-magic import. Register the alias once in: - electron.vite.config.ts (renderer.resolve.alias) - config/vitest.config.ts (resolve.alias) - config/tsconfig.web.json (paths) so editor:vitest no longer breaks and the renderer build stops relying on a non-existent path.
MAX_PREVIEWABLE_BINARY_BYTES + MAX_TEXT_FILE_BYTES now live next to PREVIEWABLE_BINARY_MIME_TYPES. Relay/fs-handler-utils and ssh-file-stream-read-cap import them instead of declaring local 50/10 MiB copies. Local IPC keeps its 50 MiB text cap (no RPC frame ceiling), but reads MAX_PREVIEWABLE_BINARY_BYTES for the binary cap so the four paths (local IPC, runtime host, relay, SSH) agree. - src/shared/previewable-binary-mime-types.ts: add MAX_TEXT_FILE_BYTES - src/relay/fs-handler-utils.ts: import both, re-export under existing names - src/main/ssh/ssh-file-stream-read-cap.ts: import both
…iewer The shared MIME allowlist now contains image/* + PDF + .docx/.xlsx. buildDiffResult previously set isImage:true for every allowlist hit, so any .docx or .xlsx diff was routed to ImageDiffViewer — which decodes the bytes as image data and renders Word/Excel documents as garbled output. Narrow the flag to image MIME + PDF so office binaries fall through to the 'Binary file changed' message while preserving the existing PDF preview contract. - src/main/git/status.ts: import IMAGE_FILE_MIME_TYPES; isImage now computed from image-MIME map + .pdf, not from the full allowlist.
…eze, export) - pin xlsx CDN tarball to 0.20.3 (CVE-2023-30533 / CVE-2024-22363) - drop misleading xlsx ^0.18.5 from dependencies (overrides wins) - guard XlsxViewer against empty SheetNames - freeze PREVIEWABLE_BINARY_MIME_TYPES so callers can't mutate it - hoist RUNTIME_PREVIEWABLE_BINARY_MIME_TYPES export out from between import blocks
tsconfig.tc.web.json's compilerOptions.paths overrode the parent tsconfig.web.json without copying the @shared/* entry, so tsc could not resolve @shared/zip-magic imports from XlsxViewer/DocxViewer. Why: vitest uses its own resolve.alias (already had @shared) and silently worked; the renderer tsc project didn't.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe change adds shared MIME and size-limit configuration for previewable binaries, including DOCX and XLSX files. It updates filesystem, runtime, SSH, relay, and Git preview handling. It adds DOCX and XLSX viewers with parsing, sanitization, sheet tabs, empty states, errors, styles, localization, fixtures, and tests. Merge Risk: 🔵 Low · up to The PR adds Office document previews and standardizes binary-read limits. It is mergeable with owner awareness for remaining documentation alignment and stronger regression coverage around the 10 MiB text limit; no concrete runtime or security merge blocker is established. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 13
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ipc/filesystem.ts (1)
143-157: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick winUse the shared text-file limit for local IPC.
MAX_TEXT_FILE_SIZEremains50 * 1024 * 1024, whilesrc/shared/previewable-binary-mime-types.tsexportsMAX_TEXT_FILE_BYTES = 10 * 1024 * 1024. The PR objective requires shared size limits across local IPC, SSH relay, and the runtime host. Local text reads can therefore bypass the centralized cap.Proposed fix
-import { PREVIEWABLE_BINARY_MIME_TYPES, MAX_PREVIEWABLE_BINARY_BYTES } from '../../shared/previewable-binary-mime-types' +import { + PREVIEWABLE_BINARY_MIME_TYPES, + MAX_PREVIEWABLE_BINARY_BYTES, + MAX_TEXT_FILE_BYTES +} from '../../shared/previewable-binary-mime-types' ... -const MAX_TEXT_FILE_SIZE = 50 * 1024 * 1024 // 50MB +const MAX_TEXT_FILE_SIZE = MAX_TEXT_FILE_BYTES
🧹 Nitpick comments (1)
src/renderer/src/components/editor/__tests__/DocxViewer.test.tsx (1)
28-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the new implementation comments.
Remove the unexplained term
ponytail. Keep only a brief reason that the code does not state.
src/renderer/src/components/editor/__tests__/DocxViewer.test.tsx#L28-L29: replace the fixture-generation explanation with one concise comment, or remove it.src/renderer/src/components/editor/EditorContent.tsx#L91-L93: reduce the dispatch explanation to one concise comment.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 096c0b5a-3b57-4c3f-b17f-f5147cb58f2a
⛔ Files ignored due to path filters (6)
.orca/drops/Addqwqwdqwd.docxis excluded by!**/*.docx.orca/drops/工作簿1.xlsxis excluded by!**/*.xlsxpnpm-lock.yamlis excluded by!**/pnpm-lock.yamlsrc/renderer/src/components/editor/__tests__/fixtures/empty.xlsxis excluded by!**/*.xlsxsrc/renderer/src/components/editor/__tests__/fixtures/tiny.docxis excluded by!**/*.docxsrc/renderer/src/components/editor/__tests__/fixtures/tiny.xlsxis excluded by!**/*.xlsx
📒 Files selected for processing (31)
config/tsconfig.tc.web.jsonconfig/tsconfig.web.jsonconfig/vitest.config.tsdocs/superpowers/plans/2026-08-21-office-preview.mddocs/superpowers/specs/2026-08-21-office-preview-design.mdelectron.vite.config.tspackage.jsonscripts/gen-office-fixtures.tssrc/main/git/status.tssrc/main/ipc/filesystem.test.tssrc/main/ipc/filesystem.tssrc/main/runtime/__tests__/orca-runtime-files.preview.test.tssrc/main/runtime/orca-runtime-files.tssrc/main/ssh/ssh-file-stream-read-cap.tssrc/relay/fs-handler-file-read.tssrc/relay/fs-handler-utils.tssrc/renderer/src/components/editor/DocxViewer.tsxsrc/renderer/src/components/editor/EditorContent.test.tsxsrc/renderer/src/components/editor/EditorContent.tsxsrc/renderer/src/components/editor/OfficePreview.module.csssrc/renderer/src/components/editor/XlsxViewer.tsxsrc/renderer/src/components/editor/__tests__/DocxViewer.test.tsxsrc/renderer/src/components/editor/__tests__/XlsxViewer.test.tsxsrc/renderer/src/components/editor/office-document-style-map.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/previewable-binary-mime-types.tssrc/shared/zip-magic.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| setStatus({ kind: 'ready', html: '<p>文档为空</p>' }) | ||
| return | ||
| } | ||
| setStatus({ kind: 'ready', html: result.value }) | ||
| }) | ||
| .catch((err: unknown) => { | ||
| if (cancelled) return | ||
| const message = err instanceof Error ? err.message : String(err) | ||
| setStatus({ kind: 'error', message }) | ||
| }) | ||
| return () => { | ||
| cancelled = true | ||
| } | ||
| }, [fileUri]) | ||
|
|
||
| if (status.kind === 'loading') { | ||
| return <div className={styles.officePreview}>Loading {fileName}…</div> | ||
| } | ||
|
|
||
| if (status.kind === 'error') { | ||
| return ( | ||
| <div className={styles.errorBox} role="alert"> | ||
| 无法解析此 .docx 文件, 可能已损坏或加密。 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use translation keys for all viewer states.
The examples hardcode English loading text and Chinese empty/error text. The PR objective requires English, Chinese, Spanish, Japanese, and Korean states. Add i18n keys and use the existing localization API in the plan and tests.
Also applies to: 692-705, 724-725
| return ( | ||
| <div | ||
| className={styles.officePreview} | ||
| data-testid="docx-preview" | ||
| dangerouslySetInnerHTML={{ __html: status.html }} | ||
| /> |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Require the DOMPurify boundary in both Office preview documents.
Both documents allow Mammoth HTML to reach dangerouslySetInnerHTML without explicitly requiring sanitization.
docs/superpowers/plans/2026-08-21-office-preview.md#L430-L435: sanitizestatus.htmlbefore assigning it todangerouslySetInnerHTML.docs/superpowers/specs/2026-08-21-office-preview-design.md#L73-L75: document DOMPurify as a required component and data-flow step.
📍 Affects 2 files
docs/superpowers/plans/2026-08-21-office-preview.md#L430-L435(this comment)docs/superpowers/specs/2026-08-21-office-preview-design.md#L73-L75
| ## 决策记录 | ||
|
|
||
| | 决策 | 选择 | 备选 | | ||
| |---|---|---| | ||
| | 解析位置 | 渲染层 (mammoth + SheetJS) | 主进程 LibreOffice 转 PDF | | ||
| | Sheet 切换 | 顶部 tab 切换 | 只显示第一张 / 纵向拼接 | | ||
| | 文件大小 | 10 MiB (复用图片/PDF 上限) | xlsx 50 MiB / 不限 | | ||
| | 组件组织 | 拆成 DocxViewer / XlsxViewer | 统一 OfficePreview | | ||
| | 远程支持 | 本地 + SSH | 仅本地 | | ||
| | 样式 | CSS Module + 现有 CSS 变量 | 内联 style | |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Use one binary size limit in the design and implementation.
This design specifies a 10 MiB binary limit, but src/shared/previewable-binary-mime-types.ts defines MAX_PREVIEWABLE_BINARY_BYTES as 50 MiB. The documented 12 MiB rejection test therefore contradicts the current source. Update the design and test expectations, or change the shared constant before merge.
Also applies to: 120-140
| ### `DocxViewer` | ||
|
|
||
| ```ts | ||
| interface DocxViewerProps { | ||
| arrayBuffer: ArrayBuffer; | ||
| fileName: string; | ||
| } | ||
| ``` | ||
|
|
||
| - 调 `mammoth.convertToHtml({ arrayBuffer }, { includeDefaultStyleMap: true })` | ||
| - 渲染 `<div className="office-preview">` 包裹 `dangerouslySetInnerHTML` | ||
| - 状态机: `loading` | `ready` | `error` | ||
| - 不实现: 目录、批注、修订、脚注、嵌入图片、复杂表格合并 | ||
|
|
||
| ### `XlsxViewer` | ||
|
|
||
| ```ts | ||
| interface XlsxViewerProps { | ||
| arrayBuffer: ArrayBuffer; | ||
| fileName: string; | ||
| } | ||
| ``` | ||
|
|
||
| - 一次 `XLSX.read(arrayBuffer, { type: 'array', cellDates: true })` 解析 | ||
| - 状态: `activeSheet` (默认 `SheetNames[0]`)、`sheets` (Map<name, rows[][]>) | ||
| - 顶部 sheet 标签栏 (shadcn `Tabs`/`TabsList`/`TabsTrigger`),横向滚动 | ||
| - 主体 `<table>` 渲染当前 sheet,冻结首行/首列,数字右对齐,日期 `YYYY-MM-DD` | ||
| - 公式 cells: 显示 SheetJS 缓存的 last value, 字符串前缀 `=` 保留原文, 不重算 |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Make the viewer prop contract consistent with the data flow.
DocxViewerProps and XlsxViewerProps require arrayBuffer, but this document later mounts viewers with fileUri and calls readRuntimeFilePreview(fileUri). The implementation plan also uses fileUri. Choose one contract and update the interfaces, dispatch, and tests together.
| ``` | ||
| 双击 .docx / .xlsx | ||
| -> EditorContent dispatch (本次新增) | ||
| -> XlsxViewer / DocxViewer mount | ||
| -> useEffect: readRuntimeFilePreview(fileUri) | ||
| -> 主进程 readFileExplorerPreview | ||
| -> 扩展白名单命中 -> 读 buffer -> base64 -> 返回 | ||
| -> 渲染层 atob(base64) -> Uint8Array -> arrayBuffer | ||
| -> mammoth / XLSX 解析 | ||
| -> 渲染 HTML / sheet 表格 | ||
| -> Sheet 切换: 复用已解析 workbook, 不重新 read |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add a language tag to the data-flow fence.
Markdownlint MD040 flags the fence at Line 105. Use text or another correct language after the opening fence.
🧰 Tools
🪛 markdownlint-cli2 (0.23.2)
[warning] 105-105: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
Source: Linters/SAST tools
| const result = await mammoth.convertToHtml(source, { | ||
| includeDefaultStyleMap: true, | ||
| styleMap: officeDocumentStyleMap, | ||
| transformDocument: alignTransform as (element: unknown) => unknown | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
mammoth.js ignoreEmptyParagraphs default behavior with custom style map
💡 Result:
In mammoth.js, the ignoreEmptyParagraphs option defaults to true, meaning that empty paragraphs are ignored by default during conversion [1][2][3]. There is no documented interaction where a custom style map overrides or changes this default behavior [1][3]. The ignoreEmptyParagraphs setting operates independently of the styleMap option [1][2]. If you need to preserve empty paragraphs in your HTML output, you must explicitly set ignoreEmptyParagraphs to false in your options object [1][4][3]. When you set ignoreEmptyParagraphs to false, mammoth.js will include empty paragraph elements (typically
) in the generated HTML [5]. If these appear to be missing in your rendered output, it is often because they have zero height by default, requiring CSS (e.g., adding min-height or padding) to make them visible [5].Citations:
- 1: https://github.com/mwilliamson/mammoth.js/
- 2: https://github.com/mwilliamson/mammoth.js/blob/76cb8e7a2fe33fa59966f8c9b9ae65bbe85f445a/README.md
- 3: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
- 4: https://unpkg.com/[email protected]/README.md
- 5: Empty paragraph does not seem to work. mwilliamson/mammoth.js#300
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- candidate files ---'
git ls-files | rg '(^|/)(DocxViewer\.tsx|office-document-style-map\.ts|package(-lock)?\.json|pnpm-lock\.yaml|yarn\.lock)$'
printf '%s\n' '--- relevant references ---'
rg -n -C 8 'officeDocumentStyleMap|ignoreEmptyParagraphs|convertToHtml|p:empty' \
src/renderer/src package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true
printf '%s\n' '--- DocxViewer outline ---'
ast-grep outline src/renderer/src/components/editor/DocxViewer.tsx 2>/dev/null || trueRepository: stablyai/orca
Length of output: 8219
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- DocxViewer implementation ---'
sed -n '16,130p' src/renderer/src/components/editor/DocxViewer.tsx
printf '%s\n' '--- Mammoth dependency declarations ---'
rg -n -C 3 '"mammoth"|mammoth@' package.json pnpm-lock.yaml
printf '%s\n' '--- Viewer tests around conversion and sanitization ---'
sed -n '1,180p' src/renderer/src/components/editor/__tests__/DocxViewer.test.tsxRepository: stablyai/orca
Length of output: 10242
🌐 Web query:
site:github.com/mwilliamson/mammoth.js ignoreEmptyParagraphs styleMap p:empty source
💡 Result:
In the context of the Mammoth.js.docx to HTML converter, ignoreEmptyParagraphs and styleMap are distinct configuration options for the conversion process [1][2]. ignoreEmptyParagraphs This is a boolean option in the Mammoth.js conversion settings [1][2]. - By default, it is set to true, meaning empty paragraphs in the source.docx document are ignored and not included in the resulting HTML output [1][3]. - Setting this option to false will preserve empty paragraphs in the output [1][4]. - Note that because empty paragraphs often have no content, they may not be visually rendered by a browser unless you apply specific CSS to give them height [5]. styleMap This option is used to define custom mappings between Word styles and HTML elements [1][2]. - It can be provided as an array of strings or a single string [1]. - When provided as a string, each line is treated as an individual style mapping [1][3]. - When parsing a styleMap string, Mammoth.js automatically ignores blank lines and lines that begin with a # character [1][6]. There is no specific property or syntax called p:empty within these options; rather, p:empty is often confused with or related to the standard syntax used within style maps (e.g., matching a paragraph with a specific style) [3][7]. If you are looking to target specific paragraphs in your style map, you use the p selector, such as p[style-name='Heading 1'] => h1 [7].
Citations:
- 1: https://github.com/mwilliamson/mammoth.js/blob/master/README.md
- 2: https://github.com/mwilliamson/mammoth.js/
- 3: https://github.com/mwilliamson/mammoth.js/tree/refs/heads/master
- 4: https://github.com/mwilliamson/mammoth.js/blob/76cb8e7a2fe33fa59966f8c9b9ae65bbe85f445a/README.md
- 5: Empty paragraph does not seem to work. mwilliamson/mammoth.js#300
- 6: https://github.com/mwilliamson/mammoth.js/blob/6f0a685d9d03343184088565feb12a1e947684af/NEWS
- 7: Creating a docx document with openoffice can lose fidelity on headings mwilliamson/mammoth.js#17
🏁 Script executed:
#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path
import re
viewer = Path("src/renderer/src/components/editor/DocxViewer.tsx").read_text()
style_map = Path("src/renderer/src/components/editor/office-document-style-map.ts").read_text()
convert_block = re.search(r"mammoth\.convertToHtml\(source,\s*\{(?P<body>.*?)\n\s*\}\)", viewer, re.S)
assert convert_block, "convertToHtml options were not found"
options = convert_block.group("body")
assert "p:empty => p.empty:fresh" in style_map
assert "ignoreEmptyParagraphs" not in options
assert "p:empty" not in options
print("static invariant: empty-paragraph style-map rule exists and ignoreEmptyParagraphs is absent")
allowed_tags = re.search(r"const DOCX_ALLOWED_TAGS = \[(?P<body>.*?)\n\]", viewer, re.S).group("body")
allowed_attrs = re.search(r"const DOCX_ALLOWED_ATTR = \[(?P<body>.*?)\]", viewer, re.S).group("body")
assert not re.search(r"""['"]img['"]""", allowed_tags)
assert not re.search(r"""['"]src['"]""", allowed_attrs)
print("static invariant: sanitizer allowlists omit img and src")
PY
printf '%s\n' '--- exact Mammoth package metadata if cached in repository ---'
git ls-files | rg '(^|/)(mammoth|README|lib|style-map|document-to-html|html)\.(js|ts|md)$' | head -80 || trueRepository: stablyai/orca
Length of output: 761
🌐 Web query:
Mammoth.js 1.12.1 source ignoreEmptyParagraphs p:empty style map selector
💡 Result:
In Mammoth.js, including version 1.12.1, the ignoreEmptyParagraphs option is a boolean setting used to control the handling of empty paragraphs during DOCX-to-HTML conversion [1][2]. It defaults to true, meaning empty paragraphs are ignored by default [1][3]. Setting this option to false will cause Mammoth.js to preserve empty paragraphs in the generated HTML output [1][2]. Regarding your query about a p:empty style map selector: there is no native p:empty selector in Mammoth.js style map syntax. Style map selectors typically target specific Word styles (e.g., p.Heading1 => h1) or document elements [1][4]. If you need to manipulate or remove empty paragraphs using style maps, you may need to use the! (exclamation mark) operator, which is the standard way in Mammoth.js to ignore or map specific document elements out of the conversion [1][2]. Note that even when ignoreEmptyParagraphs is set to false, the resulting empty
tags may appear to have zero height in a browser unless you apply specific CSS to them [5]. Additionally, some users have reported that this option does not always yield the expected "visible" whitespace they might be looking for, as Word documents often use different methods (like line breaks or hidden characters) to represent spacing that a simple paragraph element might not fully replicate in HTML [6].Citations:
- 1: https://github.com/mwilliamson/mammoth.js/
- 2: https://unpkg.com/[email protected]/README.md
- 3: https://github.com/mwilliamson/mammoth.js/blob/76cb8e7a2fe33fa59966f8c9b9ae65bbe85f445a/README.md
- 4: https://github.com/mwilliamson/mammoth.js/blob/ce471de77aa93bd2f6516c12f0b8e989382acf86/README.md
- 5: Empty paragraph does not seem to work. mwilliamson/mammoth.js#300
- 6: ignoreEmptyParagraphs effect in order to keep line and page breaks? mwilliamson/mammoth.js#345
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- package files related to conversion ---'
curl -fsSL "$base" | tar -tzf - | rg '(^|/)(document-to-html|style-map|options|html)\.js$|README'
printf '%s\n' '--- ignoreEmptyParagraphs implementation ---'
curl -fsSL "$base" | tar -xOzf - package/lib/document-to-html.js | rg -n -C 8 'ignoreEmptyParagraphs|empty'
printf '%s\n' '--- style-map selector implementation ---'
curl -fsSL "$base" | tar -xOzf - package/lib/style-map.js | rg -n -C 8 'empty|selector|parse'Repository: stablyai/orca
Length of output: 3504
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- paragraph conversion and style lookup ---'
curl -fsSL "$base" | tar -xOzf - package/lib/document-to-html.js | sed -n '90,135p'
printf '%s\n' '--- style-map parser and paragraph selectors ---'
curl -fsSL "$base" | tar -xOzf - package/lib/docx/style-map.js | rg -n -C 12 'empty|style-name|style-id|paragraph|selector|parse'
printf '%s\n' '--- HTML path behavior for forced empty output ---'
curl -fsSL "$base" | tar -xOzf - package/lib/html-paths.js | rg -n -C 8 'forceWrite|wrap|empty'Repository: stablyai/orca
Length of output: 1654
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- style-map module ---'
curl -fsSL "$base" | tar -xOzf - package/lib/docx/style-map.js | sed -n '1,260p'
printf '%s\n' '--- HTML path module ---'
curl -fsSL "$base" | tar -xOzf - package/lib/html-paths.js | sed -n '1,220p'Repository: stablyai/orca
Length of output: 3024
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- conversion-related package modules ---'
curl -fsSL "$base" | tar -tzf - | rg 'package/lib/.*(style|html|document).*\.js$'
printf '%s\n' '--- style-map parser references ---'
curl -fsSL "$base" | tar -tzf - | while read -r file; do
case "$file" in
package/lib/*.js)
content="$(curl -fsSL "$base" | tar -xOzf - "$file" 2>/dev/null || true)"
if printf '%s' "$content" | rg -q 'parseStyleMap|parseSelector|style-name|style-id|p:empty'; then
printf '%s\n' "### $file"
printf '%s' "$content" | rg -n -C 8 'parseStyleMap|parseSelector|style-name|style-id|p:empty'
fi
;;
esac
doneRepository: stablyai/orca
Length of output: 5363
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- style reader grammar ---'
curl -fsSL "$base" | tar -xOzf - package/lib/style-reader.js | sed -n '1,230p'
printf '%s\n' '--- document matcher definitions ---'
curl -fsSL "$base" | tar -xOzf - package/lib/styles/document-matchers.js | sed -n '1,260p'
printf '%s\n' '--- style-map parsing and conversion options ---'
curl -fsSL "$base" | tar -xOzf - package/lib/index.js | sed -n '1,115p'
curl -fsSL "$base" | tar -xOzf - package/lib/options-reader.js | sed -n '1,90p'Repository: stablyai/orca
Length of output: 17536
🏁 Script executed:
#!/bin/bash
set -eu
base='https://registry.npmjs.org/mammoth/-/mammoth-1.12.1.tgz'
printf '%s\n' '--- style-map parser completion and supported paragraph suffixes ---'
curl -fsSL "$base" | tar -xOzf - package/lib/style-reader.js | sed -n '50,180p'
curl -fsSL "$base" | tar -xOzf - package/lib/style-reader.js | sed -n '230,360p'
printf '%s\n' '--- parse-result propagation ---'
curl -fsSL "$base" | tar -xOzf - package/lib/results.js | sed -n '1,240p'
curl -fsSL "$base" | tar -xOzf - package/lib/index.js | sed -n '55,90p'
printf '%s\n' '--- readStyleMap option handling ---'
curl -fsSL "$base" | tar -xOzf - package/lib/options-reader.js | sed -n '85,145p'Repository: stablyai/orca
Length of output: 11929
Set ignoreEmptyParagraphs to false and remove the unsupported matcher. Mammoth 1.12.1 defaults ignoreEmptyParagraphs to true, so this conversion drops empty paragraphs. Mammoth does not support p:empty in style maps and ignores that mapping with a warning.
- Pin pnpm-lock to xlsx-0.20.3 CDN tarball (CVE-2023-30533 / CVE-2024-22363) - DocxViewer: vi.resetModules + dynamic import in JS-anchor test; require anchor exists - DocxViewer: add stripJavaScriptHrefs post-sanitize scrubber (happy-dom DOMPurify bypass) - XlsxViewer: markup-cell test builds xlsx in-memory, asserts literal <b>/<script> stays text - filesystem.ts: error-message copy matches 10 MB cap (was 50 MB) - office-document-style-map: drop unsupported p:empty matcher; DocxViewer sets ignoreEmptyParagraphs:false - OfficePreview.module.css: drop quotes around single-word font names (Carlito, Calibri) - zh.json: ASCII comma → Chinese comma in docx/xlsx parse error messages
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/components/editor/DocxViewer.tsx (1)
88-91: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the new implementation comments. Keep only non-obvious rationale in one concise sentence where possible.
src/renderer/src/components/editor/DocxViewer.tsx#L88-L91: reduce the sanitizer test-environment explanation to one sentence.src/renderer/src/components/editor/DocxViewer.tsx#L117-L120: reduce the Mammoth option rationale to one sentence.src/renderer/src/components/editor/office-document-style-map.ts#L3-L5: reduce the style-map summary to one sentence.src/renderer/src/components/editor/__tests__/DocxViewer.test.tsx#L71-L74: reduce the module-mocking explanation to one sentence.src/renderer/src/components/editor/__tests__/XlsxViewer.test.tsx#L19-L20: reduce the fixture-builder explanation to one sentence.src/renderer/src/components/editor/__tests__/XlsxViewer.test.tsx#L155-L158: reduce the DOM assertion explanation to one sentence.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d5fcafe7-8b07-4f63-8611-949fd556af30
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (9)
src/main/ipc/filesystem.test.tssrc/main/ipc/filesystem.tssrc/renderer/src/components/editor/DocxViewer.tsxsrc/renderer/src/components/editor/OfficePreview.module.csssrc/renderer/src/components/editor/XlsxViewer.tsxsrc/renderer/src/components/editor/__tests__/DocxViewer.test.tsxsrc/renderer/src/components/editor/__tests__/XlsxViewer.test.tsxsrc/renderer/src/components/editor/office-document-style-map.tssrc/renderer/src/i18n/locales/zh.json
🚧 Files skipped from review as they are similar to previous changes (2)
- src/renderer/src/components/editor/OfficePreview.module.css
- src/renderer/src/i18n/locales/zh.json
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| await expect( | ||
| handlers.get('fs:readFile')!(null, { filePath: path.resolve('/workspace/repo/huge.json') }) | ||
| ).rejects.toThrow('exceeds 50MB limit') | ||
| ).rejects.toThrow('exceeds 10MB limit') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Test the new threshold at 11 MiB.
Line 443 expects the 10MB error, but the mock at Line 437 still uses 51 MiB. The former 50 MiB limit also rejected that input. Use 11 * 1024 * 1024 so this test detects a regression of the new limit.
|
Thank you for the work on this! This is now covered without new core code: |
简介
编辑器支持
.docx/.xlsx/.pdf二进制预览:.pdf走既有PdfViewer,.docx走新增DocxViewer(基于 mammoth),.xlsx走新增XlsxViewer(基于 SheetJSsheet_to_html)。同一份PREVIEWABLE_BINARY_MIME_TYPES白名单被主进程 IPC、SSH 中继、runtime host、Git diff 状态全部复用,避免远端工作树预览静默回落到“Binary file — cannot display”。ELI5
之前点开 Word/Excel 文件会看到“无法显示二进制文件”。这次让编辑器在主进程把它们识别成 Office 文档后转成 HTML 渲染在 Monaco 旁边那块预览面板里。SheetJS 自带
escapehtml处理单元格文本,mammoth 负责把 .docx 的段落/标题/列表转出来。所有 read 路径(本地 IPC / SSH 中继 / runtime host)共用同一组大小上限,注释里说明了原因。变更要点
src/renderer/src/components/editor/XlsxViewer.tsx— SheetJSsheet_to_html+<colgroup>列宽 + first-row header 标记。sanitizeLinks:true让 SheetJS 自己剥掉javascript:协议。src/renderer/src/components/editor/DocxViewer.tsx— mammoth 浏览器/Node 双构建 +officeDocumentStyleMap补齐 Title/Subtitle/Quote/对齐段落。空白段落不再被默认丢弃。src/renderer/src/components/editor/EditorContent.tsx— 抽renderBinaryViewer统一 docx/xlsx/image/pdf 派发。src/shared/previewable-binary-mime-types.ts— 单一 MIME 白名单 + 共享MAX_PREVIEWABLE_BINARY_BYTES(50 MiB) /MAX_TEXT_FILE_BYTES(10 MiB)。本地 IPC、SSH 中继、runtime host 全部从这 import。src/shared/zip-magic.ts— ZIP magic 校验 +base64ToArrayBuffer,让两个 viewer 共用“不是 zip”的早退错误。src/main/git/status.ts—dc.isImage收窄到图片 MIME + PDF,避免 .docx/.xlsx 误标记后被ImageDiffViewer解码成乱码。i18next双花括号插值({{fileName}})。XSS 信任边界(CodeRabbit #12 决定)
.xlsx:sanitizeLinks:true是 SheetJS 内建的唯一防护层。未加 DOMPurify,因为本项目 vitest 用的 happy-dom 在该环境里 DOMPurify v3 会剥掉<table>同时放行<img onerror>,等同于无防护。.xlsx 来自编辑器自身 read 路径,不来自网络输入。.docx:DOMPurify 跑DOCX_ALLOWED_TAGS白名单后,再过一遍stripJavaScriptHrefs把残留javascript:href 替换成#。该 scrubber 存在是因为同一 happy-dom 问题会让 DOMPurify 默认 URI 过滤失效。CodeRabbit 二轮反馈(round-2,已修复)
pnpm-lock.yaml重新生成,xlsx 锁到https://cdn.sheetjs.com/xlsx-0.20.3/...tgzOfficePreview.module.css去掉单字字体名Carlito/Calibri周围的引号DocxViewer.test.tsx:vi.resetModules()移到vi.doMock之前 + 动态 import + 强制 anchor 存在XlsxViewer.test.tsx:新增“标记单元格”用例,断言<b>/<script>字面量留在文本节点、不进 DOMoffice-document-style-map.ts删除 mammoth 不支持的p:empty;DocxViewer显式ignoreEmptyParagraphs:falseXlsxViewer隐藏列的display:none移到style属性值里(之前<col hidden>被 CSS 解析器吞了)DocxViewer加stripJavaScriptHrefs后置 scrubber(见上)zh.json:ASCII 逗号 → 中文逗号验证
node config/scripts/check-changed-code-quality.mjs df7460af41:20 个改动文件,0 finding.docx/.xlsx/.pdf在 Electron dev 中实测打开、排版对齐、表格列宽生效Checklist
path.join/path.extname— 由 ppw-stack 维护