🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(portal): render local xlsx previews with layout fidelity and a reflow view (#19265)
Inneifdbabf5d9031
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex dd0a71bac58..56f45a8fa0e 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2380,6 +2380,8 @@"workingPanel.localFile.document.openWithDefaultApp": "Open with default app","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.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.jsonindex 6b02677ee3a..9c4de4e9a7c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2380,6 +2380,8 @@"workingPanel.localFile.document.openWithDefaultApp": "用默认应用打开","workingPanel.localFile.document.truncatedRows": "仅显示前 {{count}} 行","workingPanel.localFile.document.unsupported": "此文档类型暂不支持应用内预览",+ "workingPanel.localFile.document.xlsxOriginal": "原始版式",+ "workingPanel.localFile.document.xlsxReflow": "重排","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.tsindex 0ba9f0df1b5..b13bbdfede1 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2649,6 +2649,8 @@ export default {'workingPanel.localFile.document.download': 'Download','workingPanel.localFile.document.openWithDefaultApp': 'Open with default app','workingPanel.localFile.document.truncatedRows': 'Showing the first {{count}} rows',+ '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",'workingPanel.localFile.error': "Couldn't load this file",'workingPanel.localFile.preview.raw': 'Raw',diff --git a/src/features/Portal/LocalFile/DocumentPreview.tsx b/src/features/Portal/LocalFile/DocumentPreview.tsxindex 5ccfab171a4..e6d191c6b50 100644--- a/src/features/Portal/LocalFile/DocumentPreview.tsx+++ b/src/features/Portal/LocalFile/DocumentPreview.tsx@@ -14,6 +14,8 @@ import Loading from '@/components/Loading/CircleLoading';import { Document, Page, pdfjs } from '@/libs/pdfjs';import { localFileService } from '@/services/electron/localFileService';+import XlsxPane from './xlsx/XlsxPane';+// Same CDN assets as the FileViewer PDF renderer — cmaps / fonts are required// for non-latin PDFs.const pdfOptions = {@@ -66,73 +68,6 @@ const styles = createStaticStyles(({ css }) => ({border-radius: 4px;box-shadow: ${cssVar.boxShadowTertiary};`,- sheetTab: 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};- }- `,- sheetTabs: css`- overflow-x: auto;- display: flex;- flex: none;- gap: 4px;-- padding-block: 6px;- padding-inline: 8px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,- truncatedNote: css`- padding-block: 8px;- padding-inline: 12px;- font-size: 12px;- color: ${cssVar.colorTextTertiary};- `,- xlsxContainer: css`- display: flex;- flex-direction: column;- height: 100%;- background: ${cssVar.colorBgContainer};- `,- xlsxTable: css`- overflow: auto;- flex: 1;-- table {- border-collapse: collapse;- font-size: 12px;- }-- td {- overflow: hidden;-- max-width: 320px;- padding-block: 4px;- padding-inline: 8px;- border: 1px solid ${cssVar.colorBorderSecondary};-- text-overflow: ellipsis;- white-space: nowrap;- }- `,pdfContainer: css`overflow: auto;display: flex;@@ -278,126 +213,6 @@ const DocxPane = memo<OfficePaneProps>(({ blob, onError }) => {DocxPane.displayName = 'DocxPane';-/**- * DOM tables choke on huge sheets; a preview only needs the head of the data.- * Users open the real file (default app / download) for the full sheet.- */-const MAX_PREVIEW_ROWS = 500;--interface SheetGrid {- name: string;- rows: string[][];- truncated: boolean;-}--/** Flatten an exceljs cell value (rich text / formula / hyperlink / date …) to display text. */-const formatCellValue = (value: unknown): string => {- if (value === null || value === undefined) return '';- if (value instanceof Date) return value.toISOString().slice(0, 10);- if (typeof value === 'object') {- const cell = value as {- error?: string;- formula?: string;- hyperlink?: string;- result?: unknown;- richText?: { text: string }[];- text?: unknown;- };- if (cell.richText) return cell.richText.map((run) => run.text).join('');- if (cell.formula !== undefined) return formatCellValue(cell.result);- if (cell.text !== undefined) return formatCellValue(cell.text);- if (cell.error) return cell.error;- return '';- }- return String(value);-};--const XlsxPane = memo<OfficePaneProps>(({ blob, onError }) => {- const { t } = useTranslation('chat');- const [sheets, setSheets] = useState<SheetGrid[]>();- const [activeSheet, setActiveSheet] = useState(0);-- useEffect(() => {- let disposed = false;-- (async () => {- try {- const { Workbook } = await import('exceljs');- const workbook = new Workbook();- await workbook.xlsx.load(await blob.arrayBuffer());- if (disposed) return;-- const grids: SheetGrid[] = workbook.worksheets.map((sheet) => {- const columnCount = sheet.actualColumnCount;- const rows: string[][] = [];- // eachRow skips empty rows, keeping the preview dense; row order is preserved.- sheet.eachRow((row) => {- if (rows.length >= MAX_PREVIEW_ROWS) return;- const cells: string[] = [];- for (let index = 1; index <= columnCount; index++) {- cells.push(formatCellValue(row.getCell(index).value));- }- rows.push(cells);- });- return { name: sheet.name, rows, truncated: sheet.actualRowCount > MAX_PREVIEW_ROWS };- });- setSheets(grids);- setActiveSheet(0);- } catch (error) {- if (!disposed) onError(error);- }- })();-- return () => {- disposed = true;- };- }, [blob, onError]);-- if (!sheets) return <Loading />;-- const sheet = sheets[activeSheet] ?? sheets[0];-- return (- <div className={styles.xlsxContainer}>- {sheets.length > 1 && (- <div className={styles.sheetTabs}>- {sheets.map((item, index) => (- <button- className={styles.sheetTab}- data-active={index === activeSheet}- key={`${index}-${item.name}`}- type={'button'}- onClick={() => setActiveSheet(index)}- >- {item.name}- </button>- ))}- </div>- )}- <div className={styles.xlsxTable}>- <table>- <tbody>- {sheet?.rows.map((row, rowIndex) => (- <tr key={rowIndex}>- {row.map((cell, cellIndex) => (- <td key={cellIndex}>{cell}</td>- ))}- </tr>- ))}- </tbody>- </table>- {sheet?.truncated && (- <div className={styles.truncatedNote}>- {t('workingPanel.localFile.document.truncatedRows', { count: MAX_PREVIEW_ROWS })}- </div>- )}- </div>- </div>- );-});--XlsxPane.displayName = 'XlsxPane';-/*** Modern OOXML formats with an in-app renderer. Legacy binary formats (.doc /* .ppt / .xls) have none and keep the download / open-externally fallback.diff --git a/src/features/Portal/LocalFile/xlsx/SheetDocument.test.tsx b/src/features/Portal/LocalFile/xlsx/SheetDocument.test.tsxnew file mode 100644index 00000000000..86eb912f992--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/SheetDocument.test.tsx@@ -0,0 +1,47 @@+/**+ * @vitest-environment happy-dom+ */+import { render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import type { SheetOutline } from './classifySheet';+import type { CellModel } from './model';+import SheetDocument from './SheetDocument';++const cell = (c: number, t: string): CellModel => ({+ c,+ s: {},+ t,+});++describe('SheetDocument', () => {+ it('renders row extras when the final table column is empty', () => {+ const outline: SheetOutline = {+ bodyFontSize: 11,+ confidence: 1,+ mode: 'reflow',+ sections: [+ {+ blank: 0,+ body: [+ {+ cells: [cell(1, '9/15'), cell(2, '住宿')],+ extras: [cell(4, '确认码 HMTD')],+ kind: 'data',+ },+ ],+ header: [cell(1, '日期'), cell(2, '项目'), cell(3, '金额')],+ notes: [],+ title: null,+ },+ ],+ stats: { aside: 0, chrome: 0, kv: 0, note: 0, table: 1 },+ subtitle: null,+ title: null,+ };++ render(<SheetDocument outline={outline} />);++ expect(screen.getByText('确认码 HMTD')).toBeTruthy();+ });+});diff --git a/src/features/Portal/LocalFile/xlsx/SheetDocument.tsx b/src/features/Portal/LocalFile/xlsx/SheetDocument.tsxnew file mode 100644index 00000000000..490761edfca--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/SheetDocument.tsx@@ -0,0 +1,154 @@+import { Fragment, memo } from 'react';++import type { BodyItem, SheetOutline, SheetSection } from './classifySheet';+import type { CellModel } from './model';+import { styles } from './styles';++const alignOf = (cell: CellModel) =>+ cell.s.h === 'right' ? 'right' : cell.s.h === 'center' ? 'center' : undefined;++const SectionTable = memo<{+ header: CellModel[];+ rows: Extract<BodyItem, { extras: CellModel[] }>[];+}>(({ header, rows }) => {+ const columns = header.map((cell) => cell.c);++ return (+ <div className={styles.table}>+ <table>+ <thead>+ <tr>+ {header.map((cell, index) => (+ <th data-align={index === 0 ? undefined : alignOf(cell)} key={cell.c}>+ {cell.t}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map((row, rowIndex) => {+ const byColumn = new Map(row.cells.map((cell) => [cell.c, cell]));+ return (+ <tr data-total={row.kind === 'total' ? '' : undefined} key={rowIndex}>+ {columns.map((column, columnIndex) => {+ const cell = byColumn.get(column);+ const extras =+ columnIndex === columns.length - 1 && row.extras.length > 0+ ? row.extras.map((item) => item.t).join(' · ')+ : '';+ if (!cell)+ return (+ <td key={column}>+ {extras ? <span className={styles.extra}>{extras}</span> : null}+ </td>+ );+ return (+ <td data-align={alignOf(cell)} key={column}>+ {cell.t}+ {extras ? <span className={styles.extra}>{extras}</span> : null}+ </td>+ );+ })}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+});++SectionTable.displayName = 'SectionTable';++const KeyValueList = memo<{ bodyFontSize: number; rows: CellModel[][] }>(+ ({ bodyFontSize, rows }) => (+ <dl className={styles.kv}>+ {rows.map((cells, index) => {+ const [label, ...rest] = cells;+ return (+ <Fragment key={index}>+ <dt>{label.t}</dt>+ <dd>+ {rest.length === 0+ ? '—'+ : rest.map((cell, cellIndex) => (+ <span+ key={cell.c}+ className={+ cell.s.bg && cell.s.b+ ? styles.chip+ : (cell.s.fs ?? 11) < bodyFontSize+ ? styles.hint+ : undefined+ }+ >+ {cellIndex > 0 ? ' ' : ''}+ {cell.t}+ </span>+ ))}+ </dd>+ </Fragment>+ );+ })}+ </dl>+ ),+);++KeyValueList.displayName = 'KeyValueList';++const SectionBlock = memo<{ bodyFontSize: number; section: SheetSection }>(+ ({ bodyFontSize, section }) => {+ const tableRows = section.body.filter(+ (item): item is Extract<BodyItem, { extras: CellModel[] }> => item.kind !== 'kv',+ );+ const listRows = section.body.filter((item) => item.kind === 'kv').map((item) => item.cells);++ return (+ <section className={styles.section}>+ {section.title ? (+ <div className={styles.sectionHead}>+ <span>{section.title}</span>+ <span className={styles.sectionRule} />+ </div>+ ) : null}+ {section.header && tableRows.length > 0 ? (+ <SectionTable header={section.header} rows={tableRows} />+ ) : null}+ {listRows.length > 0 ? <KeyValueList bodyFontSize={bodyFontSize} rows={listRows} /> : null}+ {section.notes.length > 0 ? (+ <div className={styles.hint}>+ {section.notes.map((note, index) => (+ <div key={index}>{note}</div>+ ))}+ </div>+ ) : null}+ </section>+ );+ },+);++SectionBlock.displayName = 'SectionBlock';++interface SheetDocumentProps {+ outline: SheetOutline;+}++const SheetDocument = memo<SheetDocumentProps>(({ outline }) => (+ <div className={styles.container}>+ <div className={styles.doc}>+ {outline.title || outline.subtitle ? (+ <div className={styles.docHead}>+ {outline.title ? <div className={styles.docTitle}>{outline.title.t}</div> : null}+ {outline.subtitle ? <div className={styles.docSubtitle}>{outline.subtitle.t}</div> : null}+ </div>+ ) : null}+ {outline.sections.map((section, index) => (+ <SectionBlock bodyFontSize={outline.bodyFontSize} key={index} section={section} />+ ))}+ </div>+ </div>+));++SheetDocument.displayName = 'SheetDocument';++export default SheetDocument;diff --git a/src/features/Portal/LocalFile/xlsx/SheetGrid.test.tsx b/src/features/Portal/LocalFile/xlsx/SheetGrid.test.tsxnew file mode 100644index 00000000000..9b8eb5028cf--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/SheetGrid.test.tsx@@ -0,0 +1,43 @@+/**+ * @vitest-environment happy-dom+ */+import { render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import type { SheetModel } from './model';+import SheetGrid from './SheetGrid';++describe('SheetGrid', () => {+ it('keeps frozen columns sticky with resolved inline offsets', () => {+ const sheet: SheetModel = {+ cols: [80, 90, 100],+ frozen: { cols: 2, rows: 0 },+ name: 'Frozen Columns',+ rowCount: 1,+ rows: [+ {+ cells: [+ { c: 1, s: {}, t: 'account' },+ { c: 2, s: {}, t: 'region' },+ { c: 3, s: {}, t: 'amount' },+ ],+ h: null,+ r: 1,+ },+ ],+ truncated: false,+ };++ render(<SheetGrid sheet={sheet} />);++ const firstFrozen = screen.getByText('account').closest('td')!;+ const secondFrozen = screen.getByText('region').closest('td')!;+ const scrollable = screen.getByText('amount').closest('td')!;++ expect(firstFrozen.style.position).toBe('sticky');+ expect(firstFrozen.style.insetInlineStart).toBe('46px');+ expect(secondFrozen.style.position).toBe('sticky');+ expect(secondFrozen.style.insetInlineStart).toBe('126px');+ expect(scrollable.style.position).toBe('');+ });+});diff --git a/src/features/Portal/LocalFile/xlsx/SheetGrid.tsx b/src/features/Portal/LocalFile/xlsx/SheetGrid.tsxnew file mode 100644index 00000000000..70a52894872--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/SheetGrid.tsx@@ -0,0 +1,254 @@+import { createStaticStyles } from 'antd-style';+import { memo, useLayoutEffect, useRef } from 'react';++import type { CellModel, CellStyle, SheetModel } from './model';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: auto;+ flex: 1;++ /* The grid replays the workbook's own colors, which were authored against+ white paper — theme-following surfaces would put the file's font colors+ on a dark ground. */+ color: #1a1a1a;+ background: #fff;++ table {+ table-layout: fixed;+ border-spacing: 0;+ border-collapse: separate;+ }++ td {+ overflow: hidden;++ /* Frozen rows are sticky; an unfilled cell must still paint over the+ rows scrolling underneath it. Cell fills override this inline. */+ padding-block: 1px;+ padding-inline: 4px;+ border-block-end: 1px solid #e0e2e6;+ border-inline-end: 1px solid #e0e2e6;++ font-size: 13px;+ line-height: 1.35;+ vertical-align: bottom;++ background: #fff;+ }+ `,+ corner: css`+ z-index: 5;+ inset-block-start: 0;+ inset-inline-start: 0;+ `,+ frozen: css`+ td,+ th {+ position: sticky;+ z-index: 3;+ }+ `,+ frozenLast: css`+ td,+ th {+ box-shadow: 0 1px 0 0 #9aa4b2;+ }+ `,+ frozenColumnLast: css`+ box-shadow: 1px 0 0 0 #9aa4b2;+ `,+ gutter: css`+ position: sticky;++ border-block-end: 1px solid #e0e2e6;+ border-inline-end: 1px solid #e0e2e6;++ font-size: 11px;+ font-weight: 400;+ color: #6a7280;+ text-align: center;+ white-space: nowrap;++ background: #f2f3f5;+ `,+ headCell: css`+ z-index: 3;+ inset-block-start: 0;+ height: 22px;+ `,+ rowHead: css`+ z-index: 2;+ inset-inline-start: 0;+ width: 46px;+ `,+}));++const GUTTER_WIDTH = 46;++const columnName = (index: number) => {+ let name = '';+ let value = index;+ while (value > 0) {+ const rest = (value - 1) % 26;+ name = String.fromCharCode(65 + rest) + name;+ value = (value - rest - 1) / 26;+ }+ return name;+};++const pointToPixel = (value: number) => Math.round((value * 4) / 3);++const BORDER_EDGE = { b: 'blockEnd', l: 'inlineStart', r: 'inlineEnd', t: 'blockStart' } as const;++const toCssStyle = (style: CellStyle): Record<string, string> => {+ const css: Record<string, string> = {+ textAlign: style.h ?? 'left',+ verticalAlign: style.v === 'middle' ? 'middle' : style.v === 'top' ? 'top' : 'bottom',+ whiteSpace: style.w ? 'pre-wrap' : 'nowrap',+ };+ if (style.bg) css.background = style.bg;+ if (style.fc) css.color = style.fc;+ if (style.b) css.fontWeight = '600';+ if (style.i) css.fontStyle = 'italic';+ if (style.fs) css.fontSize = `${pointToPixel(style.fs)}px`;+ if (style.ff) css.fontFamily = `"${style.ff}", var(--font-family, sans-serif)`;+ for (const [key, side] of Object.entries(style.bd ?? {})) {+ const edge = BORDER_EDGE[key as keyof typeof BORDER_EDGE];+ css[`border${edge[0].toUpperCase()}${edge.slice(1)}`] = `${side[0]}px solid ${side[1]}`;+ }+ return css;+};++const stickyColumnStyle = (+ offset: number,+ frozenRow: boolean,+): Record<string, string | number> => ({+ insetInlineStart: offset,+ position: 'sticky',+ zIndex: frozenRow ? 4 : 2,+});++const GridCell = memo<{+ cell: CellModel;+ frozenColOffset?: number;+ frozenRow: boolean;+ lastFrozenCol: boolean;+}>(({ cell, frozenColOffset, frozenRow, lastFrozenCol }) => (+ <td+ className={lastFrozenCol ? styles.frozenColumnLast : undefined}+ colSpan={cell.cs}+ rowSpan={cell.rs}+ style={{+ ...toCssStyle(cell.s),+ ...(frozenColOffset === undefined ? {} : stickyColumnStyle(frozenColOffset, frozenRow)),+ }}+ >+ {cell.t}+ </td>+));++GridCell.displayName = 'GridCell';++interface SheetGridProps {+ sheet: SheetModel;+}++const SheetGrid = memo<SheetGridProps>(({ sheet }) => {+ const container = useRef<HTMLDivElement>(null);+ const frozenRows = sheet.frozen?.rows ?? 0;+ const frozenCols = sheet.frozen?.cols ?? 0;+ const frozenColOffsets = sheet.cols.reduce<number[]>((offsets, _width, index) => {+ if (index < frozenCols)+ offsets.push((offsets.at(-1) ?? GUTTER_WIDTH) + (index === 0 ? 0 : sheet.cols[index - 1]));+ return offsets;+ }, []);++ // Sticky rows need their own resolved offsets; row heights are only known+ // once the browser has laid the table out.+ useLayoutEffect(() => {+ const root = container.current;+ if (!root || frozenRows === 0) return;+ const head = root.querySelector('thead th');+ if (!head) return;+ let offset = head.getBoundingClientRect().height;+ for (const row of root.querySelectorAll<HTMLTableRowElement>('tbody tr[data-frozen]')) {+ for (const child of row.children)+ (child as HTMLElement).style.insetBlockStart = `${offset}px`;+ offset += row.getBoundingClientRect().height;+ }+ }, [sheet, frozenRows]);++ return (+ <div className={styles.container} ref={container}>+ <table>+ <colgroup>+ <col style={{ width: GUTTER_WIDTH }} />+ {sheet.cols.map((width, index) => (+ <col key={index} style={{ width }} />+ ))}+ </colgroup>+ <thead>+ <tr>+ <th className={`${styles.gutter} ${styles.corner} ${styles.headCell}`} />+ {sheet.cols.map((_, index) => (+ <th+ key={index}+ className={[+ styles.gutter,+ styles.headCell,+ index === frozenCols - 1 && styles.frozenColumnLast,+ ]+ .filter(Boolean)+ .join(' ')}+ style={+ index >= frozenCols+ ? undefined+ : { insetInlineStart: frozenColOffsets[index], zIndex: 4 }+ }+ >+ {columnName(index + 1)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {sheet.rows.map((row) => {+ const frozen = row.r <= frozenRows;+ const className = [+ frozen && styles.frozen,+ frozen && row.r === frozenRows && styles.frozenLast,+ ]+ .filter(Boolean)+ .join(' ');+ return (+ <tr+ className={className}+ data-frozen={frozen ? '' : undefined}+ key={row.r}+ style={row.h ? { height: pointToPixel(row.h) } : undefined}+ >+ <th className={`${styles.gutter} ${styles.rowHead}`}>{row.r}</th>+ {row.cells.map((cell) => (+ <GridCell+ cell={cell}+ frozenRow={frozen}+ key={cell.c}+ lastFrozenCol={cell.c === frozenCols}+ frozenColOffset={+ cell.c <= frozenCols ? frozenColOffsets[cell.c - 1] : undefined+ }+ />+ ))}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+});++SheetGrid.displayName = 'SheetGrid';++export default SheetGrid;diff --git a/src/features/Portal/LocalFile/xlsx/XlsxPane.tsx b/src/features/Portal/LocalFile/xlsx/XlsxPane.tsxnew file mode 100644index 00000000000..761c171d23a--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/XlsxPane.tsx@@ -0,0 +1,164 @@+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: space-between;++ padding-block: 6px;+ padding-inline: 8px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ modes: css`+ display: flex;+ flex: none;+ gap: 4px;+ `,+ 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;+ `,+ 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>+ <div className={styles.modes}>+ <button+ className={styles.tab}+ data-active={resolvedMode === 'reflow'}+ type={'button'}+ onClick={() => setMode('reflow')}+ >+ {t('workingPanel.localFile.document.xlsxReflow')}+ </button>+ <button+ className={styles.tab}+ data-active={resolvedMode === 'fidelity'}+ type={'button'}+ onClick={() => setMode('fidelity')}+ >+ {t('workingPanel.localFile.document.xlsxOriginal')}+ </button>+ </div>+ </div>+ </div>+ );+});++XlsxPane.displayName = 'XlsxPane';++export default XlsxPane;diff --git a/src/features/Portal/LocalFile/xlsx/classifySheet.test.ts b/src/features/Portal/LocalFile/xlsx/classifySheet.test.tsnew file mode 100644index 00000000000..c6f9cfcd98a--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/classifySheet.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from 'vitest';++import { classifySheet } from './classifySheet';+import type { CellModel, SheetModel } from './model';++const cell = (c: number, t: string, s: CellModel['s'] = {}, span?: number): CellModel => ({+ c,+ s: { h: 'left', ...s },+ t,+ ...(span ? { cs: span, rs: 1 } : {}),+});++const sheet = (rows: CellModel[][], colCount = 4): SheetModel => ({+ cols: Array.from({ length: colCount }, () => 80),+ frozen: null,+ name: 'Sheet1',+ rowCount: rows.length,+ rows: rows.map((cells, index) => ({ cells, h: null, r: index + 1 })),+ truncated: false,+});++const band = (t: string, s: CellModel['s'], colCount = 4) => [cell(1, t, s, colCount)];++describe('classifySheet', () => {+ it('reads a banded title, sections, header and total row', () => {+ const outline = classifySheet(+ sheet([+ band('旅行分账表', { b: 1, bg: '#2F5496', fs: 16 }),+ band('共同消费平摊', { bg: '#2F5496', fs: 10 }),+ band('共同消费', { b: 1, bg: '#D9E1F2', fs: 11 }),+ [+ cell(1, '日期', { b: 1, bg: '#4472C4' }),+ cell(2, '项目', { b: 1, bg: '#4472C4' }),+ cell(3, '金额', { b: 1, bg: '#4472C4' }),+ ],+ [cell(1, '5/31'), cell(2, '机票'), cell(3, '4502')],+ [+ cell(1, '合计', { b: 1, bg: '#D9E1F2' }),+ cell(2, '', { b: 1, bg: '#D9E1F2' }),+ cell(3, '4502', { b: 1, bg: '#D9E1F2' }),+ ],+ ]),+ );++ expect(outline.title?.t).toBe('旅行分账表');+ expect(outline.subtitle?.t).toBe('共同消费平摊');+ expect(outline.sections).toHaveLength(1);+ expect(outline.sections[0].header?.map((item) => item.t)).toEqual(['日期', '项目', '金额']);+ expect(outline.sections[0].body.map((item) => item.kind)).toEqual(['data', 'total']);+ expect(outline.stats.aside).toBe(0);+ expect(outline.mode).toBe('reflow');+ });++ it('treats repeated top-size bands as sections instead of a document title', () => {+ const outline = classifySheet(+ sheet([+ band('紧急联系', { b: 1, fs: 14 }),+ [cell(1, '项目', { b: 1, bg: '#1F4E78' }), cell(2, '号码', { b: 1, bg: '#1F4E78' })],+ [cell(1, '警察'), cell(2, '110')],+ band('支付建议', { b: 1, fs: 14 }),+ [cell(1, '场景', { b: 1, bg: '#1F4E78' }), cell(2, '方式', { b: 1, bg: '#1F4E78' })],+ [cell(1, '餐厅'), cell(2, '刷卡')],+ ]),+ );++ expect(outline.title).toBeNull();+ expect(outline.sections.map((item) => item.title)).toEqual(['紧急联系', '支付建议']);+ expect(outline.sections.every((item) => item.header !== null)).toBe(true);+ });++ it('keeps a header whose data rows only fill the first column', () => {+ const outline = classifySheet(+ sheet([+ band('个人支出', { b: 1, bg: '#EAF1FD', fs: 11 }),+ [+ cell(1, '#', { b: 1, bg: '#1F6FEB' }),+ cell(2, '日期', { b: 1, bg: '#1F6FEB' }),+ cell(3, '金额', { b: 1, bg: '#1F6FEB' }),+ ],+ [cell(1, '1')],+ [cell(1, '2')],+ ]),+ );++ expect(outline.sections[0].header).not.toBeNull();+ expect(outline.stats.table).toBe(2);+ });++ it('keeps cells outside the header columns as row extras', () => {+ const outline = classifySheet(+ sheet(+ [+ [+ cell(1, '日期', { b: 1, bg: '#4472C4' }),+ cell(2, '项目', { b: 1, bg: '#4472C4' }),+ cell(3, '金额', { b: 1, bg: '#4472C4' }),+ ],+ [cell(1, '9/15'), cell(2, '住宿'), cell(3, '346'), cell(5, '确认码 HMTD', { fs: 9 })],+ ],+ 5,+ ),+ );++ const [row] = outline.sections[0].body;+ expect(row.kind).toBe('data');+ expect(row.kind !== 'kv' && row.extras.map((item) => item.t)).toEqual(['确认码 HMTD']);+ expect(outline.stats.aside).toBe(0);+ });++ it('does not classify filled data rows as totals without a total marker', () => {+ const outline = classifySheet(+ sheet([+ [+ cell(1, '日期', { b: 1, bg: '#4472C4' }),+ cell(2, '项目', { b: 1, bg: '#4472C4' }),+ cell(3, '金额', { b: 1, bg: '#4472C4' }),+ ],+ [+ cell(1, '9/15', { bg: '#EAF1FD' }),+ cell(2, '住宿', { bg: '#EAF1FD' }),+ cell(3, '346', { bg: '#EAF1FD' }),+ ],+ ]),+ );++ expect(outline.sections[0].body[0].kind).toBe('data');+ });++ it('falls back to the fidelity grid when no structure is recognised', () => {+ const outline = classifySheet(+ sheet([+ [cell(1, '两个人:', { b: 1 }), cell(2, '11', { b: 1, bg: '#FFF2CC' })],+ [cell(1, '汇率:', { b: 1 }), cell(2, '5.28', { b: 1, bg: '#FFF2CC' })],+ ]),+ );++ expect(outline.sections[0].header).toBeNull();+ expect(outline.stats.kv).toBe(2);+ expect(outline.confidence).toBeLessThan(0.7);+ expect(outline.mode).toBe('fidelity');+ });+});diff --git a/src/features/Portal/LocalFile/xlsx/classifySheet.ts b/src/features/Portal/LocalFile/xlsx/classifySheet.tsnew file mode 100644index 00000000000..6edc29ece98--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/classifySheet.ts@@ -0,0 +1,204 @@+import type { CellModel, RowModel, SheetModel } from './model';++export type BodyItem =+ | { cells: CellModel[]; extras: CellModel[]; kind: 'data' | 'total' }+ | { cells: CellModel[]; kind: 'kv' };++export interface SheetSection {+ blank: number;+ body: BodyItem[];+ header: CellModel[] | null;+ notes: string[];+ title: string | null;+}++export interface SheetOutline {+ bodyFontSize: number;+ confidence: number;+ mode: 'reflow' | 'fidelity';+ sections: SheetSection[];+ stats: { aside: number; chrome: number; kv: number; note: number; table: number };+ subtitle: CellModel | null;+ title: CellModel | null;+}++const TOTAL_WORDS = /合计|小计|总计|净额|总额|汇总|total|sum|subtotal/i;++const CONFIDENCE_FLOOR = 0.7;++const KV_WEIGHT = 0.6;++const fontSize = (cell: CellModel) => cell.s.fs ?? 11;++interface ContentRow {+ blankAfter: number;+ cells: CellModel[];+ r: number;+}++const readContent = (rows: RowModel[]): ContentRow[] => {+ const content: ContentRow[] = [];+ for (const row of rows) {+ const cells = row.cells.filter((cell) => cell.t.trim());+ if (cells.length > 0) content.push({ blankAfter: 0, cells, r: row.r });+ else if (content.length > 0) content.at(-1)!.blankAfter += 1;+ }+ return content;+};++export const classifySheet = (sheet: SheetModel): SheetOutline => {+ const colCount = sheet.cols.length;+ const content = readContent(sheet.rows);++ const isBand = (row: ContentRow) => {+ const [cell] = row.cells;+ return row.cells.length === 1 && cell.c === 1 && (cell.cs ?? 1) >= Math.max(2, colCount * 0.8);+ };++ const bodySizes = content+ .filter((row) => !isBand(row))+ .flatMap((row) => row.cells.map((cell) => fontSize(cell)))+ .sort((a, b) => a - b);+ const bodyFontSize = bodySizes.length > 0 ? bodySizes[Math.floor(bodySizes.length / 2)] : 11;++ const bands = content.filter((row) => isBand(row));+ const largestBand = bands.reduce((max, row) => Math.max(max, fontSize(row.cells[0])), 0);+ const topBands = bands.filter((row) => fontSize(row.cells[0]) === largestBand);++ let title: CellModel | null = null;+ let subtitle: CellModel | null = null;+ let start = 0;++ const [firstRow, secondRow] = content;+ if (+ firstRow &&+ isBand(firstRow) &&+ firstRow.r <= 2 &&+ fontSize(firstRow.cells[0]) === largestBand &&+ largestBand > bodyFontSize &&+ topBands.length === 1+ ) {+ title = firstRow.cells[0];+ start = 1;+ if (+ secondRow &&+ isBand(secondRow) &&+ secondRow.cells[0].s.bg === title.s.bg &&+ fontSize(secondRow.cells[0]) < largestBand+ ) {+ subtitle = secondRow.cells[0];+ start = 2;+ }+ }++ const isSectionBand = (row: ContentRow) => {+ if (!isBand(row)) return false;+ const [cell] = row.cells;+ return Boolean(cell.s.b) && (Boolean(cell.s.bg) || fontSize(cell) > bodyFontSize);+ };++ interface DraftSection extends SheetSection {+ rows: { cells: CellModel[]; kind: 'note' | 'row' }[];+ }++ const sections: DraftSection[] = [];+ let current: DraftSection | null = null;+ const openSection = (sectionTitle: string | null): DraftSection => {+ const section: DraftSection = {+ blank: 0,+ body: [],+ header: null,+ notes: [],+ rows: [],+ title: sectionTitle,+ };+ sections.push(section);+ return section;+ };++ for (const row of content.slice(start)) {+ if (isSectionBand(row)) {+ current = openSection(row.cells[0].t);+ continue;+ }+ current ??= openSection(null);+ if (isBand(row)) {+ current.rows.push({ cells: row.cells, kind: 'note' });+ continue;+ }+ current.rows.push({ cells: row.cells, kind: 'row' });+ current.blank += row.blankAfter;+ }++ const findHeader = (section: DraftSection) => {+ const rows = section.rows;+ for (const [index, item] of rows.entries()) {+ if (item.kind !== 'row' || item.cells.length < 2) continue;+ if (!item.cells.every((cell) => cell.s.b && cell.s.bg)) continue;+ const background = item.cells[0].s.bg;+ if (!item.cells.every((cell) => cell.s.bg === background)) continue;+ if (item.cells.some((cell) => TOTAL_WORDS.test(cell.t))) continue;+ if (!rows.slice(index + 1).some((next) => next.kind === 'row')) continue;+ return item;+ }+ return null;+ };++ const stats = { aside: 0, chrome: 0, kv: 0, note: 0, table: 0 };+ if (title) stats.chrome += 1;+ if (subtitle) stats.chrome += 1;++ for (const section of sections) {+ if (section.title) stats.chrome += 1;+ const header = findHeader(section);+ section.header = header?.cells ?? null;+ const headerColumns = header?.cells.map((cell) => cell.c) ?? [];++ for (const item of section.rows) {+ if (item.kind === 'note') {+ section.notes.push(item.cells[0].t);+ stats.note += 1;+ continue;+ }+ if (header && item === header) {+ stats.chrome += 1;+ continue;+ }+ if (!header) {+ section.body.push({ cells: item.cells, kind: 'kv' });+ stats.kv += 1;+ continue;+ }++ const inColumns = item.cells.filter((cell) => headerColumns.includes(cell.c));+ const extras = item.cells.filter((cell) => !headerColumns.includes(cell.c));+ const fits =+ inColumns.length >= Math.ceil(item.cells.length * 0.6) &&+ headerColumns.includes(item.cells[0].c);++ if (!fits) {+ stats.aside += 1;+ section.body.push({ cells: item.cells, kind: 'kv' });+ continue;+ }++ const isTotal = item.cells.some((cell) => TOTAL_WORDS.test(cell.t));+ section.body.push({ cells: inColumns, extras, kind: isTotal ? 'total' : 'data' });+ stats.table += 1;+ }+ }++ const scored = stats.table + stats.chrome + stats.note + stats.kv * KV_WEIGHT;+ const weighted = stats.table + stats.chrome + stats.note + stats.kv + stats.aside;+ const confidence = weighted > 0 ? scored / weighted : 0;++ return {+ bodyFontSize,+ confidence,+ mode: confidence >= CONFIDENCE_FLOOR ? 'reflow' : 'fidelity',+ sections: sections.map(({ rows, ...section }) => section),+ stats,+ subtitle,+ title,+ };+};diff --git a/src/features/Portal/LocalFile/xlsx/model.test.ts b/src/features/Portal/LocalFile/xlsx/model.test.tsnew file mode 100644index 00000000000..630b3c5c417--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/model.test.ts@@ -0,0 +1,116 @@+import { Workbook } from 'exceljs';+import { describe, expect, it } from 'vitest';++import { readWorkbook } from './model';++const readWorksheet = async (workbook: Workbook) => {+ const buffer = await workbook.xlsx.writeBuffer();+ const [sheet] = await readWorkbook(new Blob([buffer as BlobPart]));++ return sheet;+};++describe('readWorkbook', () => {+ it('keeps sparse worksheet rows at their physical row positions', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Sparse');++ worksheet.getCell('A1').value = 'first';+ worksheet.getCell('A2').value = 'second';+ worksheet.getCell('A3').value = 'third';+ worksheet.getCell('A4').value = 'fourth';+ worksheet.getCell('A6').value = 'sixth';++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows.map((row) => row.r)).toEqual([1, 2, 3, 4, 6]);+ expect(sheet.rows.at(-1)?.cells[0].t).toBe('sixth');+ });++ it('formats percentage cells by scaling the stored value', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Percent');++ worksheet.getCell('A1').value = 0.15;+ worksheet.getCell('A1').numFmt = '0%';+ worksheet.getCell('A2').value = -0.125;+ worksheet.getCell('A2').numFmt = '0.0%';++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows[0].cells[0].t).toBe('15%');+ expect(sheet.rows[1].cells[0].t).toBe('-12.5%');+ });++ it('honors optional decimal placeholders', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Decimals');++ worksheet.getCell('A1').value = 1.25;+ worksheet.getCell('A1').numFmt = '0.##';+ worksheet.getCell('A2').value = 1.25;+ worksheet.getCell('A2').numFmt = '0.0#';+ worksheet.getCell('A3').value = 1.2;+ worksheet.getCell('A3').numFmt = '0.0#';++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows[0].cells[0].t).toBe('1.25');+ expect(sheet.rows[1].cells[0].t).toBe('1.25');+ expect(sheet.rows[2].cells[0].t).toBe('1.2');+ });++ it('formats scientific notation without fixed-point rounding', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Scientific');++ worksheet.getCell('A1').value = 0.001;+ worksheet.getCell('A1').numFmt = '0.00E+00';+ worksheet.getCell('A2').value = -123_000;+ worksheet.getCell('A2').numFmt = '0.0E+00';++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows[0].cells[0].t).toBe('1.00E-03');+ expect(sheet.rows[1].cells[0].t).toBe('-1.2E+05');+ });++ it('clips merged cell spans to rendered preview rows', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Merges');++ worksheet.getCell('A1').value = 'merged';+ worksheet.mergeCells('A1:A1000');++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows).toHaveLength(500);+ expect(sheet.rows[0].cells[0]).toMatchObject({ rs: 500, t: 'merged' });+ });++ it('formats cached date results from formula cells', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Formula Dates');++ worksheet.getCell('A1').value = { formula: 'DATE(2026,9,8)', result: new Date('2026-09-08') };++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows[0].cells[0].t).toBe('2026-09-08');+ });++ it('selects number format sections for negative and zero values', async () => {+ const workbook = new Workbook();+ const worksheet = workbook.addWorksheet('Sections');++ worksheet.getCell('A1').value = -1234;+ worksheet.getCell('A1').numFmt = '$#,##0.00;($#,##0.00);-';+ worksheet.getCell('A2').value = 0;+ worksheet.getCell('A2').numFmt = '$#,##0.00;($#,##0.00);-';++ const sheet = await readWorksheet(workbook);++ expect(sheet.rows[0].cells[0].t).toBe('($1,234.00)');+ expect(sheet.rows[1].cells[0].t).toBe('-');+ });+});diff --git a/src/features/Portal/LocalFile/xlsx/model.ts b/src/features/Portal/LocalFile/xlsx/model.tsnew file mode 100644index 00000000000..1f6af951633--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/model.ts@@ -0,0 +1,252 @@+import type { Border, Cell, Color, Row, Worksheet } from 'exceljs';++export interface CellStyle {+ b?: 1;+ bd?: Partial<Record<'b' | 'l' | 'r' | 't', [number, string]>>;+ bg?: string;+ fc?: string;+ ff?: string;+ fs?: number;+ h?: string;+ i?: 1;+ v?: string;+ w?: 1;+}++export interface CellModel {+ c: number;+ cs?: number;+ rs?: number;+ s: CellStyle;+ t: string;+}++export interface RowModel {+ cells: CellModel[];+ h: number | null;+ r: number;+}++export interface SheetModel {+ cols: number[];+ frozen: { cols: number; rows: number } | null;+ name: string;+ rowCount: number;+ rows: RowModel[];+ truncated: boolean;+}++export const MAX_PREVIEW_ROWS = 500;++const hex = (color?: Partial<Color>): string | undefined => {+ const argb = color?.argb;+ if (!argb) return undefined;+ return '#' + (argb.length === 8 ? argb.slice(2) : argb);+};++const formatNumber = (value: number, numFmt?: string): string => {+ if (!numFmt || numFmt === 'General') return String(Math.round(value * 1e10) / 1e10);+ const sections = numFmt.split(';');+ const usesNegativeSection = value < 0 && Boolean(sections[1]);+ const pattern = usesNegativeSection+ ? sections[1]+ : value === 0 && sections[2]+ ? sections[2]+ : sections[0];+ if (!/[0#]/.test(pattern)) return pattern.replaceAll('"', '');++ const isPercentage = pattern.includes('%');+ const displayValue = Math.abs(isPercentage ? value * 100 : value);+ const scientific = /E[+-]?(0+)/i.exec(pattern);+ const decimalPattern = pattern.match(/\.([0#]+)/)?.[1] ?? '';+ const decimals = decimalPattern.length;+ const requiredDecimals = decimalPattern.replaceAll('#', '').length;+ const firstPlaceholder = pattern.search(/[0#]/);+ const lastPlaceholder = Math.max(pattern.lastIndexOf('0'), pattern.lastIndexOf('#'));+ const sign = value < 0 && !usesNegativeSection ? '-' : '';+ const prefix = pattern.slice(0, firstPlaceholder).replaceAll('"', '');+ const suffix = pattern.slice(lastPlaceholder + 1).replaceAll('"', '');++ if (scientific) {+ const [mantissa, exponent] = displayValue.toExponential(decimals).split('e');+ const exponentValue = Number(exponent);+ const exponentSign = exponentValue < 0 ? '-' : '+';+ const exponentBody = String(Math.abs(exponentValue)).padStart(scientific[1].length, '0');++ return sign + prefix + mantissa + 'E' + exponentSign + exponentBody + suffix;+ }+ const body = new Intl.NumberFormat('en-US', {+ maximumFractionDigits: decimals,+ minimumFractionDigits: requiredDecimals,+ useGrouping: pattern.includes('#,##'),+ }).format(displayValue);++ return sign + prefix + body + suffix;+};++const formatCellValue = (value: Cell['value'] | unknown, numFmt?: string): string => {+ if (value === null || value === undefined) return '';+ if (value instanceof Date) return value.toISOString().slice(0, 10);+ if (typeof value === 'number') return formatNumber(value, numFmt);+ if (typeof value === 'object') {+ const rich = value as {+ error?: string;+ formula?: string;+ result?: unknown;+ richText?: { text: string }[];+ sharedFormula?: string;+ text?: unknown;+ };+ if (rich.richText) return rich.richText.map((run) => run.text).join('');+ if (rich.formula !== undefined || rich.sharedFormula !== undefined) {+ const result = rich.result;+ return formatCellValue(result, numFmt);+ }+ if (rich.text !== undefined) return String(rich.text);+ return rich.error ?? '';+ }+ return String(value);+};++const cellText = (cell: Cell): string => formatCellValue(cell.value, cell.numFmt);++const isNumericCell = (cell: Cell): boolean => {+ const value = cell.value;+ if (typeof value === 'number') return true;+ return typeof (value as { result?: unknown })?.result === 'number';+};++const BORDER_WIDTH: Record<string, number> = {+ double: 3,+ hair: 1,+ medium: 2,+ thick: 3,+ thin: 1,+};++const borderSide = (side?: Partial<Border>): [number, string] | undefined =>+ side?.style ? [BORDER_WIDTH[side.style] ?? 1, hex(side.color) ?? '#bfbfbf'] : undefined;++const readCellStyle = (cell: Cell, numeric: boolean): CellStyle => {+ const font = cell.font ?? {};+ const alignment = cell.alignment ?? {};+ const border = cell.border ?? {};+ const style: CellStyle = { h: alignment.horizontal ?? (numeric ? 'right' : 'left') };++ if (font.bold) style.b = 1;+ if (font.italic) style.i = 1;+ if (font.size) style.fs = font.size;+ if (font.name) style.ff = font.name;+ const fontColor = hex(font.color);+ if (fontColor) style.fc = fontColor;++ const fill = cell.fill;+ if (fill?.type === 'pattern' && fill.pattern === 'solid') {+ const background = hex(fill.fgColor);+ if (background) style.bg = background;+ }++ if (alignment.vertical) style.v = alignment.vertical;+ if (alignment.wrapText) style.w = 1;++ const sides: CellStyle['bd'] = {};+ for (const [key, side] of [+ ['t', border.top],+ ['l', border.left],+ ['b', border.bottom],+ ['r', border.right],+ ] as const) {+ const parsed = borderSide(side);+ if (parsed) sides[key] = parsed;+ }+ if (Object.keys(sides).length > 0) style.bd = sides;++ return style;+};++const columnLetterToIndex = (letters: string): number =>+ [...letters].reduce((total, char) => total * 26 + char.charCodeAt(0) - 64, 0);++const readMerges = (sheet: Worksheet, rowIndexes: number[], colCount: number) => {+ const spans = new Map<string, [number, number]>();+ const covered = new Set<string>();+ const renderedRows = new Set(rowIndexes);++ for (const ref of Object.values(sheet.model.merges ?? {}) as string[]) {+ const parsed = /([A-Z]+)(\d+):([A-Z]+)(\d+)/.exec(ref);+ if (!parsed) continue;+ const startCol = columnLetterToIndex(parsed[1]);+ const startRow = Number(parsed[2]);+ const endCol = columnLetterToIndex(parsed[3]);+ const endRow = Number(parsed[4]);+ if (!renderedRows.has(startRow) || startCol > colCount) continue;++ const rowSpan = rowIndexes.filter((row) => row >= startRow && row <= endRow).length;+ const colSpan = Math.min(endCol, colCount) - startCol + 1;+ spans.set(`${startRow}:${startCol}`, [rowSpan, colSpan]);+ for (const row of rowIndexes) {+ if (row < startRow || row > endRow) continue;+ for (let col = startCol; col <= Math.min(endCol, colCount); col++) {+ if (row !== startRow || col !== startCol) covered.add(`${row}:${col}`);+ }+ }+ }++ return { covered, spans };+};++const readSheet = (sheet: Worksheet): SheetModel => {+ const colCount = Math.max(sheet.actualColumnCount, 1);+ const view = sheet.views?.[0] as { state?: string; xSplit?: number; ySplit?: number } | undefined;+ const previewRows: Row[] = [];+ sheet.eachRow((row: Row) => {+ if (previewRows.length < MAX_PREVIEW_ROWS) previewRows.push(row);+ });+ const rowIndexes = previewRows.map((row) => row.number);+ const { covered, spans } = readMerges(sheet, rowIndexes, colCount);++ const rows: RowModel[] = [];+ for (const row of previewRows) {+ const rowIndex = row.number;+ const cells: CellModel[] = [];+ for (let colIndex = 1; colIndex <= colCount; colIndex++) {+ if (covered.has(`${rowIndex}:${colIndex}`)) continue;+ const cell = row.getCell(colIndex);+ const text = cellText(cell);+ const style = readCellStyle(cell, isNumericCell(cell));+ const span = spans.get(`${rowIndex}:${colIndex}`);+ if (!text && !style.bg && !style.bd && !span) {+ cells.push({ c: colIndex, s: {}, t: '' });+ continue;+ }+ cells.push({+ c: colIndex,+ s: style,+ t: text,+ ...(span ? { cs: span[1], rs: span[0] } : {}),+ });+ }+ rows.push({ cells, h: row.height ?? null, r: rowIndex });+ }++ const cols: number[] = [];+ for (let colIndex = 1; colIndex <= colCount; colIndex++) {+ cols.push(Math.round((sheet.getColumn(colIndex).width ?? 8.43) * 7 + 5));+ }++ return {+ cols,+ frozen: view?.state === 'frozen' ? { cols: view.xSplit ?? 0, rows: view.ySplit ?? 0 } : null,+ name: sheet.name,+ rowCount: rows.length,+ rows,+ truncated: sheet.actualRowCount > MAX_PREVIEW_ROWS,+ };+};++export const readWorkbook = async (blob: Blob): Promise<SheetModel[]> => {+ const { Workbook } = await import('exceljs');+ const workbook = new Workbook();+ await workbook.xlsx.load(await blob.arrayBuffer());+ return workbook.worksheets.map((sheet) => readSheet(sheet));+};diff --git a/src/features/Portal/LocalFile/xlsx/styles.ts b/src/features/Portal/LocalFile/xlsx/styles.tsnew file mode 100644index 00000000000..f34ac51b902--- /dev/null+++ b/src/features/Portal/LocalFile/xlsx/styles.ts@@ -0,0 +1,174 @@+import { createStaticStyles, cssVar } from 'antd-style';++export const styles = createStaticStyles(({ css }) => ({+ aside: css`+ display: flex;+ flex-wrap: wrap;+ gap: 10px;+ align-items: baseline;++ font-size: 13px;+ `,+ asideLabel: css`+ color: ${cssVar.colorTextSecondary};+ `,+ asideValue: css`+ font-weight: 500;+ font-variant-numeric: tabular-nums;+ `,+ chip: css`+ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 5px;++ font-size: 12.5px;+ font-weight: 500;+ color: ${cssVar.colorPrimary};++ background: ${cssVar.colorPrimaryBg};+ `,+ container: css`+ overflow: auto;+ flex: 1;+ background: ${cssVar.colorBgContainer};+ `,+ doc: css`+ display: flex;+ flex-direction: column;+ gap: 30px;++ max-width: 920px;+ margin-inline: auto;+ padding-block: 28px 44px;+ padding-inline: 32px;+ `,+ docHead: css`+ display: flex;+ flex-direction: column;+ gap: 6px;++ padding-block-end: 18px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ docSubtitle: css`+ font-size: 13.5px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ docTitle: css`+ font-size: 24px;+ font-weight: 600;+ text-wrap: balance;+ letter-spacing: -0.015em;+ `,+ extra: css`+ display: block;+ margin-block-start: 2px;+ font-size: 11px;+ color: ${cssVar.colorTextQuaternary};+ `,+ hint: css`+ font-size: 11.5px;+ line-height: 1.6;+ color: ${cssVar.colorTextQuaternary};+ `,+ kv: css`+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 9px 18px;+ align-items: baseline;++ margin: 0;++ dt {+ font-size: 12.5px;+ color: ${cssVar.colorTextSecondary};+ }++ dd {+ margin: 0;+ font-size: 13px;+ font-variant-numeric: tabular-nums;+ }+ `,+ section: css`+ display: flex;+ flex-direction: column;+ gap: 12px;+ `,+ sectionHead: css`+ display: flex;+ gap: 12px;+ align-items: center;++ font-size: 15px;+ font-weight: 600;+ `,+ sectionRule: css`+ flex: 1;+ height: 1px;+ background: ${cssVar.colorBorderSecondary};+ `,+ table: css`+ overflow-x: auto;++ table {+ border-collapse: collapse;++ /* The portal pane is narrow; let the grid keep its column rhythm and+ scroll sideways instead of collapsing cells into one glyph per line. */+ width: 100%;+ min-width: max-content;+ font-size: 13px;+ }++ th {+ padding-block-end: 8px;+ padding-inline: 10px;+ border-block-end: 1px solid ${cssVar.colorBorder};++ font-size: 10.5px;+ font-weight: 500;+ color: ${cssVar.colorTextQuaternary};+ text-align: start;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ white-space: nowrap;+ }++ td {+ max-width: 320px;+ padding-block: 8px;+ padding-inline: 10px;+ border-block-end: 1px solid ${cssVar.colorFillQuaternary};++ vertical-align: baseline;+ }++ tr[data-total] td {+ padding-block-start: 11px;+ border-block-start: 1px solid ${cssVar.colorBorder};+ border-block-end: none;+ font-weight: 600;+ }++ tbody tr:last-child td {+ border-block-end: none;+ }++ tbody tr:not([data-total]):hover td {+ background: ${cssVar.colorFillQuaternary};+ }++ td[data-align='right'],+ th[data-align='right'] {+ font-variant-numeric: tabular-nums;+ text-align: end;+ }++ td[data-align='center'],+ th[data-align='center'] {+ text-align: center;+ }+ `,+}));