Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(file-preview): add docx section tabs and pptx slide controls (#19841)

Innei33c0679fa6e7
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 2ccf8996ce1..5990758a87f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2473,12 +2473,22 @@
"workingPanel.localFile.closeLeft": "Close to the Left",
"workingPanel.localFile.closeOther": "Close Others",
"workingPanel.localFile.closeRight": "Close to the Right",
+ "workingPanel.localFile.document.actualSize": "Actual size",
"workingPanel.localFile.document.download": "Download",
+ "workingPanel.localFile.document.fitWidth": "Fit width",
"workingPanel.localFile.document.openWithDefaultApp": "Open with default app",
+ "workingPanel.localFile.document.search": "Search slides",
+ "workingPanel.localFile.document.searchEmpty": "No matches",
+ "workingPanel.localFile.document.searchHits": "{{current}} of {{total}}",
+ "workingPanel.localFile.document.searchNext": "Next match",
+ "workingPanel.localFile.document.searchPlaceholder": "Search in this deck",
+ "workingPanel.localFile.document.slideNumber": "Slide {{number}}",
"workingPanel.localFile.document.truncatedRows": "Showing the first {{count}} rows",
"workingPanel.localFile.document.unsupported": "This document type can't be previewed in-app yet",
"workingPanel.localFile.document.xlsxOriginal": "Original layout",
"workingPanel.localFile.document.xlsxReflow": "Reflow",
+ "workingPanel.localFile.document.zoomIn": "Zoom in",
+ "workingPanel.localFile.document.zoomOut": "Zoom out",
"workingPanel.localFile.error": "Couldn't load this file",
"workingPanel.localFile.preview.openExternal": "Open in browser",
"workingPanel.localFile.preview.raw": "Raw",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 273142a51e6..83a0b76ebca 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2473,12 +2473,22 @@
"workingPanel.localFile.closeLeft": "关闭左侧",
"workingPanel.localFile.closeOther": "关闭其他",
"workingPanel.localFile.closeRight": "关闭右侧",
+ "workingPanel.localFile.document.actualSize": "实际大小",
"workingPanel.localFile.document.download": "下载",
+ "workingPanel.localFile.document.fitWidth": "适应宽度",
"workingPanel.localFile.document.openWithDefaultApp": "用默认应用打开",
+ "workingPanel.localFile.document.search": "搜索幻灯片",
+ "workingPanel.localFile.document.searchEmpty": "无匹配",
+ "workingPanel.localFile.document.searchHits": "第 {{current}} / {{total}} 处",
+ "workingPanel.localFile.document.searchNext": "下一处",
+ "workingPanel.localFile.document.searchPlaceholder": "在此演示文稿中搜索",
+ "workingPanel.localFile.document.slideNumber": "第 {{number}} 页",
"workingPanel.localFile.document.truncatedRows": "仅显示前 {{count}} 行",
"workingPanel.localFile.document.unsupported": "此文档类型暂不支持应用内预览",
"workingPanel.localFile.document.xlsxOriginal": "原始版式",
"workingPanel.localFile.document.xlsxReflow": "重排",
+ "workingPanel.localFile.document.zoomIn": "放大",
+ "workingPanel.localFile.document.zoomOut": "缩小",
"workingPanel.localFile.error": "无法加载此文件",
"workingPanel.localFile.preview.openExternal": "在浏览器中打开",
"workingPanel.localFile.preview.raw": "原文",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 73934762020..7fc74c24890 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2770,9 +2770,19 @@ export default {
'workingPanel.localFile.closeLeft': 'Close to the Left',
'workingPanel.localFile.closeOther': 'Close Others',
'workingPanel.localFile.closeRight': 'Close to the Right',
+ 'workingPanel.localFile.document.actualSize': 'Actual size',
'workingPanel.localFile.document.download': 'Download',
+ 'workingPanel.localFile.document.fitWidth': 'Fit width',
'workingPanel.localFile.document.openWithDefaultApp': 'Open with default app',
+ 'workingPanel.localFile.document.search': 'Search slides',
+ 'workingPanel.localFile.document.searchEmpty': 'No matches',
+ 'workingPanel.localFile.document.searchHits': '{{current}} of {{total}}',
+ 'workingPanel.localFile.document.searchNext': 'Next match',
+ 'workingPanel.localFile.document.searchPlaceholder': 'Search in this deck',
+ 'workingPanel.localFile.document.slideNumber': 'Slide {{number}}',
'workingPanel.localFile.document.truncatedRows': 'Showing the first {{count}} rows',
+ 'workingPanel.localFile.document.zoomIn': 'Zoom in',
+ 'workingPanel.localFile.document.zoomOut': 'Zoom out',
'workingPanel.localFile.document.xlsxOriginal': 'Original layout',
'workingPanel.localFile.document.xlsxReflow': 'Reflow',
'workingPanel.localFile.document.unsupported': "This document type can't be previewed in-app yet",
diff --git a/src/features/FileViewer/Renderer/Document/DocxPane.tsx b/src/features/FileViewer/Renderer/Document/DocxPane.tsx
new file mode 100644
index 00000000000..d49362b5f22
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/DocxPane.tsx
@@ -0,0 +1,137 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+
+import Loading from '@/components/Loading/CircleLoading';
+
+import { collectDocxSections, type DocxSection } from './docxSections';
+import PaneFooter from './PaneFooter';
+
+const styles = createStaticStyles(({ css }) => ({
+ scroll: css`
+ overflow: auto;
+ flex: 1;
+ background: ${cssVar.colorBgLayout};
+
+ /* docx-preview renders fixed-size "pages"; keep them centered with a gap.
+ "safe center" falls back to flex-start when the page is wider than the
+ pane, so the left edge stays reachable by horizontal scroll. */
+ .docx-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ align-items: safe center;
+
+ padding: 10px;
+
+ background: transparent;
+ }
+
+ .docx-wrapper > section.docx {
+ margin-block-end: 0;
+ border-radius: 4px;
+ box-shadow: ${cssVar.boxShadowTertiary};
+ }
+ `,
+ wrapper: css`
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
+
+interface DocxPaneProps {
+ blob: Blob;
+ onError: (error: unknown) => void;
+}
+
+const DocxPane = memo<DocxPaneProps>(({ blob, onError }) => {
+ const [loading, setLoading] = useState(true);
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+ const [sections, setSections] = useState<DocxSection[]>([]);
+ const [activeSection, setActiveSection] = useState(0);
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!container) return;
+
+ let disposed = false;
+
+ (async () => {
+ try {
+ const { renderAsync } = await import('docx-preview');
+ if (disposed) return;
+ await renderAsync(blob, container);
+ if (disposed) return;
+ setSections(collectDocxSections(container));
+ setActiveSection(0);
+ setLoading(false);
+ } catch (error) {
+ if (!disposed) onError(error);
+ }
+ })();
+
+ return () => {
+ disposed = true;
+ setSections([]);
+ // renderAsync has no dispose handle — it owns the container's children
+ // (including injected <style>), so clearing it is the documented cleanup.
+ container.replaceChildren();
+ };
+ }, [blob, container, onError]);
+
+ // The rendered pages are one long scroll, so the active tab follows the
+ // viewport instead of only the last click.
+ useEffect(() => {
+ const scroll = scrollRef.current;
+ if (!scroll || sections.length === 0) return;
+
+ const onScroll = () => {
+ const top = scroll.getBoundingClientRect().top;
+ let next = 0;
+ sections.forEach((section, index) => {
+ if (section.element.getBoundingClientRect().top - top <= 1) next = index;
+ });
+ setActiveSection(next);
+ };
+
+ scroll.addEventListener('scroll', onScroll, { passive: true });
+ return () => scroll.removeEventListener('scroll', onScroll);
+ }, [sections]);
+
+ const goToSection = useCallback(
+ (key: string) => {
+ const section = sections[Number(key)];
+ if (!section) return;
+ setActiveSection(Number(key));
+ section.element.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ },
+ [sections],
+ );
+
+ return (
+ <div className={styles.wrapper}>
+ <div className={styles.scroll} ref={scrollRef}>
+ {loading && <Loading />}
+ <div ref={setContainer} />
+ </div>
+ {sections.length > 0 && (
+ <PaneFooter
+ activeTab={String(activeSection)}
+ tabs={sections.map((section, index) => ({
+ key: String(index),
+ label: section.title,
+ title: section.title,
+ }))}
+ onTabChange={goToSection}
+ />
+ )}
+ </div>
+ );
+});
+
+DocxPane.displayName = 'DocxPane';
+
+export default DocxPane;
diff --git a/src/features/FileViewer/Renderer/Document/OfficeOnlinePane.tsx b/src/features/FileViewer/Renderer/Document/OfficeOnlinePane.tsx
new file mode 100644
index 00000000000..626d3d8e7a0
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/OfficeOnlinePane.tsx
@@ -0,0 +1,48 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ position: relative;
+ overflow: hidden;
+ border-radius: 4px;
+ `,
+ frame: css`
+ position: absolute;
+ inset-block: -1px;
+ inset-inline-start: -1px;
+
+ width: calc(100% + 2px);
+ height: calc(100% + 2px);
+ border: 0;
+ `,
+}));
+
+interface OfficeOnlinePaneProps {
+ /** Must be publicly fetchable — Microsoft's service downloads it server-side. */
+ url: string;
+}
+
+/**
+ * Last-resort preview for legacy binary office formats (.doc / .ppt / .xls /
+ * .odt), which no in-app renderer can parse. The file URL is handed to
+ * Microsoft's embed service, so this only runs for uploaded files that already
+ * carry a remote URL — never for a device's local file.
+ */
+const OfficeOnlinePane = memo<OfficeOnlinePaneProps>(({ url }) => (
+ <Flexbox className={styles.container} height={'100%'} id="msdoc-renderer" width={'100%'}>
+ <iframe
+ className={styles.frame}
+ id="msdoc-iframe"
+ src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(url)}`}
+ title="msdoc-iframe"
+ />
+ </Flexbox>
+));
+
+OfficeOnlinePane.displayName = 'OfficeOnlinePane';
+
+export default OfficeOnlinePane;
diff --git a/src/features/FileViewer/Renderer/Document/PaneFooter.tsx b/src/features/FileViewer/Renderer/Document/PaneFooter.tsx
new file mode 100644
index 00000000000..63bdc4fe25e
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/PaneFooter.tsx
@@ -0,0 +1,174 @@
+import { Tabs } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { type ReactNode, useEffect, useState } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ footer: css`
+ display: flex;
+ flex: none;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ modes: css`
+ flex: none;
+ width: auto;
+ `,
+ note: css`
+ flex: none;
+
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ tab: css`
+ cursor: pointer;
+
+ flex: none;
+
+ padding-block: 4px;
+ padding-inline: 12px;
+ border: none;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ background: transparent;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &[data-active='true'] {
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ tabs: css`
+ /* The strip scrolls rather than collapsing: a long section or slide list
+ stays one gesture away instead of hiding behind a dropdown. */
+ scrollbar-width: none;
+
+ overflow-x: auto;
+ display: flex;
+ flex: 1;
+ gap: 4px;
+ align-items: center;
+
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ `,
+ tabVisual: css`
+ cursor: pointer;
+
+ flex: none;
+
+ padding: 0;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 4px;
+
+ background: ${cssVar.colorBgContainer};
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ }
+
+ &[data-active='true'] {
+ border-color: ${cssVar.colorPrimary};
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};
+ }
+ `,
+}));
+
+export interface PaneTab {
+ key: string;
+ label: ReactNode;
+ title?: string;
+}
+
+interface PaneFooterProps {
+ activeMode?: string;
+ activeTab?: string;
+ /** Controls placed between the tab strip and the mode switch. */
+ extra?: ReactNode;
+ modes?: { key: string; label: string }[];
+ /** A status line above the footer — truncation, an auto-switch notice, search hits. */
+ note?: ReactNode;
+ onModeChange?: (key: string) => void;
+ onTabChange?: (key: string) => void;
+ tabs: PaneTab[];
+ /** Tabs whose label is a rendered preview instead of text (slide thumbnails). */
+ visualTabs?: boolean;
+}
+
+/**
+ * The footer every document pane shares: navigation on the start side (sheets,
+ * sections, slides), optional controls, and the view-mode switch at the end.
+ */
+const PaneFooter = ({
+ activeMode,
+ activeTab,
+ extra,
+ modes,
+ note,
+ onModeChange,
+ onTabChange,
+ tabs,
+ visualTabs,
+}: PaneFooterProps) => {
+ const [strip, setStrip] = useState<HTMLElement | null>(null);
+
+ // The strip scrolls instead of collapsing, so the active item can sit off
+ // screen after a jump or after the document scrolls the selection along.
+ useEffect(() => {
+ if (!strip || activeTab === undefined) return;
+ strip
+ .querySelector(`[data-key="${CSS.escape(activeTab)}"]`)
+ ?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ }, [activeTab, strip, tabs.length]);
+
+ return (
+ <>
+ {note ? <div className={styles.note}>{note}</div> : null}
+ <div className={styles.footer}>
+ <div className={styles.tabs} ref={setStrip}>
+ {tabs.map((tab) => (
+ <button
+ className={visualTabs ? styles.tabVisual : styles.tab}
+ data-active={tab.key === activeTab}
+ data-key={tab.key}
+ key={tab.key}
+ title={tab.title}
+ type={'button'}
+ onClick={() => onTabChange?.(tab.key)}
+ >
+ {tab.label}
+ </button>
+ ))}
+ </div>
+ {extra}
+ {modes && modes.length > 0 && (
+ <Tabs
+ activeKey={activeMode}
+ className={styles.modes}
+ items={modes.map((mode) => ({ key: mode.key, label: mode.label }))}
+ size={'small'}
+ onChange={(key) => onModeChange?.(key as string)}
+ />
+ )}
+ </div>
+ </>
+ );
+};
+
+export default PaneFooter;
diff --git a/src/features/FileViewer/Renderer/Document/PptxPane.tsx b/src/features/FileViewer/Renderer/Document/PptxPane.tsx
new file mode 100644
index 00000000000..8241abc2d22
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/PptxPane.tsx
@@ -0,0 +1,293 @@
+'use client';
+
+import type { PptxViewer, SlideHandle, TextSearchResult } from '@aiden0z/pptx-renderer';
+import { Input } from '@lobehub/ui';
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronRightIcon, MinusIcon, PlusIcon, SearchIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Loading from '@/components/Loading/CircleLoading';
+
+import PaneFooter from './PaneFooter';
+
+const THUMBNAIL_WIDTH = 74;
+const ZOOM_STEP = 10;
+const ZOOM_RANGE = [25, 400] as const;
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+ counter: css`
+ flex: none;
+
+ min-width: 42px;
+
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+ text-align: center;
+ `,
+ pager: css`
+ flex: none;
+
+ margin-inline-start: 4px;
+
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ scroll: css`
+ overflow: auto;
+ flex: 1;
+ background: ${cssVar.colorBgLayout};
+ `,
+ searchRow: css`
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ `,
+ thumb: css`
+ display: block;
+ width: ${THUMBNAIL_WIDTH}px;
+ background: #fff;
+ `,
+ zoom: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ `,
+}));
+
+const SlideThumbnail = memo<{ index: number; viewer: PptxViewer }>(({ index, viewer }) => {
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+
+ useEffect(() => {
+ if (!container) return;
+
+ let handle: SlideHandle | null = null;
+ try {
+ handle = viewer.renderThumbnailToContainer(index, container, { width: THUMBNAIL_WIDTH });
+ } catch {
+ // A slide that cannot be rendered small still has a numbered tab.
+ }
+ // renderThumbnailToContainer hands ownership of the handle to the caller;
+ // destroy() on the viewer does not reclaim externally-rendered slides.
+ return () => handle?.dispose();
+ }, [container, index, viewer]);
+
+ return <div className={styles.thumb} ref={setContainer} />;
+});
+
+SlideThumbnail.displayName = 'SlideThumbnail';
+
+interface PptxPaneProps {
+ blob: Blob;
+ onError: (error: unknown) => void;
+}
+
+const PptxPane = memo<PptxPaneProps>(({ blob, onError }) => {
+ const { t } = useTranslation('chat');
+ const [loading, setLoading] = useState(true);
+ const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+ const [viewer, setViewer] = useState<PptxViewer | null>(null);
+ const [slideCount, setSlideCount] = useState(0);
+ const [currentSlide, setCurrentSlide] = useState(0);
+ const [fitMode, setFitMode] = useState<'contain' | 'none'>('contain');
+ const [zoom, setZoom] = useState(100);
+ const [searching, setSearching] = useState(false);
+ const [query, setQuery] = useState('');
+ const [hits, setHits] = useState<TextSearchResult[]>([]);
+ const [hitIndex, setHitIndex] = useState(0);
+
+ useEffect(() => {
+ if (!container || !scrollEl) return;
+
+ const controller = new AbortController();
+ let instance: PptxViewer | undefined;
+
+ (async () => {
+ try {
+ const { PptxViewer: Viewer, RECOMMENDED_ZIP_LIMITS } =
+ await import('@aiden0z/pptx-renderer');
+ if (controller.signal.aborted) return;
+ instance = await Viewer.open(blob, container, {
+ listOptions: { windowed: true },
+ onSlideChange: setCurrentSlide,
+ scrollContainer: scrollEl,
+ signal: controller.signal,
+ // Local files are still untrusted input (agent/tool generated) — cap
+ // the ZIP expansion to keep a hostile pptx from exhausting memory.
+ zipLimits: RECOMMENDED_ZIP_LIMITS,
+ });
+ setViewer(instance);
+ setSlideCount(instance.slideCount);
+ setCurrentSlide(instance.currentSlideIndex);
+ setLoading(false);
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ onError(error);
+ }
+ })();
+
+ return () => {
+ controller.abort();
+ instance?.destroy();
+ setViewer(null);
+ };
+ }, [blob, container, scrollEl, onError]);
+
+ // Stepping from the current render's `zoom` loses a click when two arrive in
+ // one tick, so the step is a functional update and the viewer follows the
+ // settled value.
+ const stepZoom = useCallback(
+ (delta: number) =>
+ setZoom((previous) => Math.min(ZOOM_RANGE[1], Math.max(ZOOM_RANGE[0], previous + delta))),
+ [],
+ );
+
+ useEffect(() => {
+ void viewer?.setZoom(zoom);
+ }, [viewer, zoom]);
+
+ const goToHit = useCallback(
+ async (next: number, results: TextSearchResult[]) => {
+ const hit = results[next];
+ if (!viewer || !hit) return;
+ setHitIndex(next);
+ viewer.clearSearchHighlights();
+ await viewer.goToSlide(hit.slideIndex);
+ await viewer.highlightSearchResult(hit);
+ },
+ [viewer],
+ );
+
+ const runSearch = useCallback(
+ (value: string) => {
+ setQuery(value);
+ if (!viewer) return;
+ if (!value.trim()) {
+ viewer.clearSearchHighlights();
+ setHits([]);
+ setHitIndex(0);
+ return;
+ }
+ const results = viewer.searchText(value);
+ setHits(results);
+ void goToHit(0, results);
+ },
+ [goToHit, viewer],
+ );
+
+ const tabs = useMemo(
+ () =>
+ viewer
+ ? Array.from({ length: slideCount }, (_, index) => ({
+ key: String(index),
+ label: <SlideThumbnail index={index} viewer={viewer} />,
+ title: t('workingPanel.localFile.document.slideNumber', { number: index + 1 }),
+ }))
+ : [],
+ [slideCount, t, viewer],
+ );
+
+ const note = searching ? (
+ <div className={styles.searchRow}>
+ <Input
+ autoFocus
+ placeholder={t('workingPanel.localFile.document.searchPlaceholder')}
+ size={'small'}
+ value={query}
+ variant={'filled'}
+ onChange={(event) => runSearch(event.target.value)}
+ />
+ <span>
+ {query.trim() === ''
+ ? null
+ : hits.length === 0
+ ? t('workingPanel.localFile.document.searchEmpty')
+ : t('workingPanel.localFile.document.searchHits', {
+ current: hitIndex + 1,
+ total: hits.length,
+ })}
+ </span>
+ <ActionIcon
+ disabled={hits.length === 0}
+ icon={ChevronRightIcon}
+ size={'small'}
+ title={t('workingPanel.localFile.document.searchNext')}
+ onClick={() => void goToHit((hitIndex + 1) % hits.length, hits)}
+ />
+ </div>
+ ) : undefined;
+
+ return (
+ <div className={styles.container}>
+ <div className={styles.scroll} ref={setScrollEl}>
+ {loading && <Loading />}
+ {/* The viewer owns this node's children — React must never render into it,
+ or its bookkeeping breaks when the library replaces the content. */}
+ <div ref={setContainer} />
+ </div>
+ <PaneFooter
+ visualTabs
+ activeMode={fitMode}
+ activeTab={String(currentSlide)}
+ note={note}
+ tabs={tabs}
+ extra={
+ <>
+ <span className={styles.pager}>
+ {slideCount > 0 ? `${currentSlide + 1} / ${slideCount}` : ''}
+ </span>
+ <div className={styles.zoom}>
+ <ActionIcon
+ icon={MinusIcon}
+ size={'small'}
+ title={t('workingPanel.localFile.document.zoomOut')}
+ onClick={() => stepZoom(-ZOOM_STEP)}
+ />
+ <span className={styles.counter}>{zoom}%</span>
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={t('workingPanel.localFile.document.zoomIn')}
+ onClick={() => stepZoom(ZOOM_STEP)}
+ />
+ </div>
+ <ActionIcon
+ active={searching}
+ icon={SearchIcon}
+ size={'small'}
+ title={t('workingPanel.localFile.document.search')}
+ onClick={() => {
+ if (searching) runSearch('');
+ setSearching(!searching);
+ }}
+ />
+ </>
+ }
+ modes={[
+ { key: 'contain', label: t('workingPanel.localFile.document.fitWidth') },
+ { key: 'none', label: t('workingPanel.localFile.document.actualSize') },
+ ]}
+ onTabChange={(key) => void viewer?.goToSlide(Number(key))}
+ onModeChange={(key) => {
+ const next = key as 'contain' | 'none';
+ setFitMode(next);
+ void viewer?.setFitMode(next);
+ }}
+ />
+ </div>
+ );
+});
+
+PptxPane.displayName = 'PptxPane';
+
+export default PptxPane;
diff --git a/src/features/FileViewer/Renderer/Document/docxSections.test.ts b/src/features/FileViewer/Renderer/Document/docxSections.test.ts
new file mode 100644
index 00000000000..1b7438cf95f
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/docxSections.test.ts
@@ -0,0 +1,79 @@
+// @vitest-environment happy-dom
+import { describe, expect, it } from 'vitest';
+
+import { collectDocxSections } from './docxSections';
+
+const render = (html: string): HTMLElement => {
+ const root = document.createElement('div');
+ root.innerHTML = html;
+ document.body.append(root);
+ return root;
+};
+
+// Mirrors docx-preview's real output: the run's size and weight live on the
+// inner span while the paragraph keeps the body default.
+const para = (text: string, size: number, bold = false) =>
+ `<p style="font-size:14px;font-weight:400"><span style="font-size:${size}px;font-weight:${bold ? 700 : 400}">${text}</span></p>`;
+
+describe('collectDocxSections', () => {
+ it('uses semantic headings when the file has them', () => {
+ const root = render('<h1>Title</h1><h2>Goals</h2><h2>Risks</h2>');
+
+ expect(collectDocxSections(root).map((section) => section.title)).toEqual([
+ 'Title',
+ 'Goals',
+ 'Risks',
+ ]);
+ });
+
+ it('infers sections from size and weight when no heading style exists', () => {
+ const root = render(
+ [
+ para('东京七日精确时刻表', 24, true),
+ para('+ 全场景兜底锦囊', 16, true),
+ para('出发:5 月中下旬 (梅雨季前),人数 1-2 人,大本营 Hyatt Centric Ginza', 11),
+ para('Day 1 — 抵达 + 浅草夜游', 16, true),
+ para('14:00 浦东起飞,东方/全日空/日航直飞 NRT,全程约 3 小时', 10),
+ para('17:30 出关取行李,出站直走到京成 Skyliner 售票处取票', 10),
+ para('详细时刻表', 13, true),
+ para('Day 2 — 新海诚三部曲', 16, true),
+ para('09:00 从银座出发,丸之内线池袋方向,注意不要坐反', 10),
+ ].join(''),
+ );
+
+ // The masthead (title + subtitle) precedes the first body line and is not
+ // a section; the sub-label is a smaller tier than the day headings.
+ expect(collectDocxSections(root).map((section) => section.title)).toEqual([
+ 'Day 1 — 抵达 + 浅草夜游',
+ 'Day 2 — 新海诚三部曲',
+ ]);
+ });
+
+ it('ignores bold runs that sit at body size', () => {
+ const root = render(
+ [para('Title', 24, true), para('body text here', 11), para('inline emphasis', 11, true)].join(
+ '',
+ ),
+ );
+
+ expect(collectDocxSections(root)).toEqual([]);
+ });
+
+ it('keeps only the largest heading tier', () => {
+ const root = render(
+ [
+ para('body opener line', 11),
+ para('Day 1', 16, true),
+ para('详细时刻表', 13, true),
+ para('09:00 出发前往浅草,银座线浅草方面', 11),
+ para('Day 2', 16, true),
+ ].join(''),
+ );
+
+ expect(collectDocxSections(root).map((section) => section.title)).toEqual(['Day 1', 'Day 2']);
+ });
+
+ it('returns nothing for an empty render', () => {
+ expect(collectDocxSections(render(''))).toEqual([]);
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Document/docxSections.ts b/src/features/FileViewer/Renderer/Document/docxSections.ts
new file mode 100644
index 00000000000..31b8e2c7adb
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/docxSections.ts
@@ -0,0 +1,103 @@
+export interface DocxSection {
+ element: HTMLElement;
+ title: string;
+}
+
+const MAX_TITLE_LENGTH = 24;
+const MIN_HEADING_RATIO = 1.15;
+const MAX_SECTIONS = 40;
+const TIER_TOLERANCE = 0.5;
+
+// docx-preview carries a run's point size and weight on the inner <span>, not
+// on the <p>, which keeps the body default. Measuring the paragraph therefore
+// reports one uniform size for the whole document and finds no headings at all.
+// The run holding most of the paragraph's text is what a reader perceives as
+// that line's size.
+const dominantRun = (element: HTMLElement): HTMLElement => {
+ let best: HTMLElement | undefined;
+ let bestLength = 0;
+ for (const child of element.children) {
+ const length = (child.textContent ?? '').trim().length;
+ if (length > bestLength) {
+ best = child as HTMLElement;
+ bestLength = length;
+ }
+ }
+ return best ?? element;
+};
+
+const readFontSize = (element: HTMLElement): number =>
+ Number.parseFloat(globalThis.getComputedStyle(dominantRun(element)).fontSize) || 0;
+
+const isBold = (element: HTMLElement): boolean => {
+ const weight = globalThis.getComputedStyle(dominantRun(element)).fontWeight;
+ return weight === 'bold' || Number(weight) >= 600;
+};
+
+const trimTitle = (text: string): string => {
+ const clean = text.replaceAll(/\s+/gu, ' ').trim();
+ return clean.length > MAX_TITLE_LENGTH ? `${clean.slice(0, MAX_TITLE_LENGTH)}…` : clean;
+};
+
+/**
+ * Derive a section list from a rendered docx.
+ *
+ * Real-world docx files routinely carry no heading styles at all — a 100-block
+ * itinerary where every paragraph is `Normal` and the hierarchy lives only in
+ * point size. So semantic headings are used when the file has them, and
+ * otherwise sections are inferred the way `classifySheet` infers a sheet's
+ * shape: the body's dominant font size is the baseline, and bold runs clearly
+ * above it are section starts. The first such block is skipped — that is the
+ * document title, not a section.
+ */
+export const collectDocxSections = (root: HTMLElement): DocxSection[] => {
+ const semantic = [...root.querySelectorAll<HTMLElement>('h1, h2, h3')];
+ if (semantic.length > 1) {
+ return semantic
+ .slice(0, MAX_SECTIONS)
+ .map((element) => ({ element, title: trimTitle(element.textContent ?? '') }))
+ .filter((section) => section.title.length > 0);
+ }
+
+ const blocks = [...root.querySelectorAll<HTMLElement>('p')].filter(
+ (element) => (element.textContent ?? '').trim().length > 0,
+ );
+ if (blocks.length === 0) return [];
+
+ // Weighted by characters, not by block count: a document whose body is a few
+ // long paragraphs and whose headings are many short lines would otherwise
+ // elect the heading size as the baseline and find no sections at all. Ties
+ // resolve to the smaller size, which is the body by construction.
+ const weights = new Map<number, number>();
+ for (const block of blocks) {
+ const size = Math.round(readFontSize(block));
+ const length = (block.textContent ?? '').trim().length;
+ weights.set(size, (weights.get(size) ?? 0) + length);
+ }
+ const baseline = [...weights.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0];
+
+ // The masthead — title and subtitle — is set at heading size but is not a
+ // section. It is whatever precedes the document's first body-size text, and
+ // it must go before the tier is chosen, or a 24pt title elects itself the
+ // only section and the 16pt day headings are all dropped.
+ const firstBodyIndex = blocks.findIndex(
+ (block) => readFontSize(block) < baseline * MIN_HEADING_RATIO,
+ );
+ const body = firstBodyIndex >= 0 ? blocks.slice(firstBodyIndex) : blocks;
+
+ const candidates = body.filter(
+ (block) => isBold(block) && readFontSize(block) >= baseline * MIN_HEADING_RATIO,
+ );
+ if (candidates.length === 0) return [];
+
+ // Only the largest remaining tier is a section. A file with day headings and
+ // two levels of bold sub-labels otherwise produces one flat strip mixing all
+ // of them, which reads as noise rather than as navigation.
+ const topSize = Math.max(...candidates.map((block) => readFontSize(block)));
+
+ return candidates
+ .filter((block) => readFontSize(block) >= topSize - TIER_TOLERANCE)
+ .slice(0, MAX_SECTIONS)
+ .map((element) => ({ element, title: trimTitle(element.textContent ?? '') }))
+ .filter((section) => section.title.length > 0);
+};
diff --git a/src/features/Portal/LocalFile/DocumentPreview.tsx b/src/features/FileViewer/Renderer/Document/index.tsx
similarity index 59%
rename from src/features/Portal/LocalFile/DocumentPreview.tsx
rename to src/features/FileViewer/Renderer/Document/index.tsx
index e6d191c6b50..46abf3e852a 100644
--- a/src/features/Portal/LocalFile/DocumentPreview.tsx
+++ b/src/features/FileViewer/Renderer/Document/index.tsx
@@ -14,6 +14,9 @@ import Loading from '@/components/Loading/CircleLoading';
import { Document, Page, pdfjs } from '@/libs/pdfjs';
import { localFileService } from '@/services/electron/localFileService';
+import DocxPane from './DocxPane';
+import OfficeOnlinePane from './OfficeOnlinePane';
+import PptxPane from './PptxPane';
import XlsxPane from './xlsx/XlsxPane';
// Same CDN assets as the FileViewer PDF renderer — cmaps / fonts are required
@@ -26,42 +29,12 @@ const pdfOptions = {
const maxPageWidth = 1200;
const styles = createStaticStyles(({ css }) => ({
- docxContainer: css`
- overflow: auto;
- height: 100%;
- background: ${cssVar.colorBgLayout};
-
- /* docx-preview renders fixed-size "pages"; keep them centered with a gap.
- "safe center" falls back to flex-start when the page is wider than the
- pane, so the left edge stays reachable by horizontal scroll. */
- .docx-wrapper {
- display: flex;
- flex-direction: column;
- gap: 12px;
- align-items: safe center;
-
- padding: 10px;
-
- background: transparent;
- }
-
- .docx-wrapper > section.docx {
- margin-block-end: 0;
- border-radius: 4px;
- box-shadow: ${cssVar.boxShadowTertiary};
- }
- `,
fallbackIcon: css`
width: 64px;
height: 64px;
border-radius: 14px;
background: ${cssVar.colorFillTertiary};
`,
- officeContainer: css`
- overflow: auto;
- height: 100%;
- background: ${cssVar.colorBgLayout};
- `,
page: css`
overflow: hidden;
margin-block-end: 12px;
@@ -121,103 +94,11 @@ const PdfPane = memo<{ blob: Blob }>(({ blob }) => {
PdfPane.displayName = 'PdfPane';
-interface OfficePaneProps {
- blob: Blob;
- /** Renderer failed — parent swaps in the download / open-externally state. */
- onError: (error: unknown) => void;
-}
-
-const PptxPane = memo<OfficePaneProps>(({ blob, onError }) => {
- const [loading, setLoading] = useState(true);
- const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
- const [container, setContainer] = useState<HTMLElement | null>(null);
-
- useEffect(() => {
- if (!container || !scrollEl) return;
-
- const controller = new AbortController();
- let viewer: { destroy: () => void } | undefined;
-
- (async () => {
- try {
- const { PptxViewer, RECOMMENDED_ZIP_LIMITS } = await import('@aiden0z/pptx-renderer');
- if (controller.signal.aborted) return;
- viewer = await PptxViewer.open(blob, container, {
- listOptions: { windowed: true },
- scrollContainer: scrollEl,
- signal: controller.signal,
- // Local files are still untrusted input (agent/tool generated) — cap
- // the ZIP expansion to keep a hostile pptx from exhausting memory.
- zipLimits: RECOMMENDED_ZIP_LIMITS,
- });
- setLoading(false);
- } catch (error) {
- if (controller.signal.aborted) return;
- onError(error);
- }
- })();
-
- return () => {
- controller.abort();
- viewer?.destroy();
- };
- }, [blob, container, scrollEl, onError]);
-
- return (
- <div className={styles.officeContainer} ref={setScrollEl}>
- {loading && <Loading />}
- {/* The viewer owns this node's children — React must never render into it,
- or its bookkeeping breaks when the library replaces the content. */}
- <div ref={setContainer} />
- </div>
- );
-});
-
-PptxPane.displayName = 'PptxPane';
-
-const DocxPane = memo<OfficePaneProps>(({ blob, onError }) => {
- const [loading, setLoading] = useState(true);
- const [container, setContainer] = useState<HTMLElement | null>(null);
-
- useEffect(() => {
- if (!container) return;
-
- let disposed = false;
-
- (async () => {
- try {
- const { renderAsync } = await import('docx-preview');
- if (disposed) return;
- await renderAsync(blob, container);
- if (!disposed) setLoading(false);
- } catch (error) {
- if (!disposed) onError(error);
- }
- })();
-
- return () => {
- disposed = true;
- // renderAsync has no dispose handle — it owns the container's children
- // (including injected <style>), so clearing it is the documented cleanup.
- container.replaceChildren();
- };
- }, [blob, container, onError]);
-
- return (
- <div className={styles.docxContainer}>
- {loading && <Loading />}
- <div ref={setContainer} />
- </div>
- );
-});
-
-DocxPane.displayName = 'DocxPane';
-
/**
* Modern OOXML formats with an in-app renderer. Legacy binary formats (.doc /
* .ppt / .xls) have none and keep the download / open-externally fallback.
*/
-const OFFICE_PANES: Record<string, typeof PptxPane> = {
+const OFFICE_PANES: Record<string, typeof DocxPane> = {
'application/vnd.openxmlformats-officedocument.presentationml.presentation': PptxPane,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': XlsxPane,
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': DocxPane,
@@ -229,18 +110,22 @@ export interface DocumentPreviewProps {
filePath: string;
/** File lives on this desktop's filesystem — offer "open with default app". */
isLocalFile: boolean;
+ /** Publicly fetchable URL, if the file has one — enables the online fallback. */
+ sourceUrl?: string | null;
}
/**
- * In-portal preview for binary documents transported as blobs. PDFs render
+ * Preview for binary documents transported as blobs — local workspace files in
+ * the portal, and uploaded files fetched from their URL by the file viewer. PDFs render
* inline via react-pdf (the Electron iframe PDF plugin is disabled, so a blob
* URL in an iframe would not render on desktop); pptx / docx / xlsx render
* inline via dynamically-imported client renderers, falling back to a
* download / open-externally state when parsing fails. Legacy binary office
- * formats (.doc / .ppt / .xls) have no local renderer and always degrade.
+ * formats (.doc / .ppt / .xls / .odt) have no renderer; with a remote
+ * `sourceUrl` they degrade to the online viewer, otherwise to download.
*/
const DocumentPreview = memo<DocumentPreviewProps>(
- ({ blob, contentType, filePath, isLocalFile }) => {
+ ({ blob, contentType, filePath, isLocalFile, sourceUrl }) => {
const { t } = useTranslation('chat');
const filename = filePath.split('/').at(-1) ?? '';
const [renderError, setRenderError] = useState(false);
@@ -272,6 +157,8 @@ const DocumentPreview = memo<DocumentPreviewProps>(
return <OfficePane blob={blob} onError={handleRenderError} />;
}
+ if (sourceUrl) return <OfficeOnlinePane url={sourceUrl} />;
+
return (
<Center gap={16} height={'100%'} width={'100%'}>
<Center className={styles.fallbackIcon}>
diff --git a/src/features/Portal/LocalFile/xlsx/SheetDocument.test.tsx b/src/features/FileViewer/Renderer/Document/xlsx/SheetDocument.test.tsx
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/SheetDocument.test.tsx
rename to src/features/FileViewer/Renderer/Document/xlsx/SheetDocument.test.tsx
diff --git a/src/features/Portal/LocalFile/xlsx/SheetDocument.tsx b/src/features/FileViewer/Renderer/Document/xlsx/SheetDocument.tsx
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/SheetDocument.tsx
rename to src/features/FileViewer/Renderer/Document/xlsx/SheetDocument.tsx
diff --git a/src/features/Portal/LocalFile/xlsx/SheetGrid.test.tsx b/src/features/FileViewer/Renderer/Document/xlsx/SheetGrid.test.tsx
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/SheetGrid.test.tsx
rename to src/features/FileViewer/Renderer/Document/xlsx/SheetGrid.test.tsx
diff --git a/src/features/Portal/LocalFile/xlsx/SheetGrid.tsx b/src/features/FileViewer/Renderer/Document/xlsx/SheetGrid.tsx
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/SheetGrid.tsx
rename to src/features/FileViewer/Renderer/Document/xlsx/SheetGrid.tsx
diff --git a/src/features/FileViewer/Renderer/Document/xlsx/XlsxPane.tsx b/src/features/FileViewer/Renderer/Document/xlsx/XlsxPane.tsx
new file mode 100644
index 00000000000..1a993284ea9
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Document/xlsx/XlsxPane.tsx
@@ -0,0 +1,88 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Loading from '@/components/Loading/CircleLoading';
+
+import PaneFooter from '../PaneFooter';
+import { classifySheet } from './classifySheet';
+import { MAX_PREVIEW_ROWS, readWorkbook, type SheetModel } from './model';
+import SheetDocument from './SheetDocument';
+import SheetGrid from './SheetGrid';
+
+const styles = createStaticStyles(({ css }) => ({
+ container: css`
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
+
+interface XlsxPaneProps {
+ blob: Blob;
+ onError: (error: unknown) => void;
+}
+
+const XlsxPane = memo<XlsxPaneProps>(({ blob, onError }) => {
+ const { t } = useTranslation('chat');
+ const [sheets, setSheets] = useState<SheetModel[]>();
+ const [activeSheet, setActiveSheet] = useState(0);
+ const [mode, setMode] = useState<'auto' | 'fidelity' | 'reflow'>('auto');
+
+ useEffect(() => {
+ let disposed = false;
+
+ readWorkbook(blob)
+ .then((parsed) => {
+ if (disposed) return;
+ setSheets(parsed);
+ setActiveSheet(0);
+ setMode('auto');
+ })
+ .catch((error) => {
+ if (!disposed) onError(error);
+ });
+
+ return () => {
+ disposed = true;
+ };
+ }, [blob, onError]);
+
+ const sheet = sheets?.[activeSheet] ?? sheets?.[0];
+ const outline = useMemo(() => (sheet ? classifySheet(sheet) : undefined), [sheet]);
+
+ if (!sheet || !outline) return <Loading />;
+
+ const resolvedMode = mode === 'auto' ? outline.mode : mode;
+
+ return (
+ <div className={styles.container}>
+ {resolvedMode === 'reflow' ? (
+ <SheetDocument outline={outline} />
+ ) : (
+ <SheetGrid sheet={sheet} />
+ )}
+ <PaneFooter
+ activeMode={resolvedMode}
+ activeTab={String(activeSheet)}
+ tabs={sheets!.map((item, index) => ({ key: String(index), label: item.name }))}
+ modes={[
+ { key: 'reflow', label: t('workingPanel.localFile.document.xlsxReflow') },
+ { key: 'fidelity', label: t('workingPanel.localFile.document.xlsxOriginal') },
+ ]}
+ note={
+ sheet.truncated
+ ? t('workingPanel.localFile.document.truncatedRows', { count: MAX_PREVIEW_ROWS })
+ : undefined
+ }
+ onModeChange={(key) => setMode(key as 'fidelity' | 'reflow')}
+ onTabChange={(key) => setActiveSheet(Number(key))}
+ />
+ </div>
+ );
+});
+
+XlsxPane.displayName = 'XlsxPane';
+
+export default XlsxPane;
diff --git a/src/features/Portal/LocalFile/xlsx/classifySheet.test.ts b/src/features/FileViewer/Renderer/Document/xlsx/classifySheet.test.ts
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/classifySheet.test.ts
rename to src/features/FileViewer/Renderer/Document/xlsx/classifySheet.test.ts
diff --git a/src/features/Portal/LocalFile/xlsx/classifySheet.ts b/src/features/FileViewer/Renderer/Document/xlsx/classifySheet.ts
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/classifySheet.ts
rename to src/features/FileViewer/Renderer/Document/xlsx/classifySheet.ts
diff --git a/src/features/Portal/LocalFile/xlsx/model.test.ts b/src/features/FileViewer/Renderer/Document/xlsx/model.test.ts
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/model.test.ts
rename to src/features/FileViewer/Renderer/Document/xlsx/model.test.ts
diff --git a/src/features/Portal/LocalFile/xlsx/model.ts b/src/features/FileViewer/Renderer/Document/xlsx/model.ts
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/model.ts
rename to src/features/FileViewer/Renderer/Document/xlsx/model.ts
diff --git a/src/features/Portal/LocalFile/xlsx/styles.ts b/src/features/FileViewer/Renderer/Document/xlsx/styles.ts
similarity index 100%
rename from src/features/Portal/LocalFile/xlsx/styles.ts
rename to src/features/FileViewer/Renderer/Document/xlsx/styles.ts
diff --git a/src/features/FileViewer/Renderer/MSDoc/index.tsx b/src/features/FileViewer/Renderer/MSDoc/index.tsx
index 90108521e16..121cbbd8a15 100644
--- a/src/features/FileViewer/Renderer/MSDoc/index.tsx
+++ b/src/features/FileViewer/Renderer/MSDoc/index.tsx
@@ -1,43 +1,92 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { css, cx } from 'antd-style';
-import { memo } from 'react';
-
-const container = css`
- position: relative;
- overflow: hidden;
- border-radius: 4px;
-`;
-
-const content = css`
- position: absolute;
- inset-block: -1px;
- inset-inline-start: -1px;
-
- width: calc(100% + 2px);
- height: calc(100% + 2px);
- border: 0;
-`;
+import { Center, Flexbox } from '@lobehub/ui';
+import { lazy, memo, Suspense } from 'react';
+
+import AsyncError from '@/components/AsyncError';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+
+import { useBlobFileLoader } from '../../hooks/useBlobFileLoader';
+import NotSupport from '../../NotSupport';
+import OfficeOnlinePane from '../Document/OfficeOnlinePane';
+
+// Deferred: pulls in react-pdf and the office renderers.
+const DocumentPreview = lazy(() => import('../Document'));
+
+const OFFICE_MIME_TYPES: Record<string, string> = {
+ doc: 'application/msword',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ odt: 'application/vnd.oasis.opendocument.text',
+ ppt: 'application/vnd.ms-powerpoint',
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ xls: 'application/vnd.ms-excel',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+};
+
+const OFFICE_MIME_VALUES = new Set(Object.values(OFFICE_MIME_TYPES));
+
+// `fileType` is either a bare extension or a full MIME depending on how the file
+// was uploaded; the renderer map keys on MIME, so normalize both to a MIME.
+export const resolveContentType = (fileType?: string, fileName?: string): string => {
+ const lowerFileType = fileType?.toLowerCase();
+ if (lowerFileType) {
+ if (OFFICE_MIME_VALUES.has(lowerFileType)) return lowerFileType;
+ if (OFFICE_MIME_TYPES[lowerFileType]) return OFFICE_MIME_TYPES[lowerFileType];
+ }
+
+ const extension = fileName?.toLowerCase().split('.').at(-1);
+ return (extension && OFFICE_MIME_TYPES[extension]) || 'application/octet-stream';
+};
interface MSDocViewerProps {
fileId: string;
+ fileName?: string;
+ fileType?: string;
url: string | null;
}
-const MSDocViewer = memo<MSDocViewerProps>(({ url }) => {
- if (!url) return null;
+const MSDocViewer = memo<MSDocViewerProps>(({ fileName, fileType, url }) => {
+ const { blob, error, loading, tooLarge } = useBlobFileLoader(url);
+
+ if (loading)
+ return (
+ <Center height={'100%'} width={'100%'}>
+ <NeuralNetworkLoading size={36} />
+ </Center>
+ );
+
+ // Oversized or unreachable for an in-app render, but the online viewer only
+ // needs the URL — it downloads the file server-side.
+ if (!blob) {
+ if (url) return <OfficeOnlinePane url={url} />;
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ {error && <AsyncError error={error} variant={'block'} />}
+ <NotSupport fileName={fileName} tooLarge={tooLarge} url={url} />
+ </Flexbox>
+ );
+ }
return (
- <Flexbox className={cx(container)} height={'100%'} id="msdoc-renderer" width={'100%'}>
- <iframe
- className={cx(content)}
- id="msdoc-iframe"
- src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(url)}`}
- title="msdoc-iframe"
+ <Suspense
+ fallback={
+ <Center height={'100%'} width={'100%'}>
+ <NeuralNetworkLoading size={36} />
+ </Center>
+ }
+ >
+ <DocumentPreview
+ blob={blob}
+ contentType={resolveContentType(fileType, fileName)}
+ filePath={fileName ?? ''}
+ isLocalFile={false}
+ sourceUrl={url}
/>
- </Flexbox>
+ </Suspense>
);
});
+MSDocViewer.displayName = 'MSDocViewer';
+
export default MSDocViewer;
diff --git a/src/features/FileViewer/Renderer/MSDoc/resolveContentType.test.ts b/src/features/FileViewer/Renderer/MSDoc/resolveContentType.test.ts
new file mode 100644
index 00000000000..7c814d0c874
--- /dev/null
+++ b/src/features/FileViewer/Renderer/MSDoc/resolveContentType.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveContentType } from './index';
+
+describe('resolveContentType', () => {
+ it('keeps a full office mime as-is', () => {
+ expect(
+ resolveContentType(
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'a.docx',
+ ),
+ ).toBe('application/vnd.openxmlformats-officedocument.wordprocessingml.document');
+ });
+
+ it('maps a bare extension fileType to its mime', () => {
+ expect(resolveContentType('XLSX', 'report.bin')).toBe(
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ );
+ });
+
+ it('falls back to the filename extension when fileType is unusable', () => {
+ expect(resolveContentType('application/octet-stream', 'Deck.PPTX')).toBe(
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ );
+ });
+
+ it('returns a generic binary mime when nothing matches', () => {
+ expect(resolveContentType(undefined, 'notes')).toBe('application/octet-stream');
+ });
+});
diff --git a/src/features/FileViewer/hooks/useBlobFileLoader.ts b/src/features/FileViewer/hooks/useBlobFileLoader.ts
new file mode 100644
index 00000000000..bab3cec3f55
--- /dev/null
+++ b/src/features/FileViewer/hooks/useBlobFileLoader.ts
@@ -0,0 +1,69 @@
+import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
+import { useEffect, useState } from 'react';
+
+/** Mirrors the device-side document preview ceiling in `@lobechat/device-control`. */
+const MAX_BINARY_PREVIEW_BYTES = 20 * 1024 * 1024;
+
+interface BlobFileState {
+ blob: Blob | null;
+ error: Error | null;
+ loading: boolean;
+ tooLarge?: boolean;
+ url: string | null;
+}
+
+/**
+ * Download original file bytes for a bounded, read-only binary preview.
+ *
+ * Use when:
+ * - Rendering an office document with an in-app renderer that takes a blob.
+ *
+ * Expects:
+ * - An accessible file URL; null disables the request.
+ *
+ * Returns:
+ * - A blob, loading/error state, or `tooLarge` for oversized files.
+ */
+export const useBlobFileLoader = (url: string | null): BlobFileState => {
+ const [state, setState] = useState<BlobFileState>({
+ blob: null,
+ error: null,
+ loading: !!url,
+ url,
+ });
+
+ useEffect(() => {
+ const controller = new AbortController();
+ setState({ blob: null, error: null, loading: !!url, url });
+ if (!url) return;
+
+ const loadFile = async () => {
+ try {
+ const response = await fetch(url, { signal: controller.signal });
+ if (!response.ok) throw new Error(`Failed to load file: ${response.status}`);
+ const blob = await readBlobWithLimit(response, MAX_BINARY_PREVIEW_BYTES);
+ if (!controller.signal.aborted) setState({ blob, error: null, loading: false, url });
+ } catch (cause) {
+ if (controller.signal.aborted) return;
+ setState({
+ blob: null,
+ error:
+ cause instanceof RangeError
+ ? null
+ : cause instanceof Error
+ ? cause
+ : new Error('Failed to load file'),
+ loading: false,
+ tooLarge: cause instanceof RangeError,
+ url,
+ });
+ }
+ };
+
+ void loadFile();
+ return () => controller.abort();
+ }, [url]);
+
+ // Never hand back a previous file's blob while the new URL's effect is starting.
+ return state.url === url ? state : { blob: null, error: null, loading: !!url, url };
+};
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index 044a633b793..4fd252a91c8 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -187,7 +187,7 @@ const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) =>
// Microsoft Office documents - check before code files to avoid false matches
// (e.g., 'doc' contains 'c' which would match CODE_EXTENSIONS)
if (matchesFileType(fileType, name, MSDOC_EXTENSIONS, MSDOC_MIME_TYPES)) {
- return <MSDocViewer fileId={id} url={url} />;
+ return <MSDocViewer fileId={id} fileName={name} fileType={fileType} url={url} />;
}
// HTML files should render as a sandboxed preview before the broader code-file fallback.
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index e8b33388548..87b9437dad0 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -34,7 +34,7 @@ import MarkdownImage from './MarkdownImage';
import PreviewToolbar, { ToolbarActionButton } from './PreviewToolbar';
// Deferred: pulls in react-pdf, only needed once a binary document is opened.
-const DocumentPreview = lazy(() => import('./DocumentPreview'));
+const DocumentPreview = lazy(() => import('@/features/FileViewer/Renderer/Document'));
interface ImagePreviewProps {
blob: Blob;
diff --git a/src/features/Portal/LocalFile/xlsx/XlsxPane.tsx b/src/features/Portal/LocalFile/xlsx/XlsxPane.tsx
deleted file mode 100644
index 8e253b2f2f5..00000000000
--- a/src/features/Portal/LocalFile/xlsx/XlsxPane.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { Tabs } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { memo, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import Loading from '@/components/Loading/CircleLoading';
-
-import { classifySheet } from './classifySheet';
-import { MAX_PREVIEW_ROWS, readWorkbook, type SheetModel } from './model';
-import SheetDocument from './SheetDocument';
-import SheetGrid from './SheetGrid';
-
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- display: flex;
- flex-direction: column;
- height: 100%;
- background: ${cssVar.colorBgContainer};
- `,
- footer: css`
- display: flex;
- flex: none;
- gap: 8px;
- align-items: center;
- justify-content: flex-end;
-
- padding-block: 6px;
- padding-inline: 8px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- modes: css`
- flex: none;
- width: auto;
- `,
- tab: css`
- cursor: pointer;
-
- padding-block: 4px;
- padding-inline: 12px;
- border: none;
- border-radius: 6px;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- white-space: nowrap;
-
- background: transparent;
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
- }
-
- &[data-active='true'] {
- font-weight: 500;
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- }
- `,
- tabs: css`
- overflow-x: auto;
- display: flex;
- gap: 4px;
- margin-inline-end: auto;
- `,
- truncatedNote: css`
- flex: none;
-
- padding-block: 6px;
- padding-inline: 12px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
-
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
-
-interface XlsxPaneProps {
- blob: Blob;
- onError: (error: unknown) => void;
-}
-
-const XlsxPane = memo<XlsxPaneProps>(({ blob, onError }) => {
- const { t } = useTranslation('chat');
- const [sheets, setSheets] = useState<SheetModel[]>();
- const [activeSheet, setActiveSheet] = useState(0);
- const [mode, setMode] = useState<'auto' | 'fidelity' | 'reflow'>('auto');
-
- useEffect(() => {
- let disposed = false;
-
- readWorkbook(blob)
- .then((parsed) => {
- if (disposed) return;
- setSheets(parsed);
- setActiveSheet(0);
- setMode('auto');
- })
- .catch((error) => {
- if (!disposed) onError(error);
- });
-
- return () => {
- disposed = true;
- };
- }, [blob, onError]);
-
- const sheet = sheets?.[activeSheet] ?? sheets?.[0];
- const outline = useMemo(() => (sheet ? classifySheet(sheet) : undefined), [sheet]);
-
- if (!sheet || !outline) return <Loading />;
-
- const resolvedMode = mode === 'auto' ? outline.mode : mode;
-
- return (
- <div className={styles.container}>
- {resolvedMode === 'reflow' ? (
- <SheetDocument outline={outline} />
- ) : (
- <SheetGrid sheet={sheet} />
- )}
- {sheet.truncated && (
- <div className={styles.truncatedNote}>
- {t('workingPanel.localFile.document.truncatedRows', { count: MAX_PREVIEW_ROWS })}
- </div>
- )}
- <div className={styles.footer}>
- <div className={styles.tabs}>
- {sheets!.map((item, index) => (
- <button
- className={styles.tab}
- data-active={index === activeSheet}
- key={`${index}-${item.name}`}
- type={'button'}
- onClick={() => setActiveSheet(index)}
- >
- {item.name}
- </button>
- ))}
- </div>
- <Tabs
- activeKey={resolvedMode}
- className={styles.modes}
- size={'small'}
- items={[
- {
- key: 'reflow',
- label: t('workingPanel.localFile.document.xlsxReflow'),
- },
- {
- key: 'fidelity',
- label: t('workingPanel.localFile.document.xlsxOriginal'),
- },
- ]}
- onChange={(key) => setMode(key as 'fidelity' | 'reflow')}
- />
- </div>
- </div>
- );
-});
-
-XlsxPane.displayName = 'XlsxPane';
-
-export default XlsxPane;