Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions bun-test-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ global.localStorage = win.localStorage as any;
global.addEventListener = win.addEventListener.bind(win) as any;
global.removeEventListener = win.removeEventListener.bind(win) as any;
global.dispatchEvent = win.dispatchEvent.bind(win) as any;
global.getComputedStyle = win.getComputedStyle.bind(win) as any;
global.Element = win.Element as any;
global.HTMLElement = win.HTMLElement as any;
global.SVGElement = win.SVGElement as any;
global.Node = win.Node as any;
global.HTMLInputElement = win.HTMLInputElement as any;
global.StorageEvent = win.StorageEvent as any;

// Mock dependencies that cause side effects or fail on static assets imports
Expand Down Expand Up @@ -69,3 +75,16 @@ mock.module('react-router-dom', () => ({
useLoaderData: () => null,
useActionData: () => null,
}));

if (typeof window.matchMedia !== 'function') {
window.matchMedia = ((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => false,
})) as any;
}
4 changes: 4 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export default defineConfig({
),
},
},
performance: {
chunkSplit: {
strategy: 'split-by-experience',
},
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
plugins: [
pluginReact({
reactCompiler: true,
Expand Down
93 changes: 93 additions & 0 deletions src/components/dangerous-confirm-modal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { ConfigProvider } from 'antd';
import { DangerousConfirmModal } from './dangerous-confirm-modal';

describe('DangerousConfirmModal', () => {
afterEach(() => {
cleanup();
});

test('does not render content when closed', () => {
render(
<ConfigProvider>
<DangerousConfirmModal
open={false}
title="Test Title"
description="Test Desc"
onCancel={() => {}}
onConfirm={() => {}}
/>
</ConfigProvider>,
);
expect(screen.queryByText('Test Title')).toBeNull();
});

test('renders title, warning message and input when open', () => {
render(
<ConfigProvider>
<DangerousConfirmModal
open={true}
title="Test Title"
description="Test Desc"
expectedConfirmText="my-app"
dangerButtonText="Confirm Delete"
onCancel={() => {}}
onConfirm={() => {}}
/>
</ConfigProvider>,
);
expect(screen.getByText('Test Title')).not.toBeNull();
expect(screen.getByText('Test Desc')).not.toBeNull();
expect(screen.getByText('my-app')).not.toBeNull();
});

test('disables confirm button when text does not match', () => {
render(
<ConfigProvider>
<DangerousConfirmModal
open={true}
title="Delete App"
description="Warning"
expectedConfirmText="my-app"
dangerButtonText="Confirm Delete"
onCancel={() => {}}
onConfirm={() => {}}
/>
</ConfigProvider>,
);

const confirmBtn = screen.getByText('Confirm Delete').closest('button');
expect((confirmBtn as HTMLButtonElement).disabled).toBe(true);

const input = screen.getByRole('textbox');
fireEvent.change(input, { target: { value: 'wrong-name' } });
expect((confirmBtn as HTMLButtonElement).disabled).toBe(true);
});

test('enables confirm button and triggers onConfirm when text matches exactly (with whitespace trimming)', () => {
const onConfirmMock = mock(() => {});
render(
<ConfigProvider>
<DangerousConfirmModal
open={true}
title="Delete App"
description="Warning"
expectedConfirmText="my-app"
dangerButtonText="Confirm Delete"
onCancel={() => {}}
onConfirm={onConfirmMock}
/>
</ConfigProvider>,
);

const confirmBtn = screen.getByText('Confirm Delete').closest('button')!;
const input = screen.getByRole('textbox');

fireEvent.change(input, { target: { value: ' my-app ' } });
expect((confirmBtn as HTMLButtonElement).disabled).toBe(false);

fireEvent.click(confirmBtn);
expect(onConfirmMock).toHaveBeenCalledTimes(1);
});
});
113 changes: 113 additions & 0 deletions src/components/dangerous-confirm-modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Alert, Input, Modal, Typography } from 'antd';
import { type ReactNode, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

const { Text } = Typography;

export interface DangerousConfirmModalProps {
open: boolean;
title: string;
description: ReactNode;
expectedConfirmText?: string;
confirmPlaceholder?: string;
dangerButtonText?: string;
cancelButtonText?: string;
loading?: boolean;
onCancel: () => void;
onConfirm: () => void | Promise<void>;
}

/**
* 高危毁灭性操作二次确认 Guard 弹窗组件
* 当配置了 expectedConfirmText 时,用户必须在输入框中手动键入完全匹配的文本方可点击确认。
*/
export function DangerousConfirmModal({
open,
title,
description,
expectedConfirmText,
confirmPlaceholder,
dangerButtonText,
cancelButtonText,
loading = false,
onCancel,
onConfirm,
}: DangerousConfirmModalProps) {
const { t } = useTranslation();
const [inputText, setInputText] = useState('');

// 重置输入状态
useEffect(() => {
if (open) {
setInputText('');
}
}, [open]);

const hasExpectedText =
expectedConfirmText !== undefined && expectedConfirmText !== null;
const isMatched = hasExpectedText
? expectedConfirmText.trim() !== '' &&
inputText.trim() === expectedConfirmText.trim()
: true;

const placeholderText =
confirmPlaceholder ?? t('dangerous_modal.confirm_placeholder');
const okText = dangerButtonText ?? t('dangerous_modal.confirm_button');
const cancelText = cancelButtonText ?? t('dangerous_modal.cancel');

return (
<Modal
open={open}
title={
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
color: '#ff4d4f',
}}
>
<ExclamationCircleFilled style={{ fontSize: 20 }} />
<span>{title}</span>
</div>
}
onCancel={onCancel}
onOk={onConfirm}
okText={okText}
okButtonProps={{
danger: true,
type: 'primary',
disabled: !isMatched,
loading,
}}
cancelText={cancelText}
destroyOnHidden
>
<Alert
type="warning"
showIcon
title={t('dangerous_modal.warning_title')}
description={description}
style={{ marginBottom: 16, marginTop: 12 }}
/>

{expectedConfirmText && (
<div style={{ marginTop: 12 }}>
<p style={{ marginBottom: 8, fontSize: 13 }}>
{t('dangerous_modal.confirm_prompt_prefix')}{' '}
<Text code>{expectedConfirmText}</Text>{' '}
{t('dangerous_modal.confirm_prompt_suffix')}
</p>
<Input
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder={placeholderText}
status={inputText && !isMatched ? 'error' : ''}
autoFocus
/>
</div>
)}
</Modal>
);
}
119 changes: 119 additions & 0 deletions src/components/lazy-chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
type ComponentProps,
type ComponentType,
lazy,
Suspense,
useCallback,
useState,
} from 'react';
import { SectionErrorBoundary } from './section-error-boundary';
import { ChartSkeleton } from './skeletons';

type ChartComponentType = 'Area' | 'Line' | 'Pie' | 'DualAxes';

function createLazyChart<T extends ChartComponentType>(type: T) {
return lazy(() =>
import('@ant-design/charts').then((module) => ({
default: module[type] as ComponentType<any>,
})),
);
}

interface AsyncChartProps<T extends ChartComponentType> {
chartType: T;
errorTitle: string;
height?: number;
chartProps: Record<string, any>;
}

function AsyncChartWrapper<T extends ChartComponentType>({
chartType,
errorTitle,
height,
chartProps,
}: AsyncChartProps<T>) {
const [retryCount, setRetryCount] = useState(0);
const [LazyComponent, setLazyComponent] = useState(() =>
createLazyChart(chartType),
);

const handleReset = useCallback(() => {
setLazyComponent(() => createLazyChart(chartType));
setRetryCount((c) => c + 1);
}, [chartType]);

return (
<SectionErrorBoundary title={errorTitle} onReset={handleReset}>
<Suspense
key={retryCount}
fallback={<ChartSkeleton height={height || 300} />}
>
<LazyComponent {...chartProps} />
</Suspense>
</SectionErrorBoundary>
);
}

export function AsyncArea({
height,
...props
}: ComponentProps<typeof import('@ant-design/charts')['Area']> & {
height?: number;
}) {
return (
<AsyncChartWrapper
chartType="Area"
errorTitle="图表渲染异常"
height={height}
chartProps={{ ...props, height }}
/>
);
}

export function AsyncLine({
height,
...props
}: ComponentProps<typeof import('@ant-design/charts')['Line']> & {
height?: number;
}) {
return (
<AsyncChartWrapper
chartType="Line"
errorTitle="折线图渲染异常"
height={height}
chartProps={{ ...props, height }}
/>
);
}

export function AsyncPie({
height,
...props
}: ComponentProps<typeof import('@ant-design/charts')['Pie']> & {
height?: number;
}) {
return (
<AsyncChartWrapper
chartType="Pie"
errorTitle="饼图渲染异常"
height={height}
chartProps={{ ...props, height }}
/>
);
}

export function AsyncDualAxes({
height,
...props
}: ComponentProps<typeof import('@ant-design/charts')['DualAxes']> & {
height?: number;
}) {
return (
<AsyncChartWrapper
chartType="DualAxes"
errorTitle="双轴图表渲染异常"
height={height}
chartProps={{ ...props, height }}
/>
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Loading