Commit 5befdd6e by 胡悦

feat: 优化表格加载状态,新增方法论默认图标功能,适配环境变量API地址

- 提取默认图标生成工具函数,简化方法论页面代码逻辑
- 为表格组件新增骨架屏加载状态,替换原有的纯文本加载提示,完善表格测试用例
- 将API默认基础地址改为从`VITE_API_BASE_URL`环境变量读取,支持自定义部署配置
- 新增方法论步骤默认图标上传校验、上传中禁用状态与重试逻辑,补充完整相关测试
1 parent 279fc775
...@@ -10,7 +10,7 @@ export interface RequestOptions { ...@@ -10,7 +10,7 @@ export interface RequestOptions {
body?: unknown; body?: unknown;
} }
const DEFAULT_BASE_URL = '/api/v1'; const DEFAULT_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? '/api/v1';
export function createApiClient(options: ApiClientOptions = {}) { export function createApiClient(options: ApiClientOptions = {}) {
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL; const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
......
...@@ -324,6 +324,42 @@ ...@@ -324,6 +324,42 @@
font-weight: 600; font-weight: 600;
} }
.tableLoading {
overflow: hidden;
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-md);
background: var(--gl-color-bg-container);
}
.tableLoading .table {
border: 0;
border-radius: 0;
}
.tableSkeletonLine {
display: block;
width: min(180px, 78%);
height: 14px;
overflow: hidden;
border-radius: 999px;
background: linear-gradient(
90deg,
var(--gl-color-fill-hover) 0%,
color-mix(in srgb, var(--gl-color-primary) 10%, #fff) 50%,
var(--gl-color-fill-hover) 100%
);
background-size: 200% 100%;
animation: tableSkeletonShimmer 1.2s ease-in-out infinite;
}
.tableLoading tr:nth-child(2) .tableSkeletonLine {
width: min(240px, 86%);
}
.tableLoading tr:nth-child(3) .tableSkeletonLine {
width: min(140px, 66%);
}
.tableEmptyCell { .tableEmptyCell {
padding: var(--gl-spacing-xl); padding: var(--gl-spacing-xl);
text-align: center; text-align: center;
...@@ -336,6 +372,16 @@ ...@@ -336,6 +372,16 @@
color: var(--gl-color-text-secondary); color: var(--gl-color-text-secondary);
} }
@keyframes tableSkeletonShimmer {
from {
background-position: 100% 0;
}
to {
background-position: -100% 0;
}
}
.sortButton, .sortButton,
.plainButton { .plainButton {
border: 0; border: 0;
......
...@@ -44,9 +44,38 @@ function renderEmptyState(empty: TableProps<Record<string, unknown>>['empty'], e ...@@ -44,9 +44,38 @@ function renderEmptyState(empty: TableProps<Record<string, unknown>>['empty'], e
return empty ?? <Empty description={emptyText} />; return empty ?? <Empty description={emptyText} />;
} }
function renderLoadingRows(columnCount: number) {
return Array.from({ length: 3 }, (_, rowIndex) => (
<tr key={rowIndex} aria-label="加载占位行">
{Array.from({ length: columnCount }, (_, columnIndex) => (
<td key={columnIndex}>
<span className={styles.tableSkeletonLine} />
</td>
))}
</tr>
));
}
export function Table<T extends Record<string, unknown>>({ columns, dataSource, empty, emptyText = '暂无数据', loading, rowKey, rowSelection, onSort }: TableProps<T>) { export function Table<T extends Record<string, unknown>>({ columns, dataSource, empty, emptyText = '暂无数据', loading, rowKey, rowSelection, onSort }: TableProps<T>) {
const columnCount = columns.length + (rowSelection ? 1 : 0);
if (loading) { if (loading) {
return <div role="status" aria-label="表格加载中" className={styles.panel}>加载中...</div>; return (
<div role="status" aria-label="表格加载中" className={styles.tableLoading}>
<table className={styles.table}>
<thead>
<tr>
{rowSelection ? <th>选择</th> : null}
{columns.map((column) => {
const key = String(column.key ?? column.dataIndex ?? column.title);
return <th key={key} scope="col">{column.title}</th>;
})}
</tr>
</thead>
<tbody>{renderLoadingRows(columnCount)}</tbody>
</table>
</div>
);
} }
return ( return (
...@@ -73,7 +102,7 @@ export function Table<T extends Record<string, unknown>>({ columns, dataSource, ...@@ -73,7 +102,7 @@ export function Table<T extends Record<string, unknown>>({ columns, dataSource,
<tbody> <tbody>
{dataSource.length === 0 ? ( {dataSource.length === 0 ? (
<tr> <tr>
<td className={styles.tableEmptyCell} colSpan={columns.length + (rowSelection ? 1 : 0)}> <td className={styles.tableEmptyCell} colSpan={columnCount}>
<div role="status" aria-label="表格空状态" className={styles.tableEmpty}> <div role="status" aria-label="表格空状态" className={styles.tableEmpty}>
{renderEmptyState(empty, emptyText)} {renderEmptyState(empty, emptyText)}
</div> </div>
......
...@@ -608,6 +608,9 @@ describe('selection, date, table and pagination components', () => { ...@@ -608,6 +608,9 @@ describe('selection, date, table and pagination components', () => {
it('renders table loading and empty states', () => { it('renders table loading and empty states', () => {
const { rerender } = render(<Table rowKey="id" loading columns={[{ title: '名称', dataIndex: 'name' }]} dataSource={[]} />); const { rerender } = render(<Table rowKey="id" loading columns={[{ title: '名称', dataIndex: 'name' }]} dataSource={[]} />);
expect(screen.getByRole('status', { name: '表格加载中' })).toBeInTheDocument(); expect(screen.getByRole('status', { name: '表格加载中' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: '名称' })).toBeInTheDocument();
expect(screen.getAllByLabelText('加载占位行')).toHaveLength(3);
expect(screen.queryByText('加载中...')).not.toBeInTheDocument();
rerender(<Table rowKey="id" columns={[{ title: '名称', dataIndex: 'name' }]} dataSource={[]} />); rerender(<Table rowKey="id" columns={[{ title: '名称', dataIndex: 'name' }]} dataSource={[]} />);
expect(screen.getByText('暂无数据')).toBeInTheDocument(); expect(screen.getByText('暂无数据')).toBeInTheDocument();
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
type MethodologyStatus, type MethodologyStatus,
type MethodologyStep as ApiMethodologyStep, type MethodologyStep as ApiMethodologyStep,
} from '../../api/methodology'; } from '../../api/methodology';
import { buildDefaultIconDataUrl, generateDefaultIconPngFile } from '../../utils/defaultIcon';
interface MethodologyStepFormState { interface MethodologyStepFormState {
step_id: string; step_id: string;
...@@ -70,16 +71,6 @@ function createEmptyStep(nextOrder: number): MethodologyStepFormState { ...@@ -70,16 +71,6 @@ function createEmptyStep(nextOrder: number): MethodologyStepFormState {
}; };
} }
function buildDefaultIcon(stepOrder: number) {
const svgContent = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><circle cx="24" cy="24" r="22" fill="%232B6CB0"/><text x="24" y="30" text-anchor="middle" fill="white" font-size="18" font-weight="bold" font-family="system-ui">${stepOrder}</text></svg>`;
const dataUrl = `data:image/svg+xml,${encodeURIComponent(svgContent)}`;
return {
id: `default-icon-${stepOrder}`,
name: `默认图标(步骤${stepOrder})`,
url: dataUrl,
};
}
export function OfficialSiteMethodologyPage() { export function OfficialSiteMethodologyPage() {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [form, setForm] = useState<MethodologyFormState | null>(null); const [form, setForm] = useState<MethodologyFormState | null>(null);
...@@ -89,6 +80,8 @@ export function OfficialSiteMethodologyPage() { ...@@ -89,6 +80,8 @@ export function OfficialSiteMethodologyPage() {
const [mainTitleError, setMainTitleError] = useState<string>(); const [mainTitleError, setMainTitleError] = useState<string>();
const [subTitleError, setSubTitleError] = useState<string>(); const [subTitleError, setSubTitleError] = useState<string>();
const [stepListError, setStepListError] = useState<string>(); const [stepListError, setStepListError] = useState<string>();
const [defaultIconUploading, setDefaultIconUploading] = useState<Set<string>>(new Set());
const [defaultIconUploadError, setDefaultIconUploadError] = useState<Map<string, string>>(new Map());
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
...@@ -155,9 +148,20 @@ export function OfficialSiteMethodologyPage() { ...@@ -155,9 +148,20 @@ export function OfficialSiteMethodologyPage() {
let nameError: string | undefined; let nameError: string | undefined;
let imageError: string | undefined; let imageError: string | undefined;
if (!step.step_icon) { // 检查默认图标上传状态
if (defaultIconUploading.has(step.step_id)) {
iconError = '请等待默认图标上传完成';
valid = false;
} else if (defaultIconUploadError.has(step.step_id)) {
iconError = '请上传步骤图标或等待默认图标上传完成';
valid = false;
} else if (!step.step_icon) {
iconError = '请配置步骤图标'; iconError = '请配置步骤图标';
valid = false; valid = false;
} else if (step.step_icon.url.startsWith('data:')) {
// data: URL 表示是本地预览而非真实上传
iconError = '请上传步骤图标或等待默认图标上传完成';
valid = false;
} }
if (!step.step_name.trim()) { if (!step.step_name.trim()) {
...@@ -468,12 +472,66 @@ export function OfficialSiteMethodologyPage() { ...@@ -468,12 +472,66 @@ export function OfficialSiteMethodologyPage() {
size="small" size="small"
variant="outline" variant="outline"
aria-label={`使用默认图标 步骤 ${index + 1}`} aria-label={`使用默认图标 步骤 ${index + 1}`}
onClick={() => { disabled={defaultIconUploading.has(step.step_id)}
onClick={async () => {
const stepId = step.step_id;
const stepOrder = step.step_order;
// 设置上传中状态
setDefaultIconUploading((prev) => new Set(prev).add(stepId));
setDefaultIconUploadError((prev) => {
const next = new Map(prev);
next.delete(stepId);
return next;
});
// 先显示临时预览(data URL)
updateStep(index, (currentStep) => ({ updateStep(index, (currentStep) => ({
...currentStep, ...currentStep,
step_icon: buildDefaultIcon(currentStep.step_order), step_icon: {
id: `default-icon-${stepOrder}`,
name: `默认图标(步骤${stepOrder})`,
url: buildDefaultIconDataUrl(stepOrder),
},
iconError: undefined, iconError: undefined,
})); }));
try {
// 生成 PNG File
const pngFile = await generateDefaultIconPngFile(stepOrder);
// 上传
const formData = new FormData();
formData.append('file', pngFile);
formData.append('usage_type', 'methodology_icon');
const result = await uploadMethodologyAsset(formData);
// 更新为真实 URL
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: {
id: result.file_id,
name: pngFile.name,
url: result.file_url,
},
iconError: undefined,
}));
} catch {
// 上传失败
setDefaultIconUploadError((prev) => {
const next = new Map(prev);
next.set(stepId, '默认图标上传失败');
return next;
});
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: undefined,
iconError: '默认图标上传失败',
}));
}
// 清除上传中状态
setDefaultIconUploading((prev) => {
const next = new Set(prev);
next.delete(stepId);
return next;
});
}} }}
> >
使用默认图标 使用默认图标
......
...@@ -3,6 +3,7 @@ import { MemoryRouter } from 'react-router-dom'; ...@@ -3,6 +3,7 @@ import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getMethodologyConfig, saveMethodologyConfig, uploadMethodologyAsset } from '../../api/methodology'; import { getMethodologyConfig, saveMethodologyConfig, uploadMethodologyAsset } from '../../api/methodology';
import { generateDefaultIconPngFile } from '../../utils/defaultIcon';
import { App } from '../../App'; import { App } from '../../App';
vi.mock('../../api/methodology', () => ({ vi.mock('../../api/methodology', () => ({
...@@ -11,6 +12,11 @@ vi.mock('../../api/methodology', () => ({ ...@@ -11,6 +12,11 @@ vi.mock('../../api/methodology', () => ({
uploadMethodologyAsset: vi.fn(), uploadMethodologyAsset: vi.fn(),
})); }));
vi.mock('../../utils/defaultIcon', () => ({
buildDefaultIconDataUrl: (stepOrder: number) => `data:image/svg+xml,default-icon-${stepOrder}`,
generateDefaultIconPngFile: vi.fn(),
}));
const mockMethodologyConfig = { const mockMethodologyConfig = {
config_id: 'methodology_001', config_id: 'methodology_001',
display_status: 'enable' as const, display_status: 'enable' as const,
...@@ -76,6 +82,7 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => { ...@@ -76,6 +82,7 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
file_type: 'png', file_type: 'png',
file_size: 500000, file_size: 500000,
}); });
vi.mocked(generateDefaultIconPngFile).mockResolvedValue(new File(['png content'], 'step-1-default-icon.png', { type: 'image/png' }));
}); });
it('renders a recoverable load error state', async () => { it('renders a recoverable load error state', async () => {
...@@ -425,4 +432,187 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => { ...@@ -425,4 +432,187 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
}); });
}); });
}); });
describe('使用默认图标', () => {
it('点击「使用默认图标」后应生成 PNG 文件并上传,使用返回 URL 作为 step_icon', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// 先删除已有步骤图标
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 1) {
clickDeleteIcon(uploadContainers[0] as HTMLElement);
}
// 模拟默认图标上传成功
vi.mocked(uploadMethodologyAsset).mockResolvedValueOnce({
file_id: 'file_default_icon_1',
file_url: 'https://cdn.example.com/default-icon-1.png',
file_type: 'png',
file_size: 5000,
});
// 点击「使用默认图标」按钮
const defaultIconButton = within(firstCard).getByRole('button', { name: '使用默认图标 步骤 1' });
fireEvent.click(defaultIconButton);
await waitFor(() => {
expect(uploadMethodologyAsset).toHaveBeenCalled();
const formDataArg = vi.mocked(uploadMethodologyAsset).mock.calls[0][0] as FormData;
expect(formDataArg.get('usage_type')).toBe('methodology_icon');
expect(formDataArg.get('file')).not.toBeNull();
const file = formDataArg.get('file') as File;
expect(file.type).toBe('image/png');
expect(file.name).toMatch(/step-\d+-default-icon\.png/);
});
// 验证预览使用上传返回的 URL,而非 data: URL
await waitFor(() => {
const images = within(firstCard).getAllByRole('img');
const defaultIconImg = images.find(img => img.getAttribute('src') === 'https://cdn.example.com/default-icon-1.png');
expect(defaultIconImg).toBeInTheDocument();
});
// 保存时 step_icon 应为上传返回的 URL
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
await waitFor(() => {
expect(saveMethodologyConfig).toHaveBeenCalled();
const savePayload = vi.mocked(saveMethodologyConfig).mock.calls[0][0];
expect(savePayload.steps[0].step_icon).toBe('https://cdn.example.com/default-icon-1.png');
// 不应为 data: URL
expect(savePayload.steps[0].step_icon).not.toMatch(/^data:/);
});
});
it('保存时校验 step_icon 必须是真实 URL,不能是 data: URL 或 SVG 内容', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
// 模拟默认图标上传失败,此时 step_icon 可能仍为 data: URL
vi.mocked(uploadMethodologyAsset).mockRejectedValueOnce(new Error('Upload failed'));
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// 删除已有步骤图标
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 1) {
clickDeleteIcon(uploadContainers[0] as HTMLElement);
}
const defaultIconButton = within(firstCard).getByRole('button', { name: '使用默认图标 步骤 1' });
fireEvent.click(defaultIconButton);
// 等待上传失败
await waitFor(() => {
expect(within(firstCard).getByText('默认图标上传失败')).toBeInTheDocument();
});
// 此时预览可能仍显示 data: URL,但保存应被阻止
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
await waitFor(() => {
// 应显示校验错误
expect(within(firstCard).getByText('请上传步骤图标或等待默认图标上传完成')).toBeInTheDocument();
});
// saveMethodologyConfig 不应被调用
expect(saveMethodologyConfig).not.toHaveBeenCalled();
});
it('默认图标上传失败时展示错误反馈,允许重试', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// 删除已有步骤图标
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 1) {
clickDeleteIcon(uploadContainers[0] as HTMLElement);
}
// 模拟上传失败
vi.mocked(uploadMethodologyAsset).mockRejectedValueOnce(new Error('Upload failed'));
const defaultIconButton = within(firstCard).getByRole('button', { name: '使用默认图标 步骤 1' });
fireEvent.click(defaultIconButton);
await waitFor(() => {
expect(within(firstCard).getByText('默认图标上传失败')).toBeInTheDocument();
});
// 模拟重试成功
vi.mocked(uploadMethodologyAsset).mockResolvedValueOnce({
file_id: 'file_default_icon_retry',
file_url: 'https://cdn.example.com/default-icon-retry.png',
file_type: 'png',
file_size: 5000,
});
// 再次点击「使用默认图标」重试
fireEvent.click(defaultIconButton);
await waitFor(() => {
const images = within(firstCard).getAllByRole('img');
const retryIconImg = images.find(img => img.getAttribute('src') === 'https://cdn.example.com/default-icon-retry.png');
expect(retryIconImg).toBeInTheDocument();
});
// 错误提示消失
expect(within(firstCard).queryByText('默认图标上传失败')).not.toBeInTheDocument();
});
it('默认图标上传中禁用重复提交', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// 删除已有步骤图标
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 1) {
clickDeleteIcon(uploadContainers[0] as HTMLElement);
}
// 模拟上传延迟
vi.mocked(uploadMethodologyAsset).mockImplementationOnce(() => new Promise(resolve => setTimeout(() => resolve({
file_id: 'file_default_icon_delayed',
file_url: 'https://cdn.example.com/default-icon-delayed.png',
file_type: 'png',
file_size: 5000,
}), 1000)));
const defaultIconButton = within(firstCard).getByRole('button', { name: '使用默认图标 步骤 1' });
fireEvent.click(defaultIconButton);
// 等待上传开始
await waitFor(() => {
expect(uploadMethodologyAsset).toHaveBeenCalledTimes(1);
});
// 上传中按钮应禁用
expect(defaultIconButton).toBeDisabled();
// 等待上传完成
await waitFor(() => {
const images = within(firstCard).getAllByRole('img');
const delayedIconImg = images.find(img => img.getAttribute('src') === 'https://cdn.example.com/default-icon-delayed.png');
expect(delayedIconImg).toBeInTheDocument();
});
// 上传完成后按钮恢复可用
expect(defaultIconButton).not.toBeDisabled();
});
});
}); });
\ No newline at end of file \ No newline at end of file
/**
* 生成默认方法论步骤图标 PNG 文件
*/
export function buildDefaultIconSvg(stepOrder: number): string {
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><circle cx="24" cy="24" r="22" fill="%232B6CB0"/><text x="24" y="30" text-anchor="middle" fill="white" font-size="18" font-weight="bold" font-family="system-ui">${stepOrder}</text></svg>`;
}
export function buildDefaultIconDataUrl(stepOrder: number): string {
const svgContent = buildDefaultIconSvg(stepOrder);
return `data:image/svg+xml,${encodeURIComponent(svgContent)}`;
}
export async function generateDefaultIconPngFile(stepOrder: number): Promise<File> {
const svgContent = buildDefaultIconSvg(stepOrder);
const svgDataUrl = `data:image/svg+xml,${encodeURIComponent(svgContent)}`;
const img = new Image();
img.src = svgDataUrl;
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error('Failed to load SVG image'));
});
const canvas = document.createElement('canvas');
canvas.width = 48;
canvas.height = 48;
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Canvas context not available');
}
ctx.drawImage(img, 0, 0, 48, 48);
const blob = await new Promise<Blob>((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('Failed to convert canvas to PNG blob'));
}
}, 'image/png');
});
return new File([blob], `step-${stepOrder}-default-icon.png`, { type: 'image/png' });
}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!