diff --git a/web/src/AiMarkdown.tsx b/web/src/AiMarkdown.tsx
index 07d22f7..f7211ba 100644
--- a/web/src/AiMarkdown.tsx
+++ b/web/src/AiMarkdown.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react';
+import { tableTextAlignment } from './tableTextAlignment';
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
import { analysisEvidenceParts } from './analysisEvidenceRefs';
@@ -132,9 +133,10 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix,
index += 2;
const body: string[][] = [];
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
+ const alignments = headers.map((header, column) => tableTextAlignment(header, body.map(row => row[column])));
blocks.push(
diff --git a/web/src/AnalysisRecordList.tsx b/web/src/AnalysisRecordList.tsx
index 34bdf46..9dfb099 100644
--- a/web/src/AnalysisRecordList.tsx
+++ b/web/src/AnalysisRecordList.tsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert, Empty, Pagination, Select, Spin } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { QualityTable as Table } from './QualityTable';
+import { alignReportTableText, tableTextAlignment } from './tableTextAlignment';
import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
import {
analysisSourceRecordCompletenessNotice,
@@ -120,6 +121,7 @@ export function AnalysisRecordListPanel({ turn, value, onUnauthorized }: {
...fields.map(field => ({
title: field || '未命名字段',
key: `field:${field}`,
+ dataIndex: ['values', field],
width: 150,
ellipsis: true,
render: (_value: unknown, row: VisibleRow) => display(row.values[field]),
@@ -160,20 +162,22 @@ export function AnalysisRecordListReport({ value }: { value: unknown }) {
return
原始记录
{recordList.queryComplete ? `已读取全部 ${recordList.loadedRows} / ${recordList.totalRows} 条` : `读取未完成 ${recordList.loadedRows} / ${recordList.totalRows} 条`}
- {recordList.sets.map(set =>
+ {recordList.sets.map(set => {
+ const alignments = Object.fromEntries(set.fields.map(field => [field, tableTextAlignment(field, set.rows.map(row => row.values[field]))]));
+ return
{visibleSetLabel(set)}
{analysisSourceRecordSetReadStatus(set)}
{set.rows.length ? | 序号 | 来源文件 | 工作表 | 原始行号 |
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && 产品 | }
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && 组别 | }
- {set.fields.map(field => {field || '未命名字段'} | )}
+ {set.fields.map(field => {field || '未命名字段'} | )}
{set.rows.map((row, index) =>
| {index + 1} | {row.sourceFile} | {row.sheet} | {row.rowNumber} |
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && {row.product || '—'} | }
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && {row.group || '—'} | }
- {set.fields.map(field => {formatRecordValue(row.values[field])} | )}
+ {set.fields.map(field => {formatRecordValue(row.values[field])} | )}
)}
: {analysisSourceRecordEmptyState(recordList, set)}
}
- )}
+ ; })}
{recordList.sets.length === 0 && {analysisSourceRecordEmptyState(recordList)}
}
;
}
@@ -226,5 +230,6 @@ export function appendAnalysisRecordReportHtml(source: string, value: unknown):
}
if (!recordList.sets.length) { const empty = doc.createElement('p'); empty.className = 'q-note'; empty.textContent = analysisSourceRecordEmptyState(recordList); container.append(empty); }
doc.body.append(container);
+ alignReportTableText(doc);
return '\n' + doc.documentElement.outerHTML;
}
diff --git a/web/src/AnalysisReportExport.tsx b/web/src/AnalysisReportExport.tsx
index 91f8f60..7381481 100644
--- a/web/src/AnalysisReportExport.tsx
+++ b/web/src/AnalysisReportExport.tsx
@@ -19,6 +19,7 @@ import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportV
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
import { useDelayedIndicator } from './useDelayedBusy';
+import { alignReportTableText, tableTextAlignment } from './tableTextAlignment';
type Row = Record
;
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
@@ -46,6 +47,7 @@ export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp
const title = resolveAnalysisReportTitle(result.reportTitle, turn.reportTitle, reportMarkdown, model.period, scope);
const answer = sanitizeAnalysisDisplayText(stripDuplicateFirstMarkdownH1(sourceAnswer, title));
const memberList = parseAnalysisMemberList(result.memberList ?? turn.memberList);
+ const memberAlignments = Object.fromEntries(memberList?.fields.map(field => [field.key, tableTextAlignment(field.label, memberList.rows.map(row => row.values[field.key]))]) ?? []);
const recordListValue = result.recordList ?? turn.recordList;
const memberListStatus = memberList && analysisMemberListFullyRead(memberList)
? `已读取全部 ${memberList.rowsReturned} 条`
@@ -63,9 +65,9 @@ export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp
{memberList && 附录:完整成员清单
成员清单
{analysisMemberListPeriod(memberList.period)} · {memberListStatus}
- | 序号 | {memberList.fields.map(field => {field.label} | )}阶段 |
+ | 序号 | {memberList.fields.map(field => {field.label} | )}阶段 |
{memberList.rows.map((row, index) =>
- | {index + 1} | {memberList.fields.map(field => {text(row.values[field.key])} | )}
+ {index + 1} | {memberList.fields.map(field => {text(row.values[field.key])} | )}
{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')} |
)}
@@ -184,6 +186,7 @@ function safeNativeHtml(source: string, title: string): string {
exportStyle.setAttribute('data-report-export-layout', '');
exportStyle.textContent = 'html,body{box-sizing:border-box;width:900px!important;min-width:900px!important;max-width:900px!important;margin:0!important;overflow-wrap:anywhere}*,*:before,*:after{box-sizing:border-box}';
parsed.head.append(exportStyle);
+ alignReportTableText(parsed);
return `\n${parsed.documentElement.outerHTML}`;
}
diff --git a/web/src/QualityTable.tsx b/web/src/QualityTable.tsx
index 7af0a9d..4617734 100644
--- a/web/src/QualityTable.tsx
+++ b/web/src/QualityTable.tsx
@@ -1,10 +1,31 @@
import { Table as AntdTable } from 'antd';
import type { ColumnsType, ColumnType, TableProps } from 'antd/es/table';
-import { createContext, isValidElement, useContext, useState } from 'react';
+import { createContext, isValidElement, useContext, useState, type ReactNode } from 'react';
import { CompactTableCell } from './CompactTableCell';
+import { tableTextAlignment } from './tableTextAlignment';
export const CompactManagementTables = createContext(false);
+function titleText(value: ReactNode): string {
+ if (typeof value === 'string' || typeof value === 'number') return String(value);
+ if (Array.isArray(value)) return value.map(titleText).join('');
+ if (isValidElement<{ children?: ReactNode }>(value)) return titleText(value.props.children);
+ return '';
+}
+
+export function alignTableColumns(columns: ColumnsType, rows: readonly T[]): ColumnsType {
+ return columns.map(column => {
+ if ('children' in column) return { ...column, children: alignTableColumns(column.children, rows) };
+ const path = column.dataIndex === undefined ? [] : Array.isArray(column.dataIndex) ? column.dataIndex : [column.dataIndex];
+ const values = path.length ? rows.map(row => path.reduce((value, key) => value && typeof value === 'object' ? (value as Record)[String(key)] : undefined, row)) : [];
+ const label = typeof column.title === 'function' ? '' : titleText(column.title);
+ const alignment = tableTextAlignment(label || String(column.key ?? path.join('.')), values);
+ return alignment === 'left' ? {
+ ...column, align: 'left', className: [column.className, 'quality-table-text-column'].filter(Boolean).join(' '),
+ } : { ...column, align: column.align ?? 'center' };
+ });
+}
+
function compactColumns(columns: ColumnsType): ColumnsType {
return columns.map(column => {
const title = typeof column.title === 'function' ? column.title : {column.title};
@@ -40,6 +61,7 @@ export function QualityTable({
...props
}: QualityTableProps) {
const compact = useContext(CompactManagementTables);
+ const alignedColumns = alignTableColumns(columns ?? [], dataSource ?? []);
const pageConfig = typeof pagination === 'object' && pagination !== null ? pagination : undefined;
const [innerPage, setInnerPage] = useState(() => ({ current: pageConfig?.defaultCurrent ?? 1, pageSize: pageConfig?.defaultPageSize ?? 15 }));
const pageSize = pageConfig?.pageSize ?? innerPage.pageSize;
@@ -66,7 +88,7 @@ export function QualityTable({
{...props}
className={['quality-table', className].filter(Boolean).join(' ')}
tableLayout={props.tableLayout ?? (compact ? 'fixed' : undefined)}
- columns={[...(showRowNumbers ? [indexColumn] : []), ...(compact ? compactColumns(columns ?? []) : columns ?? [])]}
+ columns={[...(showRowNumbers ? [indexColumn] : []), ...(compact ? compactColumns(alignedColumns) : alignedColumns)]}
dataSource={dataSource}
pagination={pagination === false ? false : { defaultPageSize: 15, pageSizeOptions: ['15', '30', '50', '100'], ...pageConfig }}
onChange={handleChange}
diff --git a/web/src/QueryPage.tsx b/web/src/QueryPage.tsx
index 54d1de7..7cce13b 100644
--- a/web/src/QueryPage.tsx
+++ b/web/src/QueryPage.tsx
@@ -1582,7 +1582,7 @@ export function RecordsDrawer({
{ title: '产业部', dataIndex: 'department', key: 'department', width: 160 },
{ title: '业务分组', dataIndex: 'group', key: 'group', width: 190 },
{ title: '产品', dataIndex: 'product', key: 'product', width: 190 },
- ...visibleRawFields.map(name => ({ title: name, key: `raw:${name}`, width: 180, ellipsis: true, render: (_: unknown, record: RecordRow) => String(record.raw?.[name] ?? '—') })),
+ ...visibleRawFields.map(name => ({ title: name, key: `raw:${name}`, dataIndex: ['raw', name], width: 180, ellipsis: true, render: (_: unknown, record: RecordRow) => String(record.raw?.[name] ?? '—') })),
{ title: '规范化值与转换说明', key: 'transform', width: 260, render: (_: unknown, record: RecordRow) => 查看本行转换
规范化值转换说明{(record.transformNotes || []).map((note, index) => - {typeof note === 'string' ? note : }
)}
},
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => 查看计算分量
},
];
diff --git a/web/src/quality-table.css b/web/src/quality-table.css
index bbe2735..0c0bc12 100644
--- a/web/src/quality-table.css
+++ b/web/src/quality-table.css
@@ -46,6 +46,10 @@
overflow-wrap: anywhere;
}
+.quality-table-frame .ant-table-cell.quality-table-text-column {
+ text-align: left !important;
+}
+
.quality-table-frame .ant-table-bordered .ant-table-cell {
border-inline-end: 1px solid var(--line, #dfe5ef) !important;
border-bottom: 1px solid var(--line, #dfe5ef) !important;
@@ -169,6 +173,7 @@
.quality-cell-overflow { cursor: help; }
.quality-cell-preview:focus-visible { outline: 2px solid var(--blue, #6379df); outline-offset: 1px; }
.quality-cell-fulltext {
+ text-align: left;
max-width: 430px;
max-height: min(320px, 55vh);
overflow: auto;
diff --git a/web/src/tableTextAlignment.ts b/web/src/tableTextAlignment.ts
new file mode 100644
index 0000000..880dd01
--- /dev/null
+++ b/web/src/tableTextAlignment.ts
@@ -0,0 +1,25 @@
+/** Long prose is left aligned as a column; names and categorical attributes stay centered. */
+export function tableTextAlignment(label: string, values: readonly unknown[] = []): 'left' | 'center' {
+ const name = label.replace(/[*`\s_.://()()-]/g, '').toLowerCase();
+ if (/名称$|属性$|状态$|类型$|类别$|编号$|代码$|错误码$|^(errorcode|status|type|name)$/.test(name)) return 'center';
+ if (/说明|原因|备注|描述|内容|口径|公式|表达式|摘要|日志|错误|异常信息|处理信息|特殊情况处理|转换|依据|证据|详情|计算分量|命中范围|条件|建议|结论|措施|定义|原始字段|原始行数据|已识别的字段对应|阈值配置|核查事项|^差异项?$|description|reason|remark|note|formula|expression|explanation|message|error|summary|detail|rawrecord|components|condition|definition/.test(name)) return 'left';
+ if (/名称|属性|状态|类型|类别|分类|阶段|年度|年份|月份|期间|日期|时间|序号|行号|编码|编号|代码|产品|规格|品名|组别|分组|产业部|指标|单位|来源文件|工作表|操作|^(name|label|title|status|type|category|stage|year|month|period|date|time|index|id|code|product|group|department|metric|unit|sourcefile|sheet)$/.test(name)) return 'center';
+ return values.some(value => typeof value === 'string'
+ ? /[\r\n]/.test(value) || Array.from(value).length > 32
+ : value !== null && typeof value === 'object') ? 'left' : 'center';
+}
+
+/** Server-rendered report tables use the same rule as the application's tables. */
+export function alignReportTableText(root: Document | HTMLElement): void {
+ root.querySelectorAll('table').forEach(table => {
+ const rows = Array.from(table.rows);
+ const header = table.tHead?.rows[table.tHead.rows.length - 1] ?? rows.find(row => Array.from(row.cells).every(cell => cell.tagName === 'TH'));
+ if (!header || rows.some(row => Array.from(row.cells).some(cell => cell.colSpan !== 1 || cell.rowSpan !== 1))) return;
+ Array.from(header.cells).forEach((cell, index) => {
+ const dataCells = rows.filter(row => row !== header).map(row => row.cells[index]).filter(Boolean);
+ if (tableTextAlignment(cell.textContent || '', dataCells.map(item => item.textContent)) === 'left') {
+ [cell, ...dataCells].forEach(item => item.style.setProperty('text-align', 'left', 'important'));
+ }
+ });
+ });
+}
diff --git a/web/verification/analysis_member_report.test.mjs b/web/verification/analysis_member_report.test.mjs
index d5d2a10..a65a415 100644
--- a/web/verification/analysis_member_report.test.mjs
+++ b/web/verification/analysis_member_report.test.mjs
@@ -1,3 +1,4 @@
+import { tableTextAlignment } from '../src/tableTextAlignment.ts';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
@@ -14,14 +15,14 @@ import {
const exportSource = fs.readFileSync(new URL('../src/AnalysisReportExport.tsx', import.meta.url), 'utf8');
const reportDocumentSource = exportSource.slice(exportSource.indexOf('function ReportDocument('), exportSource.indexOf('\nfunction reportHtmlFromElement('));
const node = (tag, props) => React.createElement(tag, props, props?.children);
-const ReportDocument = new Function('React', 'reportCss', 'record', 'text', 'buildAnalysisNarrative', 'analysisScopeText',
+const ReportDocument = new Function('tableTextAlignment', 'React', 'reportCss', 'record', 'text', 'buildAnalysisNarrative', 'analysisScopeText',
'parseServerReadingSummary', 'resolveAnalysisReportTitle', 'sanitizeAnalysisDisplayText', 'stripDuplicateFirstMarkdownH1', 'AnalysisReportNarrative',
'AnalysisLegacyResults', 'AnalysisRecordListReport', 'analysisMemberListFullyRead', 'analysisMemberListPeriod', 'parseAnalysisMemberList',
ts.transpileModule(`${reportDocumentSource}\nreturn ReportDocument;`, {
fileName: 'analysis-report-document.tsx',
compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
}).outputText
-)(React, '', value => value && typeof value === 'object' && !Array.isArray(value) ? value : {},
+)(tableTextAlignment, React, '', value => value && typeof value === 'object' && !Array.isArray(value) ? value : {},
value => value === null || value === undefined || value === '' ? '—' : String(value),
() => ({ period: '2026年9月' }), () => '', parseServerReadingSummary, () => '分析报告', value => value, value => value,
({ answer }) => node('div', { className: 'report-summary', children: answer }), () => null, () => null,
@@ -51,7 +52,7 @@ test('the report includes every member row beyond the former 150-row limit as a
assert.match(html, /成员清单<\/h2>/);
assert.match(html, /| 成员<\/th>/);
- assert.match(html, / | 备注<\/th>/);
+ assert.match(html, / | 备注<\/th>/);
assert.match(html, / | 阶段<\/th>/);
assert.equal((html.match(/ | {
diff --git a/web/verification/analysis_record_list.test.mjs b/web/verification/analysis_record_list.test.mjs
index ac38e70..2961da6 100644
--- a/web/verification/analysis_record_list.test.mjs
+++ b/web/verification/analysis_record_list.test.mjs
@@ -1,3 +1,4 @@
+import { tableTextAlignment } from '../src/tableTextAlignment.ts';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
@@ -307,9 +308,9 @@ test('the report appendix includes all rows and set coverage, escaping source an
const componentSource = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
const helpers = componentSource.slice(componentSource.indexOf('function display('), componentSource.indexOf('export function AnalysisRecordListPanel'))
+ componentSource.slice(componentSource.indexOf('export function AnalysisRecordListReport'), componentSource.indexOf('/** Add the same all-row appendix'));
- const Component = new Function('React', 'analysisSourceRecordSetLabel', 'analysisSourceRecordSetReadStatus', 'parseAnalysisSourceRecordList',
+ const Component = new Function('React', 'analysisSourceRecordSetLabel', 'analysisSourceRecordSetReadStatus', 'parseAnalysisSourceRecordList', 'tableTextAlignment',
ts.transpileModule(`${helpers.replaceAll('export function ', 'function ')}\nreturn AnalysisRecordListReport;`, { fileName: 'analysis-record-report.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
- )(React, analysisSourceRecordSetLabel, analysisSourceRecordSetReadStatus, parseAnalysisSourceRecordList);
+ )(React, analysisSourceRecordSetLabel, analysisSourceRecordSetReadStatus, parseAnalysisSourceRecordList, tableTextAlignment);
const html = renderToStaticMarkup(React.createElement(Component, { value: recordList }));
assert.equal((html.match(/
new Function('React','useState','useContext','CompactManagementTables','AntdTable',transpile(`${code}\nreturn QualityTable;`))(React,hooks.useState,()=>false,{},'AntdTable'));
+ const code=read('QualityTable.tsx').slice(read('QualityTable.tsx').indexOf('function titleText')).replaceAll('export function ', 'function ');
+ const renderer=hookRenderer(hooks=>new Function('React','tableTextAlignment','isValidElement','useState','useContext','CompactManagementTables','AntdTable',transpile(`${code}\nreturn QualityTable;`))(React,tableTextAlignment,React.isValidElement,hooks.useState,()=>false,{},'AntdTable'));
return {render:()=>find(renderer.render(props),n=>n.type==='AntdTable').props,props};
}
diff --git a/web/verification/table_text_alignment.test.mjs b/web/verification/table_text_alignment.test.mjs
new file mode 100644
index 0000000..0a6d6b2
--- /dev/null
+++ b/web/verification/table_text_alignment.test.mjs
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import ts from 'typescript';
+import React from 'react';
+import { tableTextAlignment, alignReportTableText } from '../src/tableTextAlignment.ts';
+
+const source = fs.readFileSync(new URL('../src/QualityTable.tsx', import.meta.url), 'utf8');
+const helper = source.slice(source.indexOf('function titleText'), source.indexOf('function compactColumns')).replaceAll('export function ', 'function ');
+const alignTableColumns = new Function('isValidElement', 'tableTextAlignment', ts.transpileModule(helper + '\nreturn alignTableColumns;', {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
+}).outputText)(React.isValidElement, tableTextAlignment);
+
+test('prose columns align left even with short or empty current values; names and categorical attributes stay centered', () => {
+ for (const name of ['说明', '失败原因', '计算口径', '当前计算公式', '特殊情况处理', '原始行数据', '差异项', '阈值配置', 'description', 'error_message']) {
+ assert.equal(tableTextAlignment(name), 'left', name);
+ }
+ for (const name of ['产品名称', '说明类型', '证据状态', '错误码', '属性', '来源文件', '月份', 'status']) {
+ assert.equal(tableTextAlignment(name, ['很长的名称'.repeat(20)]), 'center', name);
+ }
+ assert.equal(tableTextAlignment('自定义列', ['短', '这是一段需要左对齐的较长业务文本。'.repeat(3)]), 'left');
+ assert.equal(tableTextAlignment('自定义列', ['首行\n下一行']), 'left');
+ assert.equal(tableTextAlignment('重量', [123, null]), 'center');
+});
+
+test('grouped and dynamic source columns preserve numeric alignment, callbacks and original definitions', () => {
+ const render = () => { throw new Error('classification must not execute cell renderers'); };
+ const columns = [{ title: '分组', children: [
+ { title: React.createElement('span', null, '当前计算公式'), align: 'center', className: 'original', render },
+ { title: '自定义', dataIndex: ['raw', '含.标点'], render },
+ { title: '产品名称', dataIndex: 'name' },
+ { title: '重量', dataIndex: 'weight', align: 'right' },
+ ] }];
+ const result = alignTableColumns(columns, [{ raw: { '含.标点': '详细记录'.repeat(20) }, name: '名称'.repeat(30), weight: 42 }]);
+ assert.deepEqual(result[0].children.map(column => column.align), ['left', 'left', 'center', 'right']);
+ assert.equal(result[0].children[0].render, render);
+ assert.equal(result[0].children[0].className, 'original quality-table-text-column');
+ assert.equal(columns[0].children[0].align, 'center');
+});
+
+test('native report prose cells and their headers align left without changing names or numbers', () => {
+ const cell = (text, tagName = 'TD') => ({ textContent: text, tagName, colSpan: 1, rowSpan: 1, style: { setProperty(...args) { this.applied = args; } } });
+ const header = { cells: [cell('产品名称', 'TH'), cell('备注', 'TH'), cell('重量', 'TH')] };
+ const row = { cells: [cell('产品甲'), cell('需现场核实'), cell('120')] };
+ const table = { rows: [header, row], tHead: { rows: [header] } };
+ alignReportTableText({ querySelectorAll: () => [table] });
+ assert.deepEqual(header.cells[1].style.applied, ['text-align', 'left', 'important']);
+ assert.deepEqual(row.cells[1].style.applied, ['text-align', 'left', 'important']);
+ assert.equal(row.cells[0].style.applied, undefined);
+ assert.equal(row.cells[2].style.applied, undefined);
+});