界面:表格长文本列统一左对齐,保留名称与属性对齐

This commit is contained in:
2026-11-04 12:45:39 +08:00
parent 9f282baa95
commit 7357c309dd
13 changed files with 138 additions and 21 deletions
+4 -2
View File
@@ -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(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
</table></div>);
if (tableNote) { blocks.push(note(tableNote)); tableNote = ''; }
continue;
+2 -2
View File
@@ -71,13 +71,13 @@ export function FocusProductTable({ rows, evidenceLabels, evidencePrefix, onDril
}) {
if (!rows.length) return null;
const table = (items: FocusProductRow[], offset = 0) => <div className="analysis-focus-table-wrap"><table className="analysis-focus-table">
<thead><tr><th scope="col" className="is-index">序号</th><th scope="col">产品规格</th><th scope="col" className="is-number">报废增量(kg)</th><th scope="col" className="is-number">合格率变化</th><th scope="col">入选依据</th></tr></thead>
<thead><tr><th scope="col" className="is-index">序号</th><th scope="col">产品规格</th><th scope="col" className="is-number">报废增量(kg)</th><th scope="col" className="is-number">合格率变化</th><th scope="col" style={{ textAlign: 'left' }}>入选依据</th></tr></thead>
<tbody>{items.map((row, index) => <tr key={`${offset + index}-${row.evidenceRefs.join('-')}`}>
<td className="is-index">{offset + index + 1}</td><th scope="row" className="analysis-focus-product" title={row.product}>{row.product}{onDrilldown && (drilldownUnavailableReason?.(row)
? <span className="analysis-product-unavailable">{drilldownUnavailableReason(row)}</span>
: <div className="analysis-product-actions">{(['defects', 'trend', 'records'] as ProductDrilldownView[]).map(view => <Button type="link" size="small" key={view} onClick={event => onDrilldown(row, view, event.currentTarget)}>{({ defects: '看缺陷', trend: '看趋势', records: '看来源明细' })[view]}</Button>)}</div>)}</th>
<td className="is-number">{row.scrapDelta}</td><td className={`is-number analysis-focus-rate ${row.rateChange.startsWith('下降') ? 'is-worse' : row.rateChange.startsWith('上升') ? 'is-better' : ''}`}><span>{row.rateLabel}</span>{row.rateChange}</td>
<td className="analysis-focus-basis">{row.basis}{row.evidenceRefs.map(ref => <a key={ref} className="analysis-evidence-ref" href={`#${evidencePrefix}${ref}`}>{evidenceLabels[ref] || '数据依据'}</a>)}</td>
<td className="analysis-focus-basis" style={{ textAlign: 'left' }}>{row.basis}{row.evidenceRefs.map(ref => <a key={ref} className="analysis-evidence-ref" href={`#${evidencePrefix}${ref}`}>{evidenceLabels[ref] || '数据依据'}</a>)}</td>
</tr>)}</tbody>
</table></div>;
return <div className="analysis-focus-products">
+9 -4
View File
@@ -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 <section className="q-source-record-list">
<h2>原始记录</h2>
<p className="q-note">{recordList.queryComplete ? `已读取全部 ${recordList.loadedRows} / ${recordList.totalRows} 条` : `读取未完成 ${recordList.loadedRows} / ${recordList.totalRows} 条`}</p>
{recordList.sets.map(set => <section className="q-source-record-set" key={set.id}>
{recordList.sets.map(set => {
const alignments = Object.fromEntries(set.fields.map(field => [field, tableTextAlignment(field, set.rows.map(row => row.values[field]))]));
return <section className="q-source-record-set" key={set.id}>
<h3>{visibleSetLabel(set)}</h3>
<p className="q-note">{analysisSourceRecordSetReadStatus(set)}</p>
{set.rows.length ? <table><thead><tr><th>序号</th><th>来源文件</th><th>工作表</th><th>原始行号</th>
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && <th>产品</th>}
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && <th>组别</th>}
{set.fields.map(field => <th key={field}>{field || '未命名字段'}</th>)}
{set.fields.map(field => <th key={field} style={{ textAlign: alignments[field] === 'left' ? 'left' : undefined }}>{field || '未命名字段'}</th>)}
</tr></thead><tbody>{set.rows.map((row, index) => <tr key={`${set.id}:${index}`}>
<td>{index + 1}</td><td>{row.sourceFile}</td><td>{row.sheet}</td><td>{row.rowNumber}</td>
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && <td>{row.product || '—'}</td>}
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && <td>{row.group || '—'}</td>}
{set.fields.map(field => <td key={field}>{formatRecordValue(row.values[field])}</td>)}
{set.fields.map(field => <td key={field} style={{ textAlign: alignments[field] === 'left' ? 'left' : undefined }}>{formatRecordValue(row.values[field])}</td>)}
</tr>)}</tbody></table> : <p className="q-note">{analysisSourceRecordEmptyState(recordList, set)}</p>}
</section>)}
</section>; })}
{recordList.sets.length === 0 && <p className="q-note">{analysisSourceRecordEmptyState(recordList)}</p>}
</section>;
}
@@ -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 '<!doctype html>\n' + doc.documentElement.outerHTML;
}
+5 -2
View File
@@ -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<string, unknown>;
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 && <details className="q-report-appendix"><summary>附录:完整成员清单</summary><section className="q-member-list">
<h2>成员清单</h2>
<p className="q-note">{analysisMemberListPeriod(memberList.period)} · {memberListStatus}</p>
<table><thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key}>{field.label}</th>)}<th>阶段</th></tr></thead>
<table><thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key} style={{ textAlign: memberAlignments[field.key] === 'left' ? 'left' : undefined }}>{field.label}</th>)}<th>阶段</th></tr></thead>
<tbody>{memberList.rows.map((row, index) => <tr key={index}>
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key}>{text(row.values[field.key])}</td>)}
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key} style={{ textAlign: memberAlignments[field.key] === 'left' ? 'left' : undefined }}>{text(row.values[field.key])}</td>)}
<td>{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')}</td>
</tr>)}</tbody>
</table>
@@ -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 `<!doctype html>\n${parsed.documentElement.outerHTML}`;
}
+24 -2
View File
@@ -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<T extends object>(columns: ColumnsType<T>, rows: readonly T[]): ColumnsType<T> {
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<unknown>((value, key) => value && typeof value === 'object' ? (value as Record<string, unknown>)[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<T extends object>(columns: ColumnsType<T>): ColumnsType<T> {
return columns.map(column => {
const title = typeof column.title === 'function' ? column.title : <CompactTableCell>{column.title}</CompactTableCell>;
@@ -40,6 +61,7 @@ export function QualityTable<T extends object>({
...props
}: QualityTableProps<T>) {
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<T extends object>({
{...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}
+1 -1
View File
@@ -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) => <details className="source-fields"><summary>查看本行转换</summary><strong>规范化值</strong><BusinessValue value={withoutSystemVersionFields(record.normalized || {})} /><strong>转换说明</strong><ul>{(record.transformNotes || []).map((note, index) => <li key={index}>{typeof note === 'string' ? note : <BusinessValue value={withoutSystemVersionFields(note)} />}</li>)}</ul></details> },
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => <details className="source-fields"><summary>查看计算分量</summary><BusinessValue value={withoutSystemVersionFields(value)} /></details> },
];
+5
View File
@@ -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;
+25
View File
@@ -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'));
}
});
});
}
@@ -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>成员清单<\/h2>/);
assert.match(html, /<th>成员<\/th>/);
assert.match(html, /<th>备注<\/th>/);
assert.match(html, /<th style="text-align:left">备注<\/th>/);
assert.match(html, /<th>阶段<\/th>/);
assert.equal((html.match(/<tr/g) || []).length, 182);
assert.match(html, /最后一行成员181/);
+2 -1
View File
@@ -1,3 +1,4 @@
import { tableTextAlignment } from '../src/tableTextAlignment.ts';
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
import test from 'node:test';
import assert from 'node:assert/strict';
@@ -32,7 +33,7 @@ function component(source, name, bindings) {
}).outputText)(React, ...Object.values(bindings));
}
const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8');
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts });
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts, tableTextAlignment });
OriginalContent=component(readFileSync(new URL('../src/AnalysisOriginalContent.tsx',import.meta.url),'utf8'),'AnalysisOriginalContent',{AiMarkdown,originalAnalysisSections});
test('conclusion layout separates the lead, findings and table titles without rewriting checked facts', () => {
@@ -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(/<tr/g) || []).length, 248);
assert.match(html, /数学A · 黑片 · 2026年9月/);
@@ -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';
@@ -157,8 +158,8 @@ test('export from the actual drawer keeps the clicked release even after current
});
function tableFixture(props) {
const code=read('QualityTable.tsx').slice(read('QualityTable.tsx').indexOf('type QualityTableProps')).replace('export function QualityTable','function QualityTable');
const renderer=hookRenderer(hooks=>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};
}
@@ -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);
});