i更新
This commit is contained in:
@@ -16,7 +16,7 @@
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm vite build --mode production",
|
||||
"build": "pnpm vite build --mode production && node ../../scripts/verify-token-build.mjs dist",
|
||||
"build:analyze": "pnpm vite build --mode analyze",
|
||||
"dev": "pnpm vite --mode development",
|
||||
"preview": "vite preview",
|
||||
@@ -43,6 +43,7 @@
|
||||
"@vueuse/core": "catalog:",
|
||||
"ant-design-vue": "catalog:",
|
||||
"dayjs": "catalog:",
|
||||
"hash-wasm": "4.12.0",
|
||||
"pinia": "catalog:",
|
||||
"vue": "catalog:",
|
||||
"vue-router": "catalog:"
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface ArchiveMessage {
|
||||
attachments: ArchiveAttachment[];
|
||||
content: string;
|
||||
direction: string;
|
||||
message_origin?: 'ai' | 'human' | 'system' | 'unknown' | 'customer';
|
||||
id: string;
|
||||
message_type: string;
|
||||
sender_name: string;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* 前端隐藏按钮只是体验,后端不拦就等于没有权限系统。
|
||||
*/
|
||||
import { requestClient } from '#/api/request';
|
||||
import { sha256File } from '#/utils/file-sha256';
|
||||
|
||||
/**
|
||||
* 账号下拉框里「全部」的取值,和后端 `admin_api.ALL_ACCOUNTS` 是同一个约定。
|
||||
@@ -317,9 +318,10 @@ export function updateDesktopAccountAdmins(id: number, adminUserIds: number[]) {
|
||||
}
|
||||
|
||||
// ── 运营 ─────────────────────────────────────────────────────────────────────
|
||||
export function fetchCallStats(days = 7, accountId = 0) {
|
||||
export function fetchCallStats(days = 7, accountId = 0, signal?: AbortSignal) {
|
||||
return requestClient.get<CallStats>(
|
||||
`/stats/model-calls?days=${days}&account_id=${accountId}`,
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -331,7 +333,7 @@ export function fetchCallLog(params: {
|
||||
/** chat = 回客户的话(默认);guard = 界面识别;'' = 全都要 */
|
||||
purpose?: string;
|
||||
q?: string;
|
||||
}) {
|
||||
}, signal?: AbortSignal) {
|
||||
const query = new URLSearchParams();
|
||||
query.set('days', String(params.days ?? 7));
|
||||
query.set('account_id', String(params.accountId ?? 0));
|
||||
@@ -341,6 +343,7 @@ export function fetchCallLog(params: {
|
||||
if (params.q) query.set('q', params.q);
|
||||
return requestClient.get<{ items: ModelCallLogItem[]; total: number }>(
|
||||
`/stats/model-calls/log?${query.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -433,6 +436,7 @@ export function saveConfig(data: DesktopConfig) {
|
||||
|
||||
// ── 桌面端版本升级 ───────────────────────────────────────────────────────────
|
||||
export interface ReleasePolicy {
|
||||
package_media_id?: string;
|
||||
auto_install: boolean;
|
||||
download_url: string;
|
||||
force_upgrade: boolean;
|
||||
@@ -449,6 +453,8 @@ export interface ReleasePolicy {
|
||||
}
|
||||
|
||||
export interface ReleasePackage {
|
||||
package_media_id: string;
|
||||
download_url_expires_in: number;
|
||||
download_url: string;
|
||||
file_name: string;
|
||||
package_sha256: string;
|
||||
@@ -493,6 +499,7 @@ export function fetchRelease() {
|
||||
}
|
||||
|
||||
export function saveRelease(data: {
|
||||
package_media_id?: string;
|
||||
auto_install: boolean;
|
||||
download_url: string;
|
||||
force_upgrade: boolean;
|
||||
@@ -508,19 +515,6 @@ export function saveRelease(data: {
|
||||
return requestClient.post<ReleasePolicy>('/release', data);
|
||||
}
|
||||
|
||||
async function sha256File(file: File) {
|
||||
if (!globalThis.crypto?.subtle) {
|
||||
throw new Error('当前浏览器不支持安全哈希,请使用 HTTPS 或本机地址打开管理端');
|
||||
}
|
||||
const digest = await globalThis.crypto.subtle.digest(
|
||||
'SHA-256',
|
||||
await file.arrayBuffer(),
|
||||
);
|
||||
return [...new Uint8Array(digest)]
|
||||
.map((value) => value.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
function putCosBlob(
|
||||
url: string,
|
||||
body: Blob,
|
||||
@@ -632,7 +626,9 @@ export async function uploadReleasePackage(
|
||||
throw new Error('安装包大小必须大于 0 且不能超过 1GB');
|
||||
}
|
||||
onProgress?.(1);
|
||||
const packageSha256 = await sha256File(file);
|
||||
const packageSha256 = await sha256File(file, (fraction) => {
|
||||
onProgress?.(1 + Math.floor(fraction * 4));
|
||||
});
|
||||
onProgress?.(5);
|
||||
const prepared = await requestClient.post<ReleaseUploadPrepared>(
|
||||
'/release/package/prepare',
|
||||
@@ -707,3 +703,85 @@ export function testModel(data: {
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export interface ModelUsageSummary {
|
||||
request_count: number;
|
||||
known_count: number;
|
||||
missing_count: number;
|
||||
input_tokens: number | null;
|
||||
output_tokens: number | null;
|
||||
total_tokens: number | null;
|
||||
cached_input_tokens: number | null;
|
||||
reasoning_tokens: number | null;
|
||||
input_known_count?: number;
|
||||
output_known_count?: number;
|
||||
cached_input_known_count?: number;
|
||||
reasoning_known_count?: number;
|
||||
}
|
||||
|
||||
export interface ModelUsageStats {
|
||||
days: number;
|
||||
since: string;
|
||||
timezone: string;
|
||||
summary: ModelUsageSummary;
|
||||
by_model: (ModelUsageSummary & { provider_id: string; provider_name: string; model: string })[];
|
||||
by_purpose: (ModelUsageSummary & { purpose: string })[];
|
||||
daily: (ModelUsageSummary & { date: string })[];
|
||||
legacy_unmetered_calls: number;
|
||||
}
|
||||
|
||||
export interface ModelUsageLogItem {
|
||||
event_id: string;
|
||||
request_id: string;
|
||||
task_id: string;
|
||||
tenant_id: string;
|
||||
desktop_account_id: number | null;
|
||||
provider_id: string;
|
||||
provider_name: string;
|
||||
model: string;
|
||||
kind: string;
|
||||
purpose: string;
|
||||
role: string;
|
||||
attempt: number;
|
||||
status: string;
|
||||
input_tokens: number | null;
|
||||
output_tokens: number | null;
|
||||
total_tokens: number | null;
|
||||
cached_input_tokens: number | null;
|
||||
reasoning_tokens: number | null;
|
||||
latency_ms: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ModelUsageLog {
|
||||
total: number;
|
||||
items: ModelUsageLogItem[];
|
||||
}
|
||||
|
||||
export interface ModelUsageQuery {
|
||||
days?: number;
|
||||
accountId?: number;
|
||||
purpose?: string;
|
||||
providerId?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
function modelUsageQuery(params: ModelUsageQuery) {
|
||||
const query = new URLSearchParams();
|
||||
query.set('days', String(params.days ?? 7));
|
||||
query.set('account_id', String(params.accountId ?? ALL_ACCOUNTS));
|
||||
query.set('purpose', params.purpose ?? '');
|
||||
if (params.providerId) query.set('provider_id', params.providerId);
|
||||
if (params.limit !== undefined) query.set('limit', String(params.limit));
|
||||
if (params.offset !== undefined) query.set('offset', String(params.offset));
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
export function fetchModelUsage(params: ModelUsageQuery = {}, signal?: AbortSignal) {
|
||||
return requestClient.get<ModelUsageStats>(`/stats/model-usage?${modelUsageQuery(params)}`, { signal });
|
||||
}
|
||||
|
||||
export function fetchModelUsageLog(params: ModelUsageQuery = {}, signal?: AbortSignal) {
|
||||
return requestClient.get<ModelUsageLog>(`/stats/model-usage/log?${modelUsageQuery(params)}`, { signal });
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { requestErrorMessage, responseErrorMessage } from './error-message';
|
||||
|
||||
describe('API error messages', () => {
|
||||
it('formats FastAPI query validation arrays as readable text without request input', () => {
|
||||
const data = { detail: [{ type: 'string_too_short', loc: ['body', 'query'], msg: 'String should have at least 2 characters', input: 'PRIVATE', ctx: { min_length: 2 } }] };
|
||||
expect(responseErrorMessage(data)).toBe('检索问题至少需要 2 个字符');
|
||||
expect(requestErrorMessage({ response: { data } })).toBe('检索问题至少需要 2 个字符');
|
||||
});
|
||||
it('handles response bodies unwrapped by RequestClient', () => {
|
||||
expect(requestErrorMessage({ detail: [{ type: 'string_too_short', loc: ['body', 'query'], ctx: { min_length: 2 } }] })).toBe('检索问题至少需要 2 个字符');
|
||||
expect(requestErrorMessage({ detail: '知识索引暂不可用' })).toBe('知识索引暂不可用');
|
||||
});
|
||||
it('handles maximum length and missing or wrong-type input', () => {
|
||||
expect(responseErrorMessage({ detail: [{ type: 'string_too_long', loc: ['body', 'query'], ctx: { max_length: 2000 } }] })).toBe('检索问题不能超过 2000 个字符');
|
||||
expect(responseErrorMessage({ detail: [{ type: 'missing', loc: ['body', 'query'] }] })).toBe('请填写检索问题');
|
||||
expect(responseErrorMessage({ detail: [{ type: 'string_type', loc: ['body', 'query'] }] })).toBe('检索问题必须是文本');
|
||||
});
|
||||
it('preserves existing business errors and supports nested structured messages', () => {
|
||||
expect(responseErrorMessage({ detail: '请先选择具体账号' })).toBe('请先选择具体账号');
|
||||
expect(responseErrorMessage({ error: { message: '服务暂不可用' } })).toBe('服务暂不可用');
|
||||
expect(responseErrorMessage({ message: '没有操作权限' })).toBe('没有操作权限');
|
||||
});
|
||||
it('uses safe fallback for unknown objects, empty payload and network failures', () => {
|
||||
for (const value of [null, undefined, {}, { detail: { input: 'PRIVATE' } }, { detail: [] }]) {
|
||||
expect(responseErrorMessage(value, '请重试')).toBe('请重试');
|
||||
}
|
||||
expect(requestErrorMessage(new Error('network'), '网络异常')).toBe('网络异常');
|
||||
});
|
||||
it('does not stringify recursive or unknown objects', () => {
|
||||
const circular: Record<string, unknown> = {}; circular.detail = circular;
|
||||
expect(responseErrorMessage(circular)).toBe('请求失败,请稍后重试');
|
||||
expect(responseErrorMessage({ detail: [{ type: 'custom_error', loc: ['body', 'title'], msg: '值无效', input: 'PRIVATE' }] })).toBe('请求参数:值无效');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createSHA256 } from 'hash-wasm';
|
||||
|
||||
const HASH_CHUNK_SIZE = 4 * 1024 * 1024;
|
||||
|
||||
/** Hash files in bounded chunks, including on HTTP pages without Web Crypto. */
|
||||
export async function sha256File(
|
||||
file: Blob,
|
||||
onProgress?: (fraction: number) => void,
|
||||
): Promise<string> {
|
||||
const hasher = await createSHA256();
|
||||
hasher.init();
|
||||
onProgress?.(0);
|
||||
|
||||
for (let offset = 0; offset < file.size; offset += HASH_CHUNK_SIZE) {
|
||||
const end = Math.min(offset + HASH_CHUNK_SIZE, file.size);
|
||||
const chunk = await file.slice(offset, end).arrayBuffer();
|
||||
hasher.update(new Uint8Array(chunk));
|
||||
onProgress?.(end / file.size);
|
||||
// Let the progress indicator repaint between chunks of a large installer.
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
onProgress?.(1);
|
||||
return hasher.digest('hex');
|
||||
}
|
||||
@@ -150,6 +150,11 @@ async function loadMessages(targetPage = 0) {
|
||||
);
|
||||
}
|
||||
|
||||
const ORIGIN_LABEL: Record<string, string> = {
|
||||
ai: 'AI 发送', human: '人工发送', system: '系统发送', unknown: '来源未知', customer: '客户发送',
|
||||
};
|
||||
const ORIGIN_COLOR: Record<string, string> = { ai: 'purple', human: 'blue', system: 'cyan', customer: 'green' };
|
||||
|
||||
const TYPE_LABEL: Record<string, string> = {
|
||||
application: '应用会话',
|
||||
direct_wechat: '微信单聊',
|
||||
@@ -225,6 +230,7 @@ const TYPE_LABEL: Record<string, string> = {
|
||||
<div class="mb-1 flex items-center justify-between text-xs text-gray-400">
|
||||
<span>
|
||||
<strong class="mr-2 text-gray-600">{{ item.sender_name || '未知发送者' }}</strong>
|
||||
<Tag :color="ORIGIN_COLOR[item.message_origin || 'unknown']">{{ ORIGIN_LABEL[item.message_origin || (item.direction === 'inbound' ? 'customer' : 'unknown')] || '来源未知' }}</Tag>
|
||||
{{ item.message_type }}
|
||||
<Tag v-if="item.attachment_count" class="ml-2">{{ item.attachment_count }} 个素材</Tag>
|
||||
</span>
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useArchiveLoad } from './use-archive-load';
|
||||
|
||||
function mountRequest() {
|
||||
let request!: ReturnType<typeof useArchiveLoad>;
|
||||
const app = createApp(defineComponent({
|
||||
setup() { request = useArchiveLoad(); return () => h('div'); },
|
||||
}));
|
||||
app.mount(document.createElement('div'));
|
||||
return { app, request };
|
||||
}
|
||||
|
||||
describe('archive request lifecycle', () => {
|
||||
it('cancels the old account and ignores responses arriving out of order', async () => {
|
||||
const { app, request } = mountRequest();
|
||||
let resolveOld!: (value: string) => void;
|
||||
let oldSignal!: AbortSignal;
|
||||
const displayed: string[] = [];
|
||||
const old = request.run((signal) => {
|
||||
oldSignal = signal;
|
||||
return new Promise<string>((resolve) => { resolveOld = resolve; });
|
||||
}, (data) => displayed.push(data));
|
||||
await request.run(async () => 'new account', (data) => displayed.push(data));
|
||||
expect(oldSignal.aborted).toBe(true);
|
||||
resolveOld('old account');
|
||||
await old;
|
||||
expect(displayed).toEqual(['new account']);
|
||||
expect(request.loading.value).toBe(false);
|
||||
app.unmount();
|
||||
});
|
||||
|
||||
it('keeps the spinner for the current request when a canceled request finishes', async () => {
|
||||
const { app, request } = mountRequest();
|
||||
let oldDone!: () => void;
|
||||
let newDone!: () => void;
|
||||
const apply = vi.fn();
|
||||
const old = request.run(() => new Promise<void>((resolve) => { oldDone = resolve; }), apply);
|
||||
const current = request.run(() => new Promise<void>((resolve) => { newDone = resolve; }), apply);
|
||||
oldDone(); await old;
|
||||
expect(request.loading.value).toBe(true);
|
||||
newDone(); await current;
|
||||
expect(request.loading.value).toBe(false);
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
app.unmount();
|
||||
});
|
||||
|
||||
it('aborts network work and blocks state updates after leaving the page', async () => {
|
||||
const { app, request } = mountRequest();
|
||||
let signal!: AbortSignal;
|
||||
let done!: (value: number) => void;
|
||||
const apply = vi.fn();
|
||||
const pending = request.run((value) => {
|
||||
signal = value;
|
||||
return new Promise<number>((resolve) => { done = resolve; });
|
||||
}, apply);
|
||||
app.unmount();
|
||||
await nextTick();
|
||||
expect(signal.aborted).toBe(true);
|
||||
done(1); await pending;
|
||||
expect(apply).not.toHaveBeenCalled();
|
||||
expect(request.loading.value).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { createApp, h, nextTick, reactive } from 'vue';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { fetchModelUsage, fetchModelUsageLog } = vi.hoisted(() => ({
|
||||
fetchModelUsage: vi.fn(), fetchModelUsageLog: vi.fn(),
|
||||
}));
|
||||
vi.mock('#/api/console', () => ({ fetchModelUsage, fetchModelUsageLog }));
|
||||
|
||||
import ModelUsageStats from './ModelUsageStats.vue';
|
||||
|
||||
const totals = { request_count: 2, known_count: 1, missing_count: 1, input_tokens: 10,
|
||||
output_tokens: 5, total_tokens: 15, cached_input_tokens: null, reasoning_tokens: null,
|
||||
input_known_count: 1, output_known_count: 1 };
|
||||
const result = { days: 7, since: '2026-09-11T00:00:00Z', timezone: 'UTC', summary: totals,
|
||||
by_model: [{ ...totals, provider_id: 'p', provider_name: '测试服务商', model: 'test-model' }],
|
||||
by_purpose: [{ ...totals, purpose: 'chat' }], daily: [{ ...totals, date: '2026-09-17' }],
|
||||
legacy_unmetered_calls: 3 };
|
||||
|
||||
let cleanup: (() => void) | undefined;
|
||||
async function settle() {
|
||||
await Promise.resolve(); await Promise.resolve(); await nextTick();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
function mount() {
|
||||
const props = reactive({ accountId: -1, days: 7 });
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const app = createApp({ render: () => h(ModelUsageStats, props) });
|
||||
app.mount(host);
|
||||
cleanup = () => { app.unmount(); host.remove(); };
|
||||
return { props, host };
|
||||
}
|
||||
|
||||
describe('model usage panel', () => {
|
||||
beforeEach(() => {
|
||||
fetchModelUsage.mockReset().mockResolvedValue(result);
|
||||
fetchModelUsageLog.mockReset().mockResolvedValue({ total: 80, items: [{
|
||||
event_id: 'e1', request_id: 'r1', task_id: 't1', tenant_id: 'tenant', desktop_account_id: 1,
|
||||
provider_id: 'p', provider_name: '测试服务商', model: 'test-model', kind: 'chat', purpose: 'chat',
|
||||
role: 'judge', attempt: 1, status: 'success', input_tokens: null, output_tokens: 0,
|
||||
total_tokens: null, cached_input_tokens: null, reasoning_tokens: null, latency_ms: 500,
|
||||
created_at: '2026-09-17T17:30:00+00:00',
|
||||
}] });
|
||||
});
|
||||
afterEach(() => { cleanup?.(); cleanup = undefined; });
|
||||
|
||||
it('starts with all purposes and renders coverage, history and actual requests', async () => {
|
||||
const { host } = mount(); await settle();
|
||||
expect(fetchModelUsage.mock.calls[0]![0]).toEqual({ accountId: -1, days: 7, purpose: '' });
|
||||
expect(host.textContent).toContain('已记录总 Token');
|
||||
expect(host.textContent).toContain('3 次历史业务调用未记录 Token');
|
||||
expect(host.textContent).toContain('每日趋势(UTC)');
|
||||
expect(host.textContent).toContain('未返回');
|
||||
expect(host.textContent).toContain('裁判');
|
||||
expect(host.textContent).toContain('r1');
|
||||
});
|
||||
|
||||
it('paginates actual requests and resets the page when account changes', async () => {
|
||||
const { host, props } = mount(); await settle();
|
||||
const next = host.querySelector<HTMLElement>('.ant-pagination-next');
|
||||
expect(next).not.toBeNull(); next!.click(); await settle();
|
||||
expect(fetchModelUsageLog.mock.lastCall![0].offset).toBe(20);
|
||||
props.accountId = 12; await settle();
|
||||
expect(fetchModelUsageLog.mock.lastCall![0]).toMatchObject({ accountId: 12, offset: 0, purpose: '' });
|
||||
expect(fetchModelUsage.mock.lastCall![0].accountId).toBe(12);
|
||||
});
|
||||
|
||||
it('changes the usage purpose without relying on the customer reply log filter', async () => {
|
||||
const { host } = mount(); await settle();
|
||||
const option = [...host.querySelectorAll<HTMLElement>('.ant-segmented-item')]
|
||||
.find((node) => node.textContent === '知识整理');
|
||||
expect(option).toBeDefined(); option!.click(); await settle();
|
||||
expect(fetchModelUsage.mock.lastCall![0].purpose).toBe('knowledge');
|
||||
expect(fetchModelUsageLog.mock.lastCall![0]).toMatchObject({ purpose: 'knowledge', offset: 0 });
|
||||
});
|
||||
|
||||
it('shows request errors rather than an apparent zero-token success', async () => {
|
||||
fetchModelUsage.mockRejectedValue({ detail: '统计服务暂时不可用' });
|
||||
fetchModelUsageLog.mockRejectedValue({ detail: '明细暂时不可用' });
|
||||
const { host } = mount(); await settle();
|
||||
expect(host.textContent).toContain('统计服务暂时不可用');
|
||||
expect(host.textContent).toContain('明细暂时不可用');
|
||||
expect(host.textContent).not.toContain('总 Token 用量覆盖');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
<script setup lang="ts">
|
||||
import type { ModelUsageLog, ModelUsageStats } from '#/api/console';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { Alert, Button, Card, Col, Empty, Progress, Row, Segmented, Statistic, Table, Tag } from 'ant-design-vue';
|
||||
|
||||
import { fetchModelUsage, fetchModelUsageLog } from '#/api/console';
|
||||
|
||||
import { usageNumber, usagePurpose, usageTokens, usageUtcTime } from './model-usage-format';
|
||||
import { useUsageRequest } from './use-usage-request';
|
||||
|
||||
const props = defineProps<{ accountId: number; days: number }>();
|
||||
const purpose = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const { data: stats, loading, error, run: runStats } = useUsageRequest<ModelUsageStats>();
|
||||
const { data: log, loading: logLoading, error: logError, run: runLog } = useUsageRequest<ModelUsageLog>();
|
||||
const summary = computed(() => stats.value?.summary);
|
||||
const coverage = computed(() => summary.value?.request_count
|
||||
? Math.round((summary.value.known_count / summary.value.request_count) * 1000) / 10
|
||||
: 0);
|
||||
const maxDailyTokens = computed(() => Math.max(1, ...(stats.value?.daily ?? []).map((row) => row.total_tokens ?? 0)));
|
||||
const models = computed(() => (stats.value?.by_model ?? []).map((row) => ({
|
||||
...row, key: `${row.provider_id}:${row.model}`,
|
||||
})));
|
||||
|
||||
function scope() {
|
||||
return { accountId: props.accountId, days: props.days, purpose: purpose.value };
|
||||
}
|
||||
|
||||
function loadLog() {
|
||||
const query = { ...scope(), limit: pageSize.value, offset: (page.value - 1) * pageSize.value };
|
||||
return runLog((signal) => fetchModelUsageLog(query, signal));
|
||||
}
|
||||
|
||||
function reload() {
|
||||
const query = scope();
|
||||
void runStats((signal) => fetchModelUsage(query, signal));
|
||||
void loadLog();
|
||||
}
|
||||
|
||||
watch(() => [props.accountId, props.days, purpose.value], () => {
|
||||
page.value = 1;
|
||||
reload();
|
||||
}, { immediate: true });
|
||||
|
||||
function changePage(pagination: { current?: number; pageSize?: number }) {
|
||||
const nextSize = pagination.pageSize ?? pageSize.value;
|
||||
page.value = nextSize === pageSize.value ? (pagination.current ?? 1) : 1;
|
||||
pageSize.value = nextSize;
|
||||
void loadLog();
|
||||
}
|
||||
|
||||
const tokenColumns = [
|
||||
{ title: '请求数', dataIndex: 'request_count', key: 'request_count', width: 85 },
|
||||
{ title: '已记录输入', key: 'input_tokens', width: 115 },
|
||||
{ title: '已记录输出', key: 'output_tokens', width: 115 },
|
||||
{ title: '已记录总 Token', key: 'total_tokens', width: 135 },
|
||||
{ title: '用量覆盖', key: 'coverage', width: 120 },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card title="模型 Token 用量" class="mb-5" size="small">
|
||||
<template #extra><Button :loading="loading || logLoading" @click="reload">刷新用量</Button></template>
|
||||
<p class="mb-3 text-sm text-gray-500">
|
||||
每次实际上游请求单独计数,包含所有回答候选、裁判、重试、界面检测及知识整理。Token 仅汇总上游已返回的用量;未返回和历史未记录的部分不作估算。
|
||||
</p>
|
||||
<Segmented v-model:value="purpose" class="mb-4" :options="[
|
||||
{ value: '', label: '全部用途' }, { value: 'chat', label: '客服回答与裁判' },
|
||||
{ value: 'guard', label: '界面检测' }, { value: 'knowledge', label: '知识整理' },
|
||||
]" />
|
||||
<Alert v-if="error" class="mb-4" type="error" show-icon :message="`用量统计${error}`" />
|
||||
<Row :gutter="[12, 12]" class="mb-4">
|
||||
<Col :xs="24" :sm="12" :xl="6"><Card size="small" :loading="loading"><Statistic title="实际上游请求" :value="summary ? usageNumber(summary.request_count) : '—'" /></Card></Col>
|
||||
<Col :xs="24" :sm="12" :xl="6"><Card size="small" :loading="loading"><Statistic title="已记录输入 Token" :value="usageTokens(summary, 'input_tokens')" /></Card></Col>
|
||||
<Col :xs="24" :sm="12" :xl="6"><Card size="small" :loading="loading"><Statistic title="已记录输出 Token" :value="usageTokens(summary, 'output_tokens')" /></Card></Col>
|
||||
<Col :xs="24" :sm="12" :xl="6"><Card size="small" :loading="loading"><Statistic title="已记录总 Token" :value="usageTokens(summary, 'total_tokens')" /></Card></Col>
|
||||
</Row>
|
||||
<template v-if="stats && summary">
|
||||
<div class="mb-4 rounded border border-gray-200 p-3 dark:border-gray-700">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span>总 Token 用量覆盖:{{ usageNumber(summary.known_count) }} / {{ usageNumber(summary.request_count) }} 次请求</span>
|
||||
<Tag :color="summary.missing_count ? 'orange' : 'green'">{{ usageNumber(summary.missing_count) }} 次未返回总用量</Tag>
|
||||
</div>
|
||||
<Progress :percent="coverage" size="small" :status="summary.missing_count ? 'normal' : undefined" />
|
||||
<p v-if="summary.input_known_count != null && summary.output_known_count != null" class="mb-1 text-xs text-gray-500">
|
||||
输入用量已记录 {{ summary.input_known_count }} / {{ summary.request_count }} 次;输出用量已记录 {{ summary.output_known_count }} / {{ summary.request_count }} 次。部分请求缺少用量时,合计仅包含已知部分。
|
||||
</p>
|
||||
<p class="mb-1 text-xs text-gray-500">
|
||||
已记录缓存输入 {{ usageTokens(summary, 'cached_input_tokens') }};已记录推理 {{ usageTokens(summary, 'reasoning_tokens') }}。
|
||||
缓存与推理属于明细项,不额外叠加至总 Token。单项未返回时显示“未返回”。
|
||||
</p>
|
||||
<p class="m-0 text-xs text-gray-500">统计起点 {{ usageUtcTime(stats.since) }} UTC;日期趋势按 UTC 自然日汇总。</p>
|
||||
</div>
|
||||
<Alert v-if="stats.legacy_unmetered_calls" class="mb-4" type="warning" show-icon
|
||||
:message="`另有 ${usageNumber(stats.legacy_unmetered_calls)} 次历史业务调用未记录 Token`"
|
||||
description="这些历史调用没有逐次上游用量记录,不计入以上请求数和已记录 Token 合计。" />
|
||||
<Empty v-if="!summary.request_count" class="my-5" description="当前账号与时间范围内暂无上游请求记录" />
|
||||
<template v-else>
|
||||
<h3 class="mb-2 font-medium">按模型统计</h3>
|
||||
<Table :data-source="models" row-key="key" size="small" :pagination="false" :scroll="{ x: 850 }" class="mb-4"
|
||||
:columns="[{ title: '模型 / 服务商', key: 'model', width: 230 }, ...tokenColumns]">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'model'"><div>{{ record.model || '未标记模型' }}</div><div class="text-xs text-gray-500">{{ record.provider_name || record.provider_id }}</div></template>
|
||||
<template v-else-if="column.key === 'coverage'">{{ record.known_count }} / {{ record.request_count }}<div v-if="record.missing_count" class="text-xs text-orange-500">{{ record.missing_count }} 次未返回</div></template>
|
||||
<template v-else-if="String(column.key).endsWith('_tokens')">{{ usageTokens(record, column.key) }}</template>
|
||||
</template>
|
||||
</Table>
|
||||
<h3 class="mb-2 font-medium">按用途统计</h3>
|
||||
<Table :data-source="stats.by_purpose" row-key="purpose" size="small" :pagination="false" :scroll="{ x: 800 }" class="mb-4"
|
||||
:columns="[{ title: '用途', key: 'purpose', width: 180 }, ...tokenColumns]">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'purpose'">{{ usagePurpose(record.purpose) }}</template>
|
||||
<template v-else-if="column.key === 'coverage'">{{ record.known_count }} / {{ record.request_count }}</template>
|
||||
<template v-else-if="String(column.key).endsWith('_tokens')">{{ usageTokens(record, column.key) }}</template>
|
||||
</template>
|
||||
</Table>
|
||||
<h3 class="mb-2 font-medium">每日趋势(UTC)</h3>
|
||||
<Table :data-source="stats.daily" row-key="date" size="small" :pagination="false" :scroll="{ x: 950 }" class="mb-4"
|
||||
:columns="[{ title: '日期(UTC)', dataIndex: 'date', key: 'date', width: 125 }, ...tokenColumns, { title: '已记录总量趋势', key: 'trend', width: 200 }]">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'trend'"><Progress v-if="record.total_tokens != null" :percent="Math.round((record.total_tokens / maxDailyTokens) * 100)" :show-info="false" size="small" /><span v-else>未返回</span></template>
|
||||
<template v-else-if="column.key === 'coverage'">{{ record.known_count }} / {{ record.request_count }}</template>
|
||||
<template v-else-if="String(column.key).endsWith('_tokens')">{{ usageTokens(record, column.key) }}</template>
|
||||
</template>
|
||||
</Table>
|
||||
</template>
|
||||
</template>
|
||||
<h3 class="mb-2 font-medium">实际请求明细</h3>
|
||||
<Alert v-if="logError" class="mb-3" type="error" show-icon :message="`请求明细${logError}`"><template #action><Button size="small" @click="loadLog">重试</Button></template></Alert>
|
||||
<Table :data-source="log?.items ?? []" row-key="event_id" size="small" :loading="logLoading" :scroll="{ x: 1600 }"
|
||||
:pagination="{ current: page, pageSize, total: log?.total ?? 0, showSizeChanger: true, pageSizeOptions: ['20', '50', '100'], showTotal: (total: number) => `共 ${total} 次上游请求` }"
|
||||
:columns="[
|
||||
{ title: '时间(UTC)', key: 'created_at', width: 170 }, { title: '模型 / 服务商', key: 'model', width: 230 },
|
||||
{ title: '用途 / 角色', key: 'purpose', width: 150 }, { title: '状态', key: 'status', width: 80 },
|
||||
{ title: '输入 Token', key: 'input_tokens', width: 110 }, { title: '输出 Token', key: 'output_tokens', width: 110 },
|
||||
{ title: '总 Token', key: 'total_tokens', width: 110 }, { title: '缓存输入', key: 'cached_input_tokens', width: 110 },
|
||||
{ title: '推理 Token', key: 'reasoning_tokens', width: 110 }, { title: '耗时', key: 'latency_ms', width: 90 },
|
||||
{ title: '尝试次数', dataIndex: 'attempt', key: 'attempt', width: 90 }, { title: '请求编号', dataIndex: 'request_id', key: 'request_id', width: 210, ellipsis: true },
|
||||
]" @change="changePage">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'created_at'">{{ usageUtcTime(record.created_at) }}</template>
|
||||
<template v-else-if="column.key === 'model'"><div>{{ record.model || '未标记模型' }}</div><div class="text-xs text-gray-500">{{ record.provider_name || record.provider_id }}</div></template>
|
||||
<template v-else-if="column.key === 'purpose'"><div>{{ usagePurpose(record.purpose) }}</div><Tag>{{ record.role === 'judge' ? '裁判' : '回答 / 生成' }}</Tag></template>
|
||||
<template v-else-if="column.key === 'status'"><Tag :color="record.status === 'success' ? 'green' : 'red'">{{ record.status === 'success' ? '成功' : '失败' }}</Tag></template>
|
||||
<template v-else-if="String(column.key).endsWith('_tokens')">{{ usageNumber(record[String(column.key)]) }}</template>
|
||||
<template v-else-if="column.key === 'latency_ms'">{{ usageNumber(record.latency_ms, '—') }} ms</template>
|
||||
</template>
|
||||
<template #emptyText>{{ logError ? '请求明细加载失败,请重试' : '暂无实际上游请求' }}</template>
|
||||
</Table>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -21,25 +21,24 @@ import {
|
||||
import { ALL_ACCOUNTS, fetchCallLog, fetchCallStats } from '#/api/console';
|
||||
import ArchiveAccountSelector from '#/components/archive-account-selector.vue';
|
||||
|
||||
import ModelUsageStats from './ModelUsageStats.vue';
|
||||
import { useUsageRequest } from './use-usage-request';
|
||||
|
||||
const days = ref(7);
|
||||
const accountId = ref(ALL_ACCOUNTS);
|
||||
const loading = ref(false);
|
||||
const stats = ref<CallStats | null>(null);
|
||||
const { data: stats, loading, error: statsError, run: runStats } = useUsageRequest<CallStats>();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
stats.value = await fetchCallStats(days.value, accountId.value);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
function load() {
|
||||
const account = accountId.value;
|
||||
const period = days.value;
|
||||
return runStats((signal) => fetchCallStats(period, account, signal));
|
||||
}
|
||||
|
||||
// ── 调用记录:定位某一句具体是怎么被回复的 ──────────────────────────────
|
||||
const logKeyword = ref('');
|
||||
const logLoading = ref(false);
|
||||
const logItems = ref<ModelCallLogItem[]>([]);
|
||||
const logTotal = ref(0);
|
||||
const { data: logResponse, loading: logLoading, error: logError, run: runLog } = useUsageRequest<{ items: ModelCallLogItem[]; total: number }>();
|
||||
const logItems = computed(() => logResponse.value?.items ?? []);
|
||||
const logTotal = computed(() => logResponse.value?.total ?? 0);
|
||||
const logPage = ref(1);
|
||||
const logPageSize = ref(20);
|
||||
const detailItem = ref<ModelCallLogItem | null>(null);
|
||||
@@ -51,22 +50,16 @@ const detailItem = ref<ModelCallLogItem | null>(null);
|
||||
*/
|
||||
const logPurpose = ref('chat');
|
||||
|
||||
async function loadLog() {
|
||||
logLoading.value = true;
|
||||
try {
|
||||
const resp = await fetchCallLog({
|
||||
accountId: accountId.value,
|
||||
days: days.value,
|
||||
limit: logPageSize.value,
|
||||
offset: (logPage.value - 1) * logPageSize.value,
|
||||
q: logKeyword.value.trim(),
|
||||
purpose: logPurpose.value,
|
||||
});
|
||||
logItems.value = resp.items;
|
||||
logTotal.value = resp.total;
|
||||
} finally {
|
||||
logLoading.value = false;
|
||||
}
|
||||
function loadLog() {
|
||||
const query = {
|
||||
accountId: accountId.value,
|
||||
days: days.value,
|
||||
limit: logPageSize.value,
|
||||
offset: (logPage.value - 1) * logPageSize.value,
|
||||
q: logKeyword.value.trim(),
|
||||
purpose: logPurpose.value,
|
||||
};
|
||||
return runLog((signal) => fetchCallLog(query, signal));
|
||||
}
|
||||
|
||||
function searchLog() {
|
||||
@@ -146,24 +139,28 @@ const RISK_COLOR: Record<string, string> = {
|
||||
class="mb-4"
|
||||
type="info"
|
||||
show-icon
|
||||
message="这张表是决定要不要上双模型的唯一依据"
|
||||
description="分数分布告诉你现有回复的真实水平——如果大部分本来就是高分,并发问两个模型就是纯浪费;如果低分集中在某一类消息上,针对性换个模型比全量双跑划算得多。"
|
||||
message="客服质量与模型用量"
|
||||
description="按账号和时间查看实际模型请求、已记录 Token,以及客服回复的裁判评分、风险分布和最终选用情况。"
|
||||
/>
|
||||
|
||||
<div class="mb-4 flex items-center gap-3">
|
||||
<div class="mb-4 flex flex-wrap items-center gap-3">
|
||||
<ArchiveAccountSelector
|
||||
v-model="accountId"
|
||||
@change="accountChanged"
|
||||
/>
|
||||
<Segmented
|
||||
v-model:value="days"
|
||||
:options="[{ value: 1, label: '今天' }, { value: 7, label: '近 7 天' }, { value: 30, label: '近 30 天' }]"
|
||||
:options="[{ value: 1, label: '近 1 天' }, { value: 7, label: '近 7 天' }, { value: 30, label: '近 30 天' }]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ModelUsageStats :account-id="accountId" :days="days" />
|
||||
|
||||
<h2 class="mb-3 text-lg font-medium">客服回复质量</h2>
|
||||
<Alert v-if="statsError" class="mb-3" type="error" show-icon :message="statsError" />
|
||||
<Row :gutter="16" class="mb-4">
|
||||
<Col :span="6">
|
||||
<Card size="small"><Statistic title="总调用" :value="stats?.total ?? 0" /></Card>
|
||||
<Card size="small"><Statistic title="业务调用记录" :value="stats?.total ?? 0" /></Card>
|
||||
</Col>
|
||||
<Col :span="6">
|
||||
<Card size="small"><Statistic title="已评审" :value="stats?.judged ?? 0" /></Card>
|
||||
@@ -255,6 +252,7 @@ const RISK_COLOR: Record<string, string> = {
|
||||
「界面识别」是机器人自己看企业微信窗口用的,不是发给客户的话;它每轮轮询都要问一次模型,条数远多于真实对话,所以默认不混在一起。
|
||||
</span>
|
||||
</div>
|
||||
<Alert v-if="logError" class="mb-3" type="error" show-icon :message="logError" />
|
||||
<Table
|
||||
:data-source="logItems"
|
||||
row-key="id"
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ModelUsageSummary } from '../../api/console';
|
||||
|
||||
export function usageNumber(value: unknown, missing = '未返回'): string {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? value.toLocaleString('zh-CN')
|
||||
: missing;
|
||||
}
|
||||
|
||||
export function usageTokens(
|
||||
row: ModelUsageSummary | Record<string, unknown> | null | undefined,
|
||||
field: unknown,
|
||||
): string {
|
||||
if (!row) return '—';
|
||||
const key = String(field) as 'cached_input_tokens' | 'input_tokens' | 'output_tokens' | 'reasoning_tokens' | 'total_tokens';
|
||||
return usageNumber(row[key]);
|
||||
}
|
||||
|
||||
export function usagePurpose(value: string): string {
|
||||
return ({ chat: '客服回答与裁判', guard: '界面检测', knowledge: '知识整理' } as Record<string, string>)[value] || value || '未标记';
|
||||
}
|
||||
|
||||
export function usageUtcTime(value: string): string {
|
||||
if (!value) return '—';
|
||||
const text = value.trim().replace(' ', 'T');
|
||||
const parsed = new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(text) ? text : `${text}Z`);
|
||||
return Number.isNaN(parsed.getTime()) ? value : parsed.toISOString().slice(0, 19).replace('T', ' ');
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { ModelUsageSummary } from '../../api/console';
|
||||
|
||||
import { effectScope } from 'vue';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { usageNumber, usagePurpose, usageTokens, usageUtcTime } from './model-usage-format';
|
||||
import { useUsageRequest } from './use-usage-request';
|
||||
|
||||
function setupRequest() {
|
||||
const scope = effectScope();
|
||||
const request = scope.run(() => useUsageRequest<string>())!;
|
||||
return { request, stop: () => scope.stop() };
|
||||
}
|
||||
|
||||
describe('model usage display', () => {
|
||||
it('distinguishes an explicit zero from missing usage', () => {
|
||||
expect(usageNumber(0)).toBe('0');
|
||||
expect(usageNumber(null)).toBe('未返回');
|
||||
expect(usageNumber(undefined)).toBe('未返回');
|
||||
expect(usageNumber(Number.NaN)).toBe('未返回');
|
||||
expect(usageNumber(12000)).toBe('12,000');
|
||||
});
|
||||
|
||||
it('does not invent missing input tokens when total tokens are known', () => {
|
||||
const row: ModelUsageSummary = {
|
||||
request_count: 1, known_count: 1, missing_count: 0,
|
||||
input_tokens: null, output_tokens: null, total_tokens: 45,
|
||||
cached_input_tokens: null, reasoning_tokens: null,
|
||||
};
|
||||
expect(usageTokens(row, 'input_tokens')).toBe('未返回');
|
||||
expect(usageTokens(row, 'total_tokens')).toBe('45');
|
||||
expect(usageTokens(null, 'total_tokens')).toBe('—');
|
||||
});
|
||||
|
||||
it('displays timestamps consistently in UTC including offsets and legacy forms', () => {
|
||||
expect(usageUtcTime('2026-09-18T01:30:00+08:00')).toBe('2026-09-17 17:30:00');
|
||||
expect(usageUtcTime('2026-09-17 17:30:00')).toBe('2026-09-17 17:30:00');
|
||||
expect(usageUtcTime('not-a-time')).toBe('not-a-time');
|
||||
expect(usageUtcTime('')).toBe('—');
|
||||
});
|
||||
|
||||
it('labels all measured purposes and preserves future purpose values', () => {
|
||||
expect(usagePurpose('chat')).toBe('客服回答与裁判');
|
||||
expect(usagePurpose('guard')).toBe('界面检测');
|
||||
expect(usagePurpose('knowledge')).toBe('知识整理');
|
||||
expect(usagePurpose('future')).toBe('future');
|
||||
});
|
||||
});
|
||||
|
||||
describe('model usage request scope', () => {
|
||||
it('aborts old account requests and ignores delayed stale data', async () => {
|
||||
const { request, stop } = setupRequest();
|
||||
let done!: (value: string) => void;
|
||||
let oldSignal!: AbortSignal;
|
||||
const old = request.run((signal) => {
|
||||
oldSignal = signal;
|
||||
return new Promise((resolve) => { done = resolve; });
|
||||
});
|
||||
await request.run(async () => 'current account');
|
||||
done('previous account');
|
||||
await old;
|
||||
expect(oldSignal.aborted).toBe(true);
|
||||
expect(request.data.value).toBe('current account');
|
||||
expect(request.error.value).toBe('');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('clears old totals while the new scope loads and ignores stale errors', async () => {
|
||||
const { request, stop } = setupRequest();
|
||||
await request.run(async () => 'old totals');
|
||||
let fail!: (cause: unknown) => void;
|
||||
let done!: (value: string) => void;
|
||||
const old = request.run(() => new Promise((_resolve, reject) => { fail = reject; }));
|
||||
const current = request.run(() => new Promise((resolve) => { done = resolve; }));
|
||||
expect(request.data.value).toBeNull();
|
||||
fail(new Error('old account failed'));
|
||||
await old;
|
||||
expect(request.loading.value).toBe(true);
|
||||
expect(request.error.value).toBe('');
|
||||
done('current totals');
|
||||
await current;
|
||||
expect(request.loading.value).toBe(false);
|
||||
expect(request.data.value).toBe('current totals');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('renders a current error instead of keeping the previous account totals', async () => {
|
||||
const { request, stop } = setupRequest();
|
||||
await request.run(async () => 'old totals');
|
||||
await request.run(async () => { throw { detail: '无权访问此账号' }; });
|
||||
expect(request.data.value).toBeNull();
|
||||
expect(request.error.value).toBe('无权访问此账号');
|
||||
expect(request.loading.value).toBe(false);
|
||||
await request.run(async () => 'retry ok');
|
||||
expect(request.error.value).toBe('');
|
||||
expect(request.data.value).toBe('retry ok');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('prevents completion after navigating away', async () => {
|
||||
const { request, stop } = setupRequest();
|
||||
let done!: (value: string) => void;
|
||||
let signal!: AbortSignal;
|
||||
const pending = request.run((value) => {
|
||||
signal = value;
|
||||
return new Promise((resolve) => { done = resolve; });
|
||||
});
|
||||
stop();
|
||||
expect(signal.aborted).toBe(true);
|
||||
done('late');
|
||||
await pending;
|
||||
expect(request.data.value).toBeNull();
|
||||
expect(request.loading.value).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,7 @@ const reports = reactive<{ counts: Record<string, number>; items: any[] }>({
|
||||
const current = reactive({
|
||||
latest_version: '',
|
||||
download_url: '',
|
||||
package_media_id: '',
|
||||
release_notes: '',
|
||||
force_upgrade: false,
|
||||
auto_install: false,
|
||||
@@ -66,6 +67,7 @@ const current = reactive({
|
||||
const form = reactive({
|
||||
latest_version: '',
|
||||
download_url: '',
|
||||
package_media_id: '',
|
||||
release_notes: '',
|
||||
force_upgrade: false,
|
||||
auto_install: true,
|
||||
@@ -123,6 +125,7 @@ async function load() {
|
||||
Object.assign(form, {
|
||||
latest_version: data.latest_version,
|
||||
download_url: data.download_url,
|
||||
package_media_id: data.package_media_id || '',
|
||||
release_notes: data.release_notes,
|
||||
force_upgrade: data.force_upgrade,
|
||||
auto_install: data.auto_install,
|
||||
@@ -148,10 +151,12 @@ async function selectPackage(file: File) {
|
||||
uploadProgress.value = value;
|
||||
});
|
||||
form.download_url = result.download_url;
|
||||
form.package_media_id = result.package_media_id;
|
||||
form.auto_install = true;
|
||||
form.package_sha256 = result.package_sha256;
|
||||
form.package_size = result.package_size;
|
||||
uploadProgress.value = 100;
|
||||
message.success('安装包已直传腾讯 COS,并完成 SHA256 校验');
|
||||
message.success('安装包已上传 COS,已生成下载直链并开启自动安装');
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '安装包上传失败');
|
||||
} finally {
|
||||
@@ -214,7 +219,7 @@ onMounted(load);
|
||||
type="success"
|
||||
show-icon
|
||||
message="安装包直传腾讯 COS"
|
||||
description="浏览器先在本机计算 SHA256,再分块直传 COS;安装包不经过管理端服务器。COS 校验完成后,客户端会按发布策略安全下载和安装。"
|
||||
description="浏览器先在本机计算 SHA256,再分块直传 COS;安装包不经过管理端服务器。上传完成后显示 COS 下载直链;客户端发现已发布的新版本后直接从 COS 下载,校验通过后自动安装。"
|
||||
/>
|
||||
|
||||
<Card title="当前版本策略" class="mb-4" :loading="loading">
|
||||
@@ -257,7 +262,7 @@ onMounted(load);
|
||||
:show-upload-list="false"
|
||||
>
|
||||
<Button :loading="uploading" :disabled="!canWrite">
|
||||
{{ uploading ? '正在直传 COS' : '选择并直传 COS' }}
|
||||
{{ uploading ? (uploadProgress < 5 ? '正在计算 SHA256' : '正在直传 COS') : '选择并直传 COS' }}
|
||||
</Button>
|
||||
</Upload>
|
||||
<Tag v-if="packageReady" color="green">
|
||||
@@ -287,8 +292,9 @@ onMounted(load);
|
||||
</FormItem>
|
||||
</div>
|
||||
|
||||
<FormItem label="下载地址">
|
||||
<Input v-model:value="form.download_url" :disabled="!canWrite" placeholder="上传安装包后自动填写,也可以填写 HTTPS 地址" />
|
||||
<FormItem label="下载地址(COS 直链)">
|
||||
<Input v-model:value="form.download_url" :disabled="!canWrite" placeholder="上传安装包后自动填写 COS HTTPS 地址,也可填写其他 HTTPS 地址" @change="form.package_media_id = ''" />
|
||||
<p v-if="form.package_media_id" class="mt-2 text-xs text-gray-500">当前直链有效期为 15 分钟。发布后客户端每次检查更新都会获取新地址,无需重新上传。</p>
|
||||
</FormItem>
|
||||
<FormItem label="SHA256">
|
||||
<Input v-model:value="form.package_sha256" :disabled="!canWrite" placeholder="上传安装包后自动计算" />
|
||||
@@ -314,7 +320,7 @@ onMounted(load);
|
||||
<Textarea v-model:value="form.release_notes" :rows="5" :disabled="!canWrite" :maxlength="4000" show-count />
|
||||
</FormItem>
|
||||
|
||||
<Button v-if="canWrite" type="primary" size="large" :loading="saving" @click="submit">
|
||||
<Button v-if="canWrite" type="primary" size="large" :loading="saving" :disabled="uploading" @click="submit">
|
||||
发布版本
|
||||
</Button>
|
||||
</Form>
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { onScopeDispose, ref, shallowRef } from 'vue';
|
||||
|
||||
import { requestErrorMessage } from '../../api/error-message';
|
||||
|
||||
/** Clear old-scope totals immediately and prevent stale responses/errors from winning. */
|
||||
export function useUsageRequest<T>() {
|
||||
const data = shallowRef<null | T>(null);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
let current: AbortController | undefined;
|
||||
|
||||
function cancel() {
|
||||
current?.abort();
|
||||
current = undefined;
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
async function run(fetcher: (signal: AbortSignal) => Promise<T>) {
|
||||
cancel();
|
||||
const request = new AbortController();
|
||||
current = request;
|
||||
data.value = null;
|
||||
error.value = '';
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await fetcher(request.signal);
|
||||
if (current === request && !request.signal.aborted) data.value = result;
|
||||
} catch (cause) {
|
||||
if (current === request && !request.signal.aborted) {
|
||||
error.value = requestErrorMessage(cause, '加载失败,请稍后重试');
|
||||
}
|
||||
} finally {
|
||||
if (current === request) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onScopeDispose(cancel);
|
||||
return { cancel, data, error, loading, run };
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { KnowledgeItem } from '#/api/knowledge';
|
||||
import { actionProblem, runKnowledgeBatch } from './batch';
|
||||
|
||||
const item = (id: string, status = 'draft') => ({ id, title: id, revision: 4, status, conditions: '通用预约流程' } as KnowledgeItem);
|
||||
describe('knowledge batch workflow', () => {
|
||||
it('preserves revisions, reports partial failures and continues to other items', async () => {
|
||||
const seen: number[] = [];
|
||||
const result = await runKnowledgeBatch([item('a'), item('b'), item('c')], async (entry) => {
|
||||
seen.push(entry.revision);
|
||||
if (entry.id === 'b') throw { response: { data: { detail: '知识版本已变化,请刷新' } } };
|
||||
}, () => {}, () => false);
|
||||
expect(seen).toEqual([4, 4, 4]);
|
||||
expect(result.map((row) => row.status)).toEqual(['success', 'failed', 'success']);
|
||||
expect(result[1]?.error).toContain('版本已变化');
|
||||
});
|
||||
it('stops only subsequent requests after an in-flight mutation completes', async () => {
|
||||
let stop = false;
|
||||
const result = await runKnowledgeBatch([item('a'), item('b')], async () => { stop = true; }, () => {}, () => stop);
|
||||
expect(result.map((row) => row.status)).toEqual(['success', 'pending']);
|
||||
});
|
||||
it('only permits deletion of rejected knowledge', () => {
|
||||
expect(actionProblem(item('a', 'rejected'), 'delete')).toBe('');
|
||||
for (const status of ['draft', 'approved', 'published', 'stale', 'disabled']) {
|
||||
expect(actionProblem(item('a', status), 'delete')).toBeTruthy();
|
||||
}
|
||||
});
|
||||
it('does not approve missing conditions or publish drafts', () => {
|
||||
expect(actionProblem({ ...item('a'), conditions: ' ' }, 'approve')).toContain('适用条件');
|
||||
expect(actionProblem(item('a'), 'publish')).toBeTruthy();
|
||||
expect(actionProblem(item('a', 'approved'), 'publish')).toBe('');
|
||||
expect(actionProblem(item('a', 'stale'), 'approve')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,10 @@ export default defineConfig(async () => {
|
||||
return {
|
||||
application: {},
|
||||
vite: {
|
||||
resolve: {
|
||||
// Workspace packages must share the same injection keys and store instance.
|
||||
dedupe: ['vue', 'vue-router', 'pinia'],
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
// 前端统一请求 /api/*,代理到 admin_api.py 的 /api/v2/*。
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { generatorContentHash } from '../hash';
|
||||
|
||||
describe('generatorContentHash', () => {
|
||||
it('should generate an MD5 hash for the content', () => {
|
||||
const content = 'example content';
|
||||
const expectedHash = createHash('md5')
|
||||
.update(content, 'utf8')
|
||||
.digest('hex');
|
||||
const actualHash = generatorContentHash(content);
|
||||
expect(actualHash).toBe(expectedHash);
|
||||
});
|
||||
|
||||
it('should generate an MD5 hash with specified length', () => {
|
||||
const content = 'example content';
|
||||
const hashLength = 10;
|
||||
const generatedHash = generatorContentHash(content, hashLength);
|
||||
expect(generatedHash).toHaveLength(hashLength);
|
||||
});
|
||||
|
||||
it('should correctly generate the hash with specified length', () => {
|
||||
const content = 'example content';
|
||||
const hashLength = 8;
|
||||
const expectedHash = createHash('md5')
|
||||
.update(content, 'utf8')
|
||||
.digest('hex')
|
||||
.slice(0, hashLength);
|
||||
const generatedHash = generatorContentHash(content, hashLength);
|
||||
expect(generatedHash).toBe(expectedHash);
|
||||
});
|
||||
|
||||
it('should return full hash if hash length parameter is not provided', () => {
|
||||
const content = 'example content';
|
||||
const expectedHash = createHash('md5')
|
||||
.update(content, 'utf8')
|
||||
.digest('hex');
|
||||
const actualHash = generatorContentHash(content);
|
||||
expect(actualHash).toBe(expectedHash);
|
||||
});
|
||||
|
||||
it('should handle empty content', () => {
|
||||
const content = '';
|
||||
const expectedHash = createHash('md5')
|
||||
.update(content, 'utf8')
|
||||
.digest('hex');
|
||||
const actualHash = generatorContentHash(content);
|
||||
expect(actualHash).toBe(expectedHash);
|
||||
});
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
// pathUtils.test.ts
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { toPosixPath } from '../path';
|
||||
|
||||
describe('toPosixPath', () => {
|
||||
// 测试 Windows 风格路径到 POSIX 风格路径的转换
|
||||
it('converts Windows-style paths to POSIX paths', () => {
|
||||
const windowsPath = String.raw`C:\Users\Example\file.txt`;
|
||||
const expectedPosixPath = 'C:/Users/Example/file.txt';
|
||||
expect(toPosixPath(windowsPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
|
||||
// 确认 POSIX 风格路径不会被改变
|
||||
it('leaves POSIX-style paths unchanged', () => {
|
||||
const posixPath = '/home/user/file.txt';
|
||||
expect(toPosixPath(posixPath)).toBe(posixPath);
|
||||
});
|
||||
|
||||
// 测试带有多个分隔符的路径
|
||||
it('converts paths with mixed separators', () => {
|
||||
const mixedPath = String.raw`C:/Users\Example\file.txt`;
|
||||
const expectedPosixPath = 'C:/Users/Example/file.txt';
|
||||
expect(toPosixPath(mixedPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
|
||||
// 测试空字符串
|
||||
it('handles empty strings', () => {
|
||||
const emptyPath = '';
|
||||
expect(toPosixPath(emptyPath)).toBe('');
|
||||
});
|
||||
|
||||
// 测试仅包含分隔符的路径
|
||||
it('handles path with only separators', () => {
|
||||
const separatorsPath = '\\\\\\';
|
||||
const expectedPosixPath = '///';
|
||||
expect(toPosixPath(separatorsPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
|
||||
// 测试不包含任何分隔符的路径
|
||||
it('handles path without separators', () => {
|
||||
const noSeparatorPath = 'file.txt';
|
||||
expect(toPosixPath(noSeparatorPath)).toBe('file.txt');
|
||||
});
|
||||
|
||||
// 测试以分隔符结尾的路径
|
||||
it('handles path ending with a separator', () => {
|
||||
const endingSeparatorPath = 'C:\\Users\\Example\\';
|
||||
const expectedPosixPath = 'C:/Users/Example/';
|
||||
expect(toPosixPath(endingSeparatorPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
|
||||
// 测试以分隔符开头的路径
|
||||
it('handles path starting with a separator', () => {
|
||||
const startingSeparatorPath = String.raw`\Users\Example`;
|
||||
const expectedPosixPath = '/Users/Example';
|
||||
expect(toPosixPath(startingSeparatorPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
|
||||
// 测试包含非法字符的路径
|
||||
it('handles path with invalid characters', () => {
|
||||
const invalidCharsPath = String.raw`C:\Us*?ers\Ex<ample>|file.txt`;
|
||||
const expectedPosixPath = 'C:/Us*?ers/Ex<ample>|file.txt';
|
||||
expect(toPosixPath(invalidCharsPath)).toBe(expectedPosixPath);
|
||||
});
|
||||
});
|
||||
@@ -1,159 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { viteCssLayerPlugin } from './css-layer';
|
||||
|
||||
interface FakeAsset {
|
||||
fileName: string;
|
||||
source: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
function createBundle(assets: FakeAsset[]) {
|
||||
return Object.fromEntries(assets.map((asset) => [asset.fileName, asset]));
|
||||
}
|
||||
|
||||
const LAYER_ORDER_STATEMENT =
|
||||
'@layer properties, theme, base, ant, antd, el, td, components, utilities;';
|
||||
|
||||
describe('viteCssLayerPlugin', () => {
|
||||
it('wraps matching css modules in the target layer', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const transform = plugin.transform;
|
||||
|
||||
if (typeof transform !== 'function') return;
|
||||
|
||||
const result = transform.call(
|
||||
undefined as never,
|
||||
'.el-button { color: red; }',
|
||||
'/node_modules/element-plus/es/components/button/style/css/index.css?used',
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
code: '@layer el {\n.el-button { color: red; }\n}',
|
||||
map: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not wrap css modules outside the target package', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const transform = plugin.transform;
|
||||
|
||||
if (typeof transform !== 'function') return;
|
||||
|
||||
const result = transform.call(
|
||||
undefined as never,
|
||||
'.local { color: red; }',
|
||||
'/src/views/home/index.css',
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('injects the layer order statement into matching css assets', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: '@layer el{.el-button{color:red}}',
|
||||
type: 'asset',
|
||||
},
|
||||
{
|
||||
fileName: 'theme-x.css',
|
||||
source: '.local { color: blue; }',
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
expect(bundle['theme-x.css'].source).toBe('.local { color: blue; }');
|
||||
});
|
||||
|
||||
it('does not inject the statement twice when already present', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: `${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('injects the statement even when the asset starts with a BOM', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: `\uFEFF@layer el{.el-button{color:red}}`,
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n\uFEFF@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores non-css assets', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.js',
|
||||
source: '@layer el{.el-button{color:red}}',
|
||||
type: 'chunk',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.js'].source).toBe(
|
||||
'@layer el{.el-button{color:red}}',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
FORM_FIELD_SLOT_MIGRATION_WARNING,
|
||||
viteFormFieldSlotMigrationWarningPlugin,
|
||||
} from './form-field-slot-migration-warning';
|
||||
|
||||
describe('form field slot migration warning plugin', () => {
|
||||
it('warns in serve mode and injects the same browser message', () => {
|
||||
const plugin = viteFormFieldSlotMigrationWarningPlugin();
|
||||
const warning = vi.fn();
|
||||
|
||||
expect(plugin.apply).toBe('serve');
|
||||
expect(plugin.configResolved).toBeTypeOf('function');
|
||||
if (typeof plugin.configResolved !== 'function') return;
|
||||
|
||||
plugin.configResolved({ logger: { warn: warning } } as ResolvedConfig);
|
||||
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledWith(FORM_FIELD_SLOT_MIGRATION_WARNING);
|
||||
expect(plugin.transformIndexHtml).toBeTypeOf('function');
|
||||
if (typeof plugin.transformIndexHtml !== 'function') return;
|
||||
|
||||
const result = plugin.transformIndexHtml('', {} as never);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
attrs: {
|
||||
'data-vben-form-field-slot-migration-warning': '',
|
||||
},
|
||||
children: `console.warn(${JSON.stringify(FORM_FIELD_SLOT_MIGRATION_WARNING)});`,
|
||||
injectTo: 'body',
|
||||
tag: 'script',
|
||||
},
|
||||
]);
|
||||
expect(FORM_FIELD_SLOT_MIGRATION_WARNING).toContain('`v-bind="slotProps"`');
|
||||
expect(FORM_FIELD_SLOT_MIGRATION_WARNING).toContain(
|
||||
'`v-bind="slotProps.componentProps"`',
|
||||
);
|
||||
});
|
||||
});
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { MemoryStorageDriver } from '../memory-storage-driver';
|
||||
import { StorageManager } from '../storage-manager';
|
||||
|
||||
describe('storageManager', () => {
|
||||
let storageManager: StorageManager;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
storageManager = new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix: 'test_',
|
||||
});
|
||||
});
|
||||
|
||||
it('should set and get an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should return default value if item does not exist', async () => {
|
||||
const user = await storageManager.getItem('nonexistent', {
|
||||
age: 0,
|
||||
name: 'Default User',
|
||||
});
|
||||
expect(user).toEqual({ age: 0, name: 'Default User' });
|
||||
});
|
||||
|
||||
it('should remove an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.removeItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear all items with the prefix', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
expect(await storageManager.getItem('user1')).toBeNull();
|
||||
expect(await storageManager.getItem('user2')).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not clear non-expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should return null for non-existent items without default value', async () => {
|
||||
const user = await storageManager.getItem('nonexistent');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should overwrite existing items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items without expiry correctly', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should remove expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not remove non-expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should handle multiple items with different expiry times', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
|
||||
vi.advanceTimersByTime(1500); // 快进时间
|
||||
await storageManager.clearExpiredItems();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items with no expiry', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(10_000); // 快进时间
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should clear all items correctly', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
convertToHsl,
|
||||
convertToHslCssVar,
|
||||
convertToRgb,
|
||||
isValidColor,
|
||||
} from '../convert';
|
||||
|
||||
describe('color conversion functions', () => {
|
||||
it('should correctly convert color to HSL format', () => {
|
||||
const color = '#ff0000';
|
||||
const expectedHsl = 'hsl(0 100% 50%)';
|
||||
expect(convertToHsl(color)).toEqual(expectedHsl);
|
||||
});
|
||||
|
||||
it('should correctly convert color with alpha to HSL format', () => {
|
||||
const color = 'rgba(255, 0, 0, 0.5)';
|
||||
const expectedHsl = 'hsl(0 100% 50%) 0.5';
|
||||
expect(convertToHsl(color)).toEqual(expectedHsl);
|
||||
});
|
||||
|
||||
it('should correctly convert color to HSL CSS variable format', () => {
|
||||
const color = '#ff0000';
|
||||
const expectedHsl = '0 100% 50%';
|
||||
expect(convertToHslCssVar(color)).toEqual(expectedHsl);
|
||||
});
|
||||
|
||||
it('should correctly convert color with alpha to HSL CSS variable format', () => {
|
||||
const color = 'rgba(255, 0, 0, 0.5)';
|
||||
const expectedHsl = '0 100% 50% / 0.5';
|
||||
expect(convertToHslCssVar(color)).toEqual(expectedHsl);
|
||||
});
|
||||
|
||||
it('should correctly convert color to RGB CSS variable format', () => {
|
||||
const color = 'hsl(284, 100%, 50%)';
|
||||
const expectedRgb = 'rgb(187, 0, 255)';
|
||||
expect(convertToRgb(color)).toEqual(expectedRgb);
|
||||
});
|
||||
|
||||
it('should correctly convert color with alpha to RGBA CSS variable format', () => {
|
||||
const color = 'hsla(284, 100%, 50%, 0.92)';
|
||||
const expectedRgba = 'rgba(187, 0, 255, 0.92)';
|
||||
expect(convertToRgb(color)).toEqual(expectedRgba);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidColor', () => {
|
||||
it('isValidColor function', () => {
|
||||
// 测试有效颜色
|
||||
expect(isValidColor('blue')).toBe(true);
|
||||
expect(isValidColor('#000000')).toBe(true);
|
||||
|
||||
// 测试无效颜色
|
||||
expect(isValidColor('invalid color')).toBe(false);
|
||||
expect(isValidColor()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,143 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
formatDate,
|
||||
formatDateTime,
|
||||
getCurrentTimezone,
|
||||
getSystemTimezone,
|
||||
isDate,
|
||||
isDayjsObject,
|
||||
setCurrentTimezone,
|
||||
} from '../date';
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
describe('dateUtils', () => {
|
||||
const sampleISO = '2024-10-30T12:34:56Z';
|
||||
const sampleTimestamp = Date.parse(sampleISO);
|
||||
|
||||
beforeEach(() => {
|
||||
// 重置时区
|
||||
dayjs.tz.setDefault();
|
||||
setCurrentTimezone(); // 重置为系统默认
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDate
|
||||
// ===============================
|
||||
describe('formatDate', () => {
|
||||
it('should format a valid ISO date string', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY/MM/DD');
|
||||
expect(formatted).toMatch(/2024\/10\/30/);
|
||||
});
|
||||
|
||||
it('should format a timestamp correctly', () => {
|
||||
const formatted = formatDate(sampleTimestamp);
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a Date object', () => {
|
||||
const formatted = formatDate(new Date(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a dayjs object', () => {
|
||||
const formatted = formatDate(dayjs(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should return original input if date is invalid', () => {
|
||||
const invalid = 'not-a-date';
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const formatted = formatDate(invalid);
|
||||
expect(formatted).toBe(invalid);
|
||||
expect(spy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should apply given format', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY-MM-DD HH:mm');
|
||||
expect(formatted).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDateTime
|
||||
// ===============================
|
||||
describe('formatDateTime', () => {
|
||||
it('should format date into full datetime', () => {
|
||||
const result = formatDateTime(sampleISO);
|
||||
expect(result).toMatch(/2024-10-30 \d{2}:\d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDate
|
||||
// ===============================
|
||||
describe('isDate', () => {
|
||||
it('should return true for Date instances', () => {
|
||||
expect(isDate(new Date())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-Date values', () => {
|
||||
expect(isDate('2024-10-30')).toBe(false);
|
||||
expect(isDate(null)).toBe(false);
|
||||
expect(isDate(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDayjsObject
|
||||
// ===============================
|
||||
describe('isDayjsObject', () => {
|
||||
it('should return true for dayjs objects', () => {
|
||||
expect(isDayjsObject(dayjs())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for other values', () => {
|
||||
expect(isDayjsObject(new Date())).toBe(false);
|
||||
expect(isDayjsObject('string')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// getSystemTimezone
|
||||
// ===============================
|
||||
describe('getSystemTimezone', () => {
|
||||
it('should return a valid IANA timezone string', () => {
|
||||
const tz = getSystemTimezone();
|
||||
expect(typeof tz).toBe('string');
|
||||
expect(tz).toMatch(/^[A-Z]+\/[A-Z_]+/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// setCurrentTimezone / getCurrentTimezone
|
||||
// ===============================
|
||||
describe('setCurrentTimezone & getCurrentTimezone', () => {
|
||||
it('should set and retrieve the current timezone', () => {
|
||||
setCurrentTimezone('Asia/Shanghai');
|
||||
expect(getCurrentTimezone()).toBe('Asia/Shanghai');
|
||||
});
|
||||
|
||||
it('should reset to system timezone when called with no args', () => {
|
||||
const guessed = getSystemTimezone();
|
||||
setCurrentTimezone();
|
||||
expect(getCurrentTimezone()).toBe(guessed);
|
||||
});
|
||||
|
||||
it('should update dayjs default timezone', () => {
|
||||
setCurrentTimezone('America/New_York');
|
||||
const d = dayjs('2024-01-01T00:00:00Z');
|
||||
// 校验时区转换生效(小时变化)
|
||||
expect(d.tz().format('HH')).not.toBe('00');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { diff, diffStrict } from '../diff';
|
||||
|
||||
describe('diff function', () => {
|
||||
it('should return an empty object when comparing identical objects', () => {
|
||||
const obj1 = { a: 1, b: { c: 2 } };
|
||||
const obj2 = { a: 1, b: { c: 2 } };
|
||||
expect(diff(obj1, obj2)).toEqual(undefined);
|
||||
});
|
||||
|
||||
it('should detect simple changes in primitive values', () => {
|
||||
const obj1 = { a: 1, b: 2 };
|
||||
const obj2 = { a: 1, b: 3 };
|
||||
expect(diff(obj1, obj2)).toEqual({ b: 3 });
|
||||
});
|
||||
|
||||
it('should detect nested object changes', () => {
|
||||
const obj1 = { a: 1, b: { c: 2, d: 4 } };
|
||||
const obj2 = { a: 1, b: { c: 3, d: 4 } };
|
||||
expect(diff(obj1, obj2)).toEqual({ b: { c: 3 } });
|
||||
});
|
||||
|
||||
it('should handle array changes', () => {
|
||||
const obj1 = { a: [1, 2, 3], b: 2 };
|
||||
const obj2 = { a: [1, 2, 4], b: 2 };
|
||||
expect(diff(obj1, obj2)).toEqual({ a: [1, 2, 4] });
|
||||
});
|
||||
|
||||
it('should ignore array order changes', () => {
|
||||
const obj1 = { a: [1, 2, 3] };
|
||||
const obj2 = { a: [3, 2, 1] };
|
||||
expect(diff(obj1, obj2)).toEqual(undefined);
|
||||
});
|
||||
|
||||
it('should handle added keys', () => {
|
||||
const obj1 = { a: 1 };
|
||||
const obj2 = { a: 1, b: 2 };
|
||||
expect(diff(obj1, obj2)).toEqual({ b: 2 });
|
||||
});
|
||||
|
||||
it('should handle removed keys', () => {
|
||||
const obj1 = { a: 1, b: 2 };
|
||||
const obj2 = { a: 1 };
|
||||
expect(diff(obj1, obj2)).toEqual(undefined);
|
||||
});
|
||||
|
||||
it('should handle boolean value changes', () => {
|
||||
const obj1 = { a: true, b: false };
|
||||
const obj2 = { a: true, b: true };
|
||||
expect(diff(obj1, obj2)).toEqual({ b: true });
|
||||
});
|
||||
|
||||
it('should handle null and undefined values', () => {
|
||||
const obj1 = { a: null, b: undefined };
|
||||
const obj2: any = { a: 1, b: undefined };
|
||||
expect(diff(obj1, obj2)).toEqual({ a: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('diffStrict function', () => {
|
||||
it('should return undefined when comparing identical objects', () => {
|
||||
const obj1 = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
|
||||
const obj2 = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
|
||||
expect(diffStrict(obj1, obj2)).toEqual(undefined);
|
||||
});
|
||||
|
||||
it('should detect array order changes', () => {
|
||||
const obj1 = { a: ['search', 'theme', 'logout'] };
|
||||
const obj2 = { a: ['logout', 'theme', 'search'] };
|
||||
expect(diffStrict(obj1, obj2)).toEqual({
|
||||
a: ['logout', 'theme', 'search'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should detect array element changes', () => {
|
||||
const obj1 = { a: [1, 2, 3] };
|
||||
const obj2 = { a: [1, 2, 4] };
|
||||
expect(diffStrict(obj1, obj2)).toEqual({ a: [1, 2, 4] });
|
||||
});
|
||||
|
||||
it('should detect nested object changes', () => {
|
||||
const obj1 = { a: 1, b: { c: 2, d: 4 } };
|
||||
const obj2 = { a: 1, b: { c: 3, d: 4 } };
|
||||
expect(diffStrict(obj1, obj2)).toEqual({ b: { c: 3 } });
|
||||
});
|
||||
});
|
||||
@@ -1,208 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ELEMENT_ID_LAYOUT_SCROLL } from '../../constants';
|
||||
import {
|
||||
getElementVisibleRect,
|
||||
getLayoutScrollElement,
|
||||
needsScrollbar,
|
||||
} from '../dom';
|
||||
|
||||
describe('getElementVisibleRect', () => {
|
||||
// 设置浏览器视口尺寸的 mock
|
||||
beforeEach(() => {
|
||||
vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(
|
||||
800,
|
||||
);
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800);
|
||||
vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(
|
||||
1000,
|
||||
);
|
||||
vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(1000);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should return default rect if element is undefined', () => {
|
||||
expect(getElementVisibleRect()).toEqual({
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return default rect if element is null', () => {
|
||||
expect(getElementVisibleRect(null)).toEqual({
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return correct visible rect when element is fully visible', () => {
|
||||
const element = {
|
||||
getBoundingClientRect: () => ({
|
||||
bottom: 400,
|
||||
height: 300,
|
||||
left: 200,
|
||||
right: 600,
|
||||
top: 100,
|
||||
width: 400,
|
||||
}),
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 400,
|
||||
height: 300,
|
||||
left: 200,
|
||||
right: 600,
|
||||
top: 100,
|
||||
width: 400,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return correct visible rect when element is partially off-screen at the top', () => {
|
||||
const element = {
|
||||
getBoundingClientRect: () => ({
|
||||
bottom: 200,
|
||||
height: 250,
|
||||
left: 100,
|
||||
right: 500,
|
||||
top: -50,
|
||||
width: 400,
|
||||
}),
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 200,
|
||||
height: 200,
|
||||
left: 100,
|
||||
right: 500,
|
||||
top: 0,
|
||||
width: 400,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return correct visible rect when element is partially off-screen at the right', () => {
|
||||
const element = {
|
||||
getBoundingClientRect: () => ({
|
||||
bottom: 400,
|
||||
height: 300,
|
||||
left: 800,
|
||||
right: 1200,
|
||||
top: 100,
|
||||
width: 400,
|
||||
}),
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 400,
|
||||
height: 300,
|
||||
left: 800,
|
||||
right: 1000,
|
||||
top: 100,
|
||||
width: 200,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return all zeros when element is completely off-screen', () => {
|
||||
const element = {
|
||||
getBoundingClientRect: () => ({
|
||||
bottom: 1200,
|
||||
height: 300,
|
||||
left: 1100,
|
||||
right: 1400,
|
||||
top: 900,
|
||||
width: 300,
|
||||
}),
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getLayoutScrollElement', () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('should return the layout scroll element', () => {
|
||||
const element = document.createElement('div');
|
||||
element.id = ELEMENT_ID_LAYOUT_SCROLL;
|
||||
document.body.append(element);
|
||||
|
||||
expect(getLayoutScrollElement()).toBe(element);
|
||||
});
|
||||
|
||||
it('should return null when the layout scroll element is missing', () => {
|
||||
expect(getLayoutScrollElement()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('needsScrollbar', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should check scrollbar state from target element', () => {
|
||||
const element = document.createElement('div');
|
||||
vi.spyOn(element, 'clientHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(element, 'scrollHeight', 'get').mockReturnValue(120);
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
overflowY: 'auto',
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
expect(needsScrollbar(element)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false when target content does not overflow', () => {
|
||||
const element = document.createElement('div');
|
||||
vi.spyOn(element, 'clientHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(element, 'scrollHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
overflowY: 'auto',
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
expect(needsScrollbar(element)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['clip', 'hidden'])(
|
||||
'should ignore %s overflow targets',
|
||||
(overflowY) => {
|
||||
const element = document.createElement('div');
|
||||
vi.spyOn(element, 'clientHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(element, 'scrollHeight', 'get').mockReturnValue(120);
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
overflowY,
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
expect(needsScrollbar(element)).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('should fall back to document scrollbar state', () => {
|
||||
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockReturnValue(
|
||||
120,
|
||||
);
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
overflowY: 'auto',
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
expect(needsScrollbar()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,183 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
getFirstNonNullOrUndefined,
|
||||
isBoolean,
|
||||
isEmpty,
|
||||
isHttpUrl,
|
||||
isObject,
|
||||
isUndefined,
|
||||
isWindow,
|
||||
} from '../inference';
|
||||
|
||||
describe('isHttpUrl', () => {
|
||||
it("should return true when given 'http://example.com'", () => {
|
||||
expect(isHttpUrl('http://example.com')).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true when given 'https://example.com'", () => {
|
||||
expect(isHttpUrl('https://example.com')).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when given 'ftp://example.com'", () => {
|
||||
expect(isHttpUrl('ftp://example.com')).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when given 'example.com'", () => {
|
||||
expect(isHttpUrl('example.com')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isUndefined', () => {
|
||||
it('isUndefined should return true for undefined values', () => {
|
||||
expect(isUndefined()).toBe(true);
|
||||
});
|
||||
|
||||
it('isUndefined should return false for null values', () => {
|
||||
expect(isUndefined(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('isUndefined should return false for defined values', () => {
|
||||
expect(isUndefined(0)).toBe(false);
|
||||
expect(isUndefined('')).toBe(false);
|
||||
expect(isUndefined(false)).toBe(false);
|
||||
});
|
||||
|
||||
it('isUndefined should return false for objects and arrays', () => {
|
||||
expect(isUndefined({})).toBe(false);
|
||||
expect(isUndefined([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isEmpty', () => {
|
||||
it('should return true for empty string', () => {
|
||||
expect(isEmpty('')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for empty array', () => {
|
||||
expect(isEmpty([])).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for empty object', () => {
|
||||
expect(isEmpty({})).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-empty string', () => {
|
||||
expect(isEmpty('hello')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for non-empty array', () => {
|
||||
expect(isEmpty([1, 2, 3])).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for non-empty object', () => {
|
||||
expect(isEmpty({ a: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true for null or undefined', () => {
|
||||
expect(isEmpty(null)).toBe(true);
|
||||
expect(isEmpty()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for number or boolean', () => {
|
||||
expect(isEmpty(0)).toBe(false);
|
||||
expect(isEmpty(true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isWindow', () => {
|
||||
it('should return true for the window object', () => {
|
||||
expect(isWindow(window)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for other objects', () => {
|
||||
expect(isWindow({})).toBe(false);
|
||||
expect(isWindow([])).toBe(false);
|
||||
expect(isWindow(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBoolean', () => {
|
||||
it('should return true for boolean values', () => {
|
||||
expect(isBoolean(true)).toBe(true);
|
||||
expect(isBoolean(false)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-boolean values', () => {
|
||||
expect(isBoolean(null)).toBe(false);
|
||||
expect(isBoolean(42)).toBe(false);
|
||||
expect(isBoolean('string')).toBe(false);
|
||||
expect(isBoolean({})).toBe(false);
|
||||
expect(isBoolean([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isObject', () => {
|
||||
it('should return true for objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-objects', () => {
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject('string')).toBe(false);
|
||||
expect(isObject(true)).toBe(false);
|
||||
expect(isObject([1, 2, 3])).toBe(true);
|
||||
expect(isObject(new Date())).toBe(true);
|
||||
expect(isObject(/regex/)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFirstNonNullOrUndefined', () => {
|
||||
describe('getFirstNonNullOrUndefined', () => {
|
||||
it('should return the first non-null and non-undefined value for a number array', () => {
|
||||
expect(getFirstNonNullOrUndefined<number>(undefined, null, 0, 42)).toBe(
|
||||
0,
|
||||
);
|
||||
expect(getFirstNonNullOrUndefined<number>(null, undefined, 42, 123)).toBe(
|
||||
42,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return the first non-null and non-undefined value for a string array', () => {
|
||||
expect(
|
||||
getFirstNonNullOrUndefined<string>(undefined, null, '', 'hello'),
|
||||
).toBe('');
|
||||
expect(
|
||||
getFirstNonNullOrUndefined<string>(null, undefined, 'test', 'world'),
|
||||
).toBe('test');
|
||||
});
|
||||
|
||||
it('should return undefined if all values are null or undefined', () => {
|
||||
expect(getFirstNonNullOrUndefined(undefined, null)).toBeUndefined();
|
||||
expect(getFirstNonNullOrUndefined(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should work with a single value', () => {
|
||||
expect(getFirstNonNullOrUndefined(42)).toBe(42);
|
||||
expect(getFirstNonNullOrUndefined()).toBeUndefined();
|
||||
expect(getFirstNonNullOrUndefined(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle mixed types correctly', () => {
|
||||
expect(
|
||||
getFirstNonNullOrUndefined<number | object | string>(
|
||||
undefined,
|
||||
null,
|
||||
'test',
|
||||
123,
|
||||
{ key: 'value' },
|
||||
),
|
||||
).toBe('test');
|
||||
expect(
|
||||
getFirstNonNullOrUndefined<number | object | string>(
|
||||
null,
|
||||
undefined,
|
||||
[1, 2, 3],
|
||||
'string',
|
||||
),
|
||||
).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
capitalizeFirstLetter,
|
||||
kebabToCamelCase,
|
||||
toCamelCase,
|
||||
toLowerCaseFirstLetter,
|
||||
} from '../letter';
|
||||
|
||||
describe('capitalizeFirstLetter', () => {
|
||||
it('should capitalize the first letter of a string', () => {
|
||||
expect(capitalizeFirstLetter('hello')).toBe('Hello');
|
||||
expect(capitalizeFirstLetter('world')).toBe('World');
|
||||
});
|
||||
|
||||
it('should handle empty strings', () => {
|
||||
expect(capitalizeFirstLetter('')).toBe('');
|
||||
});
|
||||
|
||||
it('should handle single character strings', () => {
|
||||
expect(capitalizeFirstLetter('a')).toBe('A');
|
||||
expect(capitalizeFirstLetter('b')).toBe('B');
|
||||
});
|
||||
|
||||
it('should not change the case of other characters', () => {
|
||||
expect(capitalizeFirstLetter('hElLo')).toBe('HElLo');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toLowerCaseFirstLetter', () => {
|
||||
it('should convert the first letter to lowercase', () => {
|
||||
expect(toLowerCaseFirstLetter('CommonAppName')).toBe('commonAppName');
|
||||
expect(toLowerCaseFirstLetter('AnotherKeyExample')).toBe(
|
||||
'anotherKeyExample',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return the same string if the first letter is already lowercase', () => {
|
||||
expect(toLowerCaseFirstLetter('alreadyLowerCase')).toBe('alreadyLowerCase');
|
||||
});
|
||||
|
||||
it('should handle empty strings', () => {
|
||||
expect(toLowerCaseFirstLetter('')).toBe('');
|
||||
});
|
||||
|
||||
it('should handle single character strings', () => {
|
||||
expect(toLowerCaseFirstLetter('A')).toBe('a');
|
||||
expect(toLowerCaseFirstLetter('a')).toBe('a');
|
||||
});
|
||||
|
||||
it('should handle strings with only one uppercase letter', () => {
|
||||
expect(toLowerCaseFirstLetter('A')).toBe('a');
|
||||
});
|
||||
|
||||
it('should handle strings with special characters', () => {
|
||||
expect(toLowerCaseFirstLetter('!Special')).toBe('!Special');
|
||||
expect(toLowerCaseFirstLetter('123Number')).toBe('123Number');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toCamelCase', () => {
|
||||
it('should return the key if parentKey is empty', () => {
|
||||
expect(toCamelCase('child', '')).toBe('child');
|
||||
});
|
||||
|
||||
it('should combine parentKey and key in camel case', () => {
|
||||
expect(toCamelCase('child', 'parent')).toBe('parentChild');
|
||||
});
|
||||
|
||||
it('should handle empty key and parentKey', () => {
|
||||
expect(toCamelCase('', '')).toBe('');
|
||||
});
|
||||
|
||||
it('should handle key with capital letters', () => {
|
||||
expect(toCamelCase('Child', 'parent')).toBe('parentChild');
|
||||
expect(toCamelCase('Child', 'Parent')).toBe('ParentChild');
|
||||
});
|
||||
});
|
||||
|
||||
describe('kebabToCamelCase', () => {
|
||||
it('should convert kebab-case to camelCase correctly', () => {
|
||||
expect(kebabToCamelCase('my-component-name')).toBe('myComponentName');
|
||||
});
|
||||
|
||||
it('should handle multiple consecutive hyphens', () => {
|
||||
expect(kebabToCamelCase('my--component--name')).toBe('myComponentName');
|
||||
});
|
||||
|
||||
it('should trim leading and trailing hyphens', () => {
|
||||
expect(kebabToCamelCase('-my-component-name-')).toBe('myComponentName');
|
||||
});
|
||||
|
||||
it('should preserve the case of the first word', () => {
|
||||
expect(kebabToCamelCase('My-component-name')).toBe('MyComponentName');
|
||||
});
|
||||
|
||||
it('should convert a single word correctly', () => {
|
||||
expect(kebabToCamelCase('component')).toBe('component');
|
||||
});
|
||||
|
||||
it('should return an empty string if input is empty', () => {
|
||||
expect(kebabToCamelCase('')).toBe('');
|
||||
});
|
||||
|
||||
it('should handle strings with no hyphens', () => {
|
||||
expect(kebabToCamelCase('mycomponentname')).toBe('mycomponentname');
|
||||
});
|
||||
|
||||
it('should handle strings with only hyphens', () => {
|
||||
expect(kebabToCamelCase('---')).toBe('');
|
||||
});
|
||||
|
||||
it('should handle mixed case inputs', () => {
|
||||
expect(kebabToCamelCase('my-Component-Name')).toBe('myComponentName');
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { loadScript } from '../resources';
|
||||
|
||||
describe('loadScript', () => {
|
||||
beforeEach(() => {
|
||||
// 每个测试前清空 head,保证环境干净
|
||||
document.head.innerHTML = '';
|
||||
});
|
||||
|
||||
it('should resolve when the script loads successfully', async () => {
|
||||
// happy-dom v20+ auto-fires 'load' via handleDisabledFileLoadingAsSuccess
|
||||
const promise = loadScript('/test-script.js');
|
||||
|
||||
const script = document.querySelector(
|
||||
'script[src="/test-script.js"]',
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
|
||||
await expect(promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not insert duplicate script and resolve immediately if already loaded', async () => {
|
||||
// 先手动插入一个相同 src 的 script
|
||||
const existing = document.createElement('script');
|
||||
existing.src = 'bar.js';
|
||||
document.head.append(existing);
|
||||
|
||||
// 再次调用
|
||||
const promise = loadScript('bar.js');
|
||||
|
||||
// 立即 resolve
|
||||
await expect(promise).resolves.toBeUndefined();
|
||||
|
||||
// head 中只保留一个
|
||||
const scripts = document.head.querySelectorAll('script[src="bar.js"]');
|
||||
expect(scripts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should reject when the script fails to load', async () => {
|
||||
let capturedScript: HTMLScriptElement | null = null;
|
||||
|
||||
// 拦截 append,捕获 script 元素但不插入 DOM,
|
||||
// 防止 happy-dom v20+ 自动触发 load 事件
|
||||
const appendSpy = vi
|
||||
.spyOn(document.head, 'append')
|
||||
.mockImplementation((...nodes) => {
|
||||
for (const node of nodes) {
|
||||
if (node instanceof HTMLScriptElement) {
|
||||
capturedScript = node;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const promise = loadScript('error.js');
|
||||
|
||||
appendSpy.mockRestore();
|
||||
|
||||
expect(capturedScript).toBeTruthy();
|
||||
if (!capturedScript) {
|
||||
throw new Error('Expected the captured script element to exist');
|
||||
}
|
||||
capturedScript.dispatchEvent(new Event('error'));
|
||||
|
||||
await expect(promise).rejects.toThrow('Failed to load script: error.js');
|
||||
});
|
||||
|
||||
it('should handle multiple concurrent calls and only insert one script tag', async () => {
|
||||
const p1 = loadScript('/test-script.js');
|
||||
const p2 = loadScript('/test-script.js');
|
||||
|
||||
// happy-dom v20+ auto-fires 'load',两个 promise 都应该 resolve
|
||||
await expect(p1).resolves.toBeUndefined();
|
||||
await expect(p2).resolves.toBeUndefined();
|
||||
|
||||
// 只插入一次
|
||||
const scripts = document.head.querySelectorAll(
|
||||
'script[src="/test-script.js"]',
|
||||
);
|
||||
expect(scripts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,107 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createStack, Stack } from '../stack';
|
||||
|
||||
describe('stack', () => {
|
||||
let stack: Stack<number>;
|
||||
|
||||
beforeEach(() => {
|
||||
stack = new Stack<number>();
|
||||
});
|
||||
|
||||
it('push & size should work', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('peek should return top element without removing it', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.peek()).toBe(2);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('pop should remove and return top element', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.pop()).toBe(2);
|
||||
expect(stack.size).toBe(1);
|
||||
expect(stack.peek()).toBe(1);
|
||||
});
|
||||
|
||||
it('pop on empty stack should return undefined', () => {
|
||||
expect(stack.pop()).toBeUndefined();
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clear should remove all elements', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
stack.clear();
|
||||
|
||||
expect(stack.size).toBe(0);
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('toArray should return a shallow copy', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
const arr = stack.toArray();
|
||||
arr.push(3);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
expect(stack.toArray()).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('dedup should remove existing item before push', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2, 1]);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('dedup = false should allow duplicate items', () => {
|
||||
const s = new Stack<number>(false);
|
||||
|
||||
s.push(1, 1, 1);
|
||||
|
||||
expect(s.toArray()).toEqual([1, 1, 1]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('remove should delete all matching items', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
stack.remove(1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2]);
|
||||
expect(stack.size).toBe(1);
|
||||
});
|
||||
|
||||
it('maxSize should limit stack capacity', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 4);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3, 4]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('dedup + maxSize should work together', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 2); // 去重并重新入栈
|
||||
|
||||
expect(s.toArray()).toEqual([1, 3, 2]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('createStack should create a stack instance', () => {
|
||||
const s = createStack<number>(true, 2);
|
||||
|
||||
s.push(1, 2, 3);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { StateHandler } from '../state-handler';
|
||||
|
||||
describe('stateHandler', () => {
|
||||
it('should resolve when condition is set to true', async () => {
|
||||
const handler = new StateHandler();
|
||||
|
||||
// 模拟异步设置 condition 为 true
|
||||
setTimeout(() => {
|
||||
handler.setConditionTrue(); // 明确触发 condition 为 true
|
||||
}, 10);
|
||||
|
||||
// 等待条件被设置为 true
|
||||
await handler.waitForCondition();
|
||||
expect(handler.isConditionTrue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should resolve immediately if condition is already true', async () => {
|
||||
const handler = new StateHandler();
|
||||
handler.setConditionTrue(); // 提前设置为 true
|
||||
|
||||
// 立即 resolve,因为 condition 已经是 true
|
||||
await handler.waitForCondition();
|
||||
expect(handler.isConditionTrue()).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject when condition is set to false after waiting', async () => {
|
||||
const handler = new StateHandler();
|
||||
|
||||
// 模拟异步设置 condition 为 false
|
||||
setTimeout(() => {
|
||||
handler.setConditionFalse(); // 明确触发 condition 为 false
|
||||
}, 10);
|
||||
|
||||
// 等待过程中,期望 Promise 被 reject
|
||||
await expect(handler.waitForCondition()).rejects.toThrow(
|
||||
'Condition was set to false',
|
||||
);
|
||||
expect(handler.isConditionTrue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should reset condition to false', () => {
|
||||
const handler = new StateHandler();
|
||||
handler.setConditionTrue(); // 设置为 true
|
||||
handler.reset(); // 重置为 false
|
||||
|
||||
expect(handler.isConditionTrue()).toBe(false);
|
||||
});
|
||||
|
||||
it('should resolve when condition is set to true after reset', async () => {
|
||||
const handler = new StateHandler();
|
||||
handler.reset(); // 确保初始为 false
|
||||
|
||||
setTimeout(() => {
|
||||
handler.setConditionTrue(); // 重置后设置为 true
|
||||
}, 10);
|
||||
|
||||
await handler.waitForCondition();
|
||||
expect(handler.isConditionTrue()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,196 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { filterTree, mapTree, traverseTreeValues } from '../tree';
|
||||
|
||||
describe('traverseTreeValues', () => {
|
||||
interface Node {
|
||||
children?: Node[];
|
||||
name: string;
|
||||
}
|
||||
|
||||
type NodeValue = string;
|
||||
|
||||
const sampleTree: Node[] = [
|
||||
{
|
||||
name: 'A',
|
||||
children: [
|
||||
{ name: 'B' },
|
||||
{
|
||||
name: 'C',
|
||||
children: [{ name: 'D' }, { name: 'E' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'F',
|
||||
children: [
|
||||
{ name: 'G' },
|
||||
{
|
||||
name: 'H',
|
||||
children: [{ name: 'I' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
it('traverses tree and returns all node values', () => {
|
||||
const values = traverseTreeValues<Node, NodeValue>(
|
||||
sampleTree,
|
||||
(node) => node.name,
|
||||
{
|
||||
childProps: 'children',
|
||||
},
|
||||
);
|
||||
expect(values).toEqual(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']);
|
||||
});
|
||||
|
||||
it('handles empty tree', () => {
|
||||
const values = traverseTreeValues<Node, NodeValue>([], (node) => node.name);
|
||||
expect(values).toEqual([]);
|
||||
});
|
||||
|
||||
it('handles tree with only root node', () => {
|
||||
const rootNode = { name: 'A' };
|
||||
const values = traverseTreeValues<Node, NodeValue>(
|
||||
[rootNode],
|
||||
(node) => node.name,
|
||||
);
|
||||
expect(values).toEqual(['A']);
|
||||
});
|
||||
|
||||
it('handles tree with only leaf nodes', () => {
|
||||
const leafNodes = [{ name: 'A' }, { name: 'B' }, { name: 'C' }];
|
||||
const values = traverseTreeValues<Node, NodeValue>(
|
||||
leafNodes,
|
||||
(node) => node.name,
|
||||
);
|
||||
expect(values).toEqual(['A', 'B', 'C']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterTree', () => {
|
||||
const tree = [
|
||||
{
|
||||
id: 1,
|
||||
children: [
|
||||
{ id: 2 },
|
||||
{ id: 3, children: [{ id: 4 }, { id: 5 }, { id: 6 }] },
|
||||
{ id: 7 },
|
||||
],
|
||||
},
|
||||
{ id: 8, children: [{ id: 9 }, { id: 10 }] },
|
||||
{ id: 11 },
|
||||
];
|
||||
|
||||
it('should return all nodes when condition is always true', () => {
|
||||
const result = filterTree(tree, () => true, { childProps: 'children' });
|
||||
expect(result).toEqual(tree);
|
||||
});
|
||||
|
||||
it('should return only root nodes when condition is always false', () => {
|
||||
const result = filterTree(tree, () => false);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return nodes with even id values', () => {
|
||||
const result = filterTree(tree, (node) => node.id % 2 === 0);
|
||||
expect(result).toEqual([{ id: 8, children: [{ id: 10 }] }]);
|
||||
});
|
||||
|
||||
it('should return nodes with odd id values and their ancestors', () => {
|
||||
const result = filterTree(tree, (node) => node.id % 2 === 1);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
id: 1,
|
||||
children: [{ id: 3, children: [{ id: 5 }] }, { id: 7 }],
|
||||
},
|
||||
{ id: 11 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should return nodes with "leaf" in their name', () => {
|
||||
const tree = [
|
||||
{
|
||||
name: 'root',
|
||||
children: [
|
||||
{ name: 'leaf 1' },
|
||||
{
|
||||
name: 'branch',
|
||||
children: [{ name: 'leaf 2' }, { name: 'leaf 3' }],
|
||||
},
|
||||
{ name: 'leaf 4' },
|
||||
],
|
||||
},
|
||||
];
|
||||
const result = filterTree(
|
||||
tree,
|
||||
(node) => node.name.includes('leaf') || node.name === 'root',
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
name: 'root',
|
||||
children: [{ name: 'leaf 1' }, { name: 'leaf 4' }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapTree', () => {
|
||||
it('map infinite depth tree using mapTree', () => {
|
||||
const tree = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'node1',
|
||||
children: [
|
||||
{ id: 2, name: 'node2' },
|
||||
{ id: 3, name: 'node3' },
|
||||
{
|
||||
id: 4,
|
||||
name: 'node4',
|
||||
children: [
|
||||
{
|
||||
id: 5,
|
||||
name: 'node5',
|
||||
children: [
|
||||
{ id: 6, name: 'node6' },
|
||||
{ id: 7, name: 'node7' },
|
||||
],
|
||||
},
|
||||
{ id: 8, name: 'node8' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const newTree = mapTree(tree, (node) => ({
|
||||
...node,
|
||||
name: `${node.name}-new`,
|
||||
}));
|
||||
|
||||
expect(newTree).toEqual([
|
||||
{
|
||||
id: 1,
|
||||
name: 'node1-new',
|
||||
children: [
|
||||
{ id: 2, name: 'node2-new' },
|
||||
{ id: 3, name: 'node3-new' },
|
||||
{
|
||||
id: 4,
|
||||
name: 'node4-new',
|
||||
children: [
|
||||
{
|
||||
id: 5,
|
||||
name: 'node5-new',
|
||||
children: [
|
||||
{ id: 6, name: 'node6-new' },
|
||||
{ id: 7, name: 'node7-new' },
|
||||
],
|
||||
},
|
||||
{ id: 8, name: 'node8-new' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { uniqueByField } from '../unique';
|
||||
|
||||
describe('uniqueByField', () => {
|
||||
it('should return an array with unique items based on id field', () => {
|
||||
const items = [
|
||||
{ id: 1, name: 'Item 1' },
|
||||
{ id: 2, name: 'Item 2' },
|
||||
{ id: 3, name: 'Item 3' },
|
||||
{ id: 1, name: 'Duplicate Item' },
|
||||
];
|
||||
|
||||
const uniqueItems = uniqueByField(items, 'id');
|
||||
|
||||
expect(uniqueItems).toHaveLength(3);
|
||||
expect(uniqueItems).toEqual([
|
||||
{ id: 1, name: 'Item 1' },
|
||||
{ id: 2, name: 'Item 2' },
|
||||
{ id: 3, name: 'Item 3' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should return an empty array when input array is empty', () => {
|
||||
const items: any[] = []; // Empty array
|
||||
|
||||
const uniqueItems = uniqueByField(items, 'id');
|
||||
|
||||
// Assert expected results
|
||||
expect(uniqueItems).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle arrays with only one item correctly', () => {
|
||||
const items = [{ id: 1, name: 'Item 1' }];
|
||||
|
||||
const uniqueItems = uniqueByField(items, 'id');
|
||||
|
||||
// Assert expected results
|
||||
expect(uniqueItems).toHaveLength(1);
|
||||
expect(uniqueItems).toEqual([{ id: 1, name: 'Item 1' }]);
|
||||
});
|
||||
|
||||
it('should preserve the order of the first occurrence of each item', () => {
|
||||
const items = [
|
||||
{ id: 2, name: 'Item 2' },
|
||||
{ id: 1, name: 'Item 1' },
|
||||
{ id: 3, name: 'Item 3' },
|
||||
{ id: 1, name: 'Duplicate Item' },
|
||||
];
|
||||
|
||||
const uniqueItems = uniqueByField(items, 'id');
|
||||
|
||||
// Assert expected results (order of first occurrences preserved)
|
||||
expect(uniqueItems).toEqual([
|
||||
{ id: 2, name: 'Item 2' },
|
||||
{ id: 1, name: 'Item 1' },
|
||||
{ id: 3, name: 'Item 3' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import { expect, it } from 'vitest';
|
||||
|
||||
import { updateCSSVariables } from '../update-css-variables';
|
||||
|
||||
it('updateCSSVariables should update CSS variables in :root selector', () => {
|
||||
// 模拟初始的内联样式表内容
|
||||
const initialStyleContent = ':root { --primaryColor: red; }';
|
||||
document.head.innerHTML = `<style id="custom-styles">${initialStyleContent}</style>`;
|
||||
|
||||
// 要更新的CSS变量和它们的新值
|
||||
const updatedVariables = {
|
||||
fontSize: '16px',
|
||||
primaryColor: 'blue',
|
||||
secondaryColor: 'green',
|
||||
};
|
||||
|
||||
// 调用函数来更新CSS变量
|
||||
updateCSSVariables(updatedVariables, 'custom-styles');
|
||||
|
||||
// 获取更新后的样式内容
|
||||
const styleElement = document.querySelector('#custom-styles');
|
||||
const updatedStyleContent = styleElement ? styleElement.textContent : '';
|
||||
|
||||
// 检查更新后的样式内容是否包含正确的更新值
|
||||
expect(
|
||||
updatedStyleContent?.includes('primaryColor: blue;') &&
|
||||
updatedStyleContent?.includes('secondaryColor: green;') &&
|
||||
updatedStyleContent?.includes('fontSize: 16px;'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('updateCSSVariables should support a custom selector', () => {
|
||||
document.head.innerHTML = `<style id="tdesign-styles"></style>`;
|
||||
|
||||
// 使用自定义选择器(如 TDesign 的 theme-mode 选择器)更新 CSS 变量
|
||||
updateCSSVariables(
|
||||
{ '--td-brand-color': 'rgb(0, 82, 217)' },
|
||||
'tdesign-styles',
|
||||
":root[theme-mode='dark']",
|
||||
);
|
||||
|
||||
const styleElement = document.querySelector('#tdesign-styles');
|
||||
const content = styleElement?.textContent ?? '';
|
||||
|
||||
// 选择器与变量都应正确写入
|
||||
expect(content.startsWith(":root[theme-mode='dark'] {")).toBe(true);
|
||||
expect(content.includes('--td-brand-color: rgb(0, 82, 217);')).toBe(true);
|
||||
});
|
||||
@@ -1,158 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { bindMethods, getNestedValue } from '../util';
|
||||
|
||||
class TestClass {
|
||||
public value: string;
|
||||
|
||||
constructor(value: string) {
|
||||
this.value = value;
|
||||
bindMethods(this); // 调用通用方法
|
||||
}
|
||||
|
||||
getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
setValue(newValue: string) {
|
||||
this.value = newValue;
|
||||
}
|
||||
}
|
||||
|
||||
describe('bindMethods', () => {
|
||||
it('should bind methods to the instance correctly', () => {
|
||||
const instance = new TestClass('initial');
|
||||
|
||||
// 解构方法
|
||||
const { getValue } = instance;
|
||||
|
||||
// 检查 getValue 是否能正确调用,并且 this 绑定了 instance
|
||||
expect(getValue()).toBe('initial');
|
||||
});
|
||||
|
||||
it('should bind multiple methods', () => {
|
||||
const instance = new TestClass('initial');
|
||||
|
||||
const { getValue, setValue } = instance;
|
||||
|
||||
// 检查 getValue 和 setValue 方法是否正确绑定了 this
|
||||
setValue('newValue');
|
||||
expect(getValue()).toBe('newValue');
|
||||
});
|
||||
|
||||
it('should not bind non-function properties', () => {
|
||||
const instance = new TestClass('initial');
|
||||
|
||||
// 检查普通属性是否保持原样
|
||||
expect(instance.value).toBe('initial');
|
||||
});
|
||||
|
||||
it('should not bind constructor method', () => {
|
||||
const instance = new TestClass('test');
|
||||
|
||||
// 检查 constructor 是否没有被绑定
|
||||
expect(instance.constructor.name).toBe('TestClass');
|
||||
});
|
||||
|
||||
it('should not bind getter/setter properties', () => {
|
||||
class TestWithGetterSetter {
|
||||
get value() {
|
||||
return this._value;
|
||||
}
|
||||
|
||||
set value(newValue: string) {
|
||||
this._value = newValue;
|
||||
}
|
||||
|
||||
private _value: string = 'test';
|
||||
|
||||
constructor() {
|
||||
bindMethods(this);
|
||||
}
|
||||
}
|
||||
|
||||
const instance = new TestWithGetterSetter();
|
||||
const { value } = instance;
|
||||
|
||||
// Getter 和 setter 不应被绑定
|
||||
expect(value).toBe('test');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNestedValue', () => {
|
||||
interface UserProfile {
|
||||
age: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface UserSettings {
|
||||
theme: string;
|
||||
}
|
||||
|
||||
interface Data {
|
||||
user: {
|
||||
profile: UserProfile;
|
||||
settings: UserSettings;
|
||||
};
|
||||
}
|
||||
|
||||
const data: Data = {
|
||||
user: {
|
||||
profile: {
|
||||
age: 25,
|
||||
name: 'Alice',
|
||||
},
|
||||
settings: {
|
||||
theme: 'dark',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it('should get a nested value when the path is valid', () => {
|
||||
const result = getNestedValue(data, 'user.profile.name');
|
||||
expect(result).toBe('Alice');
|
||||
});
|
||||
|
||||
it('should return undefined for non-existent property', () => {
|
||||
const result = getNestedValue(data, 'user.profile.gender');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when accessing a non-existent deep path', () => {
|
||||
const result = getNestedValue(data, 'user.nonexistent.field');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined if a middle level is undefined', () => {
|
||||
const result = getNestedValue({ user: undefined }, 'user.profile.name');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return the correct value for a nested setting', () => {
|
||||
const result = getNestedValue(data, 'user.settings.theme');
|
||||
expect(result).toBe('dark');
|
||||
});
|
||||
|
||||
it('should work for a single-level path', () => {
|
||||
const result = getNestedValue({ a: 1, b: 2 }, 'b');
|
||||
expect(result).toBe(2);
|
||||
});
|
||||
|
||||
it('should throw if path is empty', () => {
|
||||
expect(() => getNestedValue(data, '')).toThrow(
|
||||
'Path must be a non-empty string',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle paths with array indexes', () => {
|
||||
const complexData = { list: [{ name: 'Item1' }, { name: 'Item2' }] };
|
||||
const result = getNestedValue(complexData, 'list.1.name');
|
||||
expect(result).toBe('Item2');
|
||||
});
|
||||
|
||||
it('should return undefined when accessing an out-of-bounds array index', () => {
|
||||
const complexData = { list: [{ name: 'Item1' }] };
|
||||
const result = getNestedValue(complexData, 'list.2.name');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { openWindow } from '../window';
|
||||
|
||||
describe('openWindow', () => {
|
||||
// 保存原始的 window.open 函数
|
||||
let originalOpen: typeof window.open;
|
||||
|
||||
beforeEach(() => {
|
||||
originalOpen = window.open;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.open = originalOpen;
|
||||
});
|
||||
|
||||
it('should call window.open with correct arguments', () => {
|
||||
const url = 'https://example.com';
|
||||
const options = { noopener: true, noreferrer: true, target: '_blank' };
|
||||
|
||||
window.open = vi.fn();
|
||||
|
||||
// 调用函数
|
||||
openWindow(url, options);
|
||||
|
||||
// 验证 window.open 是否被正确地调用
|
||||
expect(window.open).toHaveBeenCalledWith(
|
||||
url,
|
||||
options.target,
|
||||
'noopener=yes,noreferrer=yes',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import type { App } from 'vue';
|
||||
|
||||
import { createApp, h } from 'vue';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useLayoutContentStyle } from '../use-layout-style';
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('useLayoutContentStyle', () => {
|
||||
it('positions overlays without observing content size', () => {
|
||||
const resizeObserver = vi.fn();
|
||||
vi.stubGlobal('ResizeObserver', resizeObserver);
|
||||
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp({
|
||||
setup() {
|
||||
const { contentElement, overlayStyle } = useLayoutContentStyle();
|
||||
return () =>
|
||||
h('main', { ref: contentElement }, [
|
||||
h('div', { style: overlayStyle.value }),
|
||||
]);
|
||||
},
|
||||
});
|
||||
activeApp.mount(host);
|
||||
|
||||
const overlay = host.querySelector<HTMLElement>('main > div');
|
||||
expect(overlay).not.toBeNull();
|
||||
if (!overlay) throw new Error('overlay element was not rendered');
|
||||
|
||||
expect(resizeObserver).not.toHaveBeenCalled();
|
||||
expect(overlay.style.position).toBe('absolute');
|
||||
expect(`${overlay.style.inset}`).toBe('0');
|
||||
});
|
||||
});
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
import type { App } from 'vue';
|
||||
|
||||
import { createApp } from 'vue';
|
||||
|
||||
import { CSS_VARIABLE_LAYOUT_VIEWPORT_HEIGHT } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useLayoutViewportHeight } from '../use-layout-viewport-height';
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
function stubDvhSupport(supported: boolean) {
|
||||
vi.stubGlobal('CSS', {
|
||||
supports: vi.fn((property: string, value: string) => {
|
||||
return supported && property === 'height' && value === '1dvh';
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function mountViewportHeight() {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp({
|
||||
setup() {
|
||||
useLayoutViewportHeight();
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
activeApp.mount(host);
|
||||
}
|
||||
|
||||
function getViewportHeightVar() {
|
||||
return document.documentElement.style.getPropertyValue(
|
||||
CSS_VARIABLE_LAYOUT_VIEWPORT_HEIGHT,
|
||||
);
|
||||
}
|
||||
|
||||
async function flushAnimationFrame() {
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
document.documentElement.style.removeProperty(
|
||||
CSS_VARIABLE_LAYOUT_VIEWPORT_HEIGHT,
|
||||
);
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useLayoutViewportHeight', () => {
|
||||
it('does not write the CSS variable when dvh is supported', () => {
|
||||
const resizeObserver = vi.fn();
|
||||
const addEventListener = vi.spyOn(window, 'addEventListener');
|
||||
vi.stubGlobal('ResizeObserver', resizeObserver);
|
||||
stubDvhSupport(true);
|
||||
|
||||
mountViewportHeight();
|
||||
|
||||
expect(getViewportHeightVar()).toBe('');
|
||||
expect(resizeObserver).not.toHaveBeenCalled();
|
||||
expect(addEventListener).not.toHaveBeenCalledWith(
|
||||
'resize',
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('writes innerHeight when dvh is unsupported', () => {
|
||||
const resizeObserver = vi.fn();
|
||||
vi.stubGlobal('ResizeObserver', resizeObserver);
|
||||
stubDvhSupport(false);
|
||||
vi.stubGlobal('visualViewport', null);
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800);
|
||||
|
||||
mountViewportHeight();
|
||||
|
||||
expect(getViewportHeightVar()).toBe('800px');
|
||||
expect(resizeObserver).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prefers visualViewport.height over innerHeight', () => {
|
||||
stubDvhSupport(false);
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800);
|
||||
const visualViewport = new EventTarget() as VisualViewport;
|
||||
Object.defineProperty(visualViewport, 'height', {
|
||||
configurable: true,
|
||||
value: 640,
|
||||
writable: true,
|
||||
});
|
||||
vi.stubGlobal('visualViewport', visualViewport);
|
||||
|
||||
mountViewportHeight();
|
||||
|
||||
expect(getViewportHeightVar()).toBe('640px');
|
||||
});
|
||||
|
||||
it('updates the CSS variable on visualViewport resize and stops after unmount', async () => {
|
||||
stubDvhSupport(false);
|
||||
const visualViewport = new EventTarget() as VisualViewport;
|
||||
Object.defineProperty(visualViewport, 'height', {
|
||||
configurable: true,
|
||||
value: 640,
|
||||
writable: true,
|
||||
});
|
||||
vi.stubGlobal('visualViewport', visualViewport);
|
||||
|
||||
mountViewportHeight();
|
||||
expect(getViewportHeightVar()).toBe('640px');
|
||||
|
||||
Object.defineProperty(visualViewport, 'height', {
|
||||
configurable: true,
|
||||
value: 520,
|
||||
writable: true,
|
||||
});
|
||||
visualViewport.dispatchEvent(new Event('resize'));
|
||||
await flushAnimationFrame();
|
||||
|
||||
expect(getViewportHeightVar()).toBe('520px');
|
||||
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
|
||||
Object.defineProperty(visualViewport, 'height', {
|
||||
configurable: true,
|
||||
value: 400,
|
||||
writable: true,
|
||||
});
|
||||
visualViewport.dispatchEvent(new Event('resize'));
|
||||
await flushAnimationFrame();
|
||||
|
||||
expect(getViewportHeightVar()).toBe('520px');
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
import type { App, WritableComputedRef } from 'vue';
|
||||
|
||||
import { createApp, nextTick } from 'vue';
|
||||
|
||||
import { ELEMENT_ID_LAYOUT_SCROLL } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { SCROLL_FIXED_CLASS, useScrollLock } from '../use-scroll-lock';
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
function createScrollableElement(id?: string) {
|
||||
const element = document.createElement('div');
|
||||
if (id) {
|
||||
element.id = id;
|
||||
}
|
||||
element.style.overflow = 'auto';
|
||||
Object.defineProperties(element, {
|
||||
clientHeight: { configurable: true, value: 100 },
|
||||
scrollHeight: { configurable: true, value: 120 },
|
||||
});
|
||||
document.body.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function mountScrollLock(options?: { immediate?: boolean }) {
|
||||
let scrollLock: undefined | WritableComputedRef<boolean>;
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp({
|
||||
setup() {
|
||||
scrollLock = useScrollLock(options);
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
activeApp.mount(host);
|
||||
|
||||
if (!scrollLock) {
|
||||
throw new Error('useScrollLock was not initialized');
|
||||
}
|
||||
return scrollLock;
|
||||
}
|
||||
|
||||
async function flushMountedLock() {
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
document.body.style.cssText = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useScrollLock', () => {
|
||||
it('should lock the layout scroll element first', async () => {
|
||||
const element = createScrollableElement(ELEMENT_ID_LAYOUT_SCROLL);
|
||||
element.style.setProperty('scrollbar-gutter', 'auto');
|
||||
const scrollLock = mountScrollLock();
|
||||
|
||||
await flushMountedLock();
|
||||
|
||||
expect(scrollLock.value).toBe(true);
|
||||
expect(element.style.overflow).toBe('hidden');
|
||||
expect(element.style.getPropertyValue('scrollbar-gutter')).toBe('stable');
|
||||
expect(document.body.style.overflow).not.toBe('hidden');
|
||||
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
|
||||
expect(element.style.overflow).toBe('auto');
|
||||
expect(element.style.getPropertyValue('scrollbar-gutter')).toBe('auto');
|
||||
});
|
||||
|
||||
it('should support manual locking', async () => {
|
||||
const element = createScrollableElement(ELEMENT_ID_LAYOUT_SCROLL);
|
||||
const scrollLock = mountScrollLock({ immediate: false });
|
||||
|
||||
await flushMountedLock();
|
||||
expect(scrollLock.value).toBe(false);
|
||||
|
||||
scrollLock.value = true;
|
||||
expect(element.style.overflow).toBe('hidden');
|
||||
expect(element.style.getPropertyValue('scrollbar-gutter')).toBe('stable');
|
||||
|
||||
scrollLock.value = false;
|
||||
expect(element.style.overflow).toBe('auto');
|
||||
expect(element.style.getPropertyValue('scrollbar-gutter')).toBe('');
|
||||
});
|
||||
|
||||
it('should fall back to body and compensate fixed nodes', async () => {
|
||||
document.body.style.overflow = 'auto';
|
||||
Object.defineProperties(document.body, {
|
||||
clientHeight: { configurable: true, value: 100 },
|
||||
scrollHeight: { configurable: true, value: 120 },
|
||||
});
|
||||
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockReturnValue(
|
||||
120,
|
||||
);
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(100);
|
||||
vi.spyOn(window, 'getComputedStyle').mockReturnValue({
|
||||
overflowY: 'auto',
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
const fixedNode = document.createElement('div');
|
||||
fixedNode.className = SCROLL_FIXED_CLASS;
|
||||
fixedNode.style.transition = 'opacity 200ms';
|
||||
document.body.append(fixedNode);
|
||||
const scrollLock = mountScrollLock();
|
||||
|
||||
await flushMountedLock();
|
||||
|
||||
expect(scrollLock.value).toBe(true);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
expect(document.body.style.paddingRight).toBe('0px');
|
||||
expect(fixedNode.style.paddingRight).toBe('0px');
|
||||
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
|
||||
expect(document.body.style.overflow).toBe('auto');
|
||||
expect(document.body.style.paddingRight).toBe('');
|
||||
expect(fixedNode.style.paddingRight).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import type { SortableOptions } from 'sortablejs';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useSortable } from '../use-sortable';
|
||||
|
||||
describe('useSortable', () => {
|
||||
beforeEach(() => {
|
||||
vi.mock('sortablejs/modular/sortable.complete.esm.js', () => ({
|
||||
default: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}));
|
||||
});
|
||||
it('should call Sortable.create with the correct options', async () => {
|
||||
// Create a mock element
|
||||
const mockElement = document.createElement('div') as HTMLDivElement;
|
||||
|
||||
// Define custom options
|
||||
const customOptions: SortableOptions = {
|
||||
group: 'test-group',
|
||||
sort: false,
|
||||
};
|
||||
|
||||
// Use the useSortable function
|
||||
const { initializeSortable } = useSortable(mockElement, customOptions);
|
||||
|
||||
// Initialize sortable
|
||||
await initializeSortable();
|
||||
|
||||
// Import sortablejs to access the mocked create function
|
||||
const Sortable =
|
||||
// @ts-expect-error - This is a dynamic import
|
||||
await import('sortablejs/modular/sortable.complete.esm.js');
|
||||
|
||||
// Verify that Sortable.create was called with the correct parameters
|
||||
expect(Sortable.default.create).toHaveBeenCalledTimes(1);
|
||||
expect(Sortable.default.create).toHaveBeenCalledWith(
|
||||
mockElement,
|
||||
expect.objectContaining({
|
||||
animation: 300,
|
||||
delay: 400,
|
||||
delayOnTouchOnly: true,
|
||||
...customOptions,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,170 +0,0 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`defaultPreferences immutability test > should not modify the config object 1`] = `
|
||||
{
|
||||
"app": {
|
||||
"accessMode": "frontend",
|
||||
"authPageLayout": "panel-right",
|
||||
"checkUpdatesInterval": 1,
|
||||
"colorGrayMode": false,
|
||||
"colorWeakMode": false,
|
||||
"compact": false,
|
||||
"contentCompact": "wide",
|
||||
"contentCompactWidth": 1200,
|
||||
"contentPadding": 0,
|
||||
"contentPaddingBottom": 0,
|
||||
"contentPaddingLeft": 0,
|
||||
"contentPaddingRight": 0,
|
||||
"contentPaddingTop": 0,
|
||||
"defaultAvatar": "https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp",
|
||||
"defaultHomePath": "/dashboard",
|
||||
"dynamicTitle": true,
|
||||
"enableCheckUpdates": true,
|
||||
"enableCopyPreferences": true,
|
||||
"enablePreferences": true,
|
||||
"enableRefreshToken": false,
|
||||
"enableStickyPreferencesNavigationBar": true,
|
||||
"isMobile": false,
|
||||
"layout": "sidebar-nav",
|
||||
"locale": "zh-CN",
|
||||
"loginExpiredMode": "page",
|
||||
"name": "Vben Admin",
|
||||
"preferencesButtonPosition": "auto",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"watermark": false,
|
||||
"watermarkContent": "",
|
||||
"zIndex": 200,
|
||||
},
|
||||
"breadcrumb": {
|
||||
"enable": true,
|
||||
"hideOnlyOne": false,
|
||||
"showHome": false,
|
||||
"showIcon": true,
|
||||
"styleType": "normal",
|
||||
},
|
||||
"copyright": {
|
||||
"companyName": "Vben",
|
||||
"companySiteLink": "https://www.vben.pro",
|
||||
"date": "2024",
|
||||
"enable": true,
|
||||
"icp": "闽ICP备19024351号",
|
||||
"icpLink": "https://beian.miit.gov.cn/",
|
||||
"settingShow": true,
|
||||
},
|
||||
"footer": {
|
||||
"enable": false,
|
||||
"fixed": false,
|
||||
"height": 32,
|
||||
},
|
||||
"header": {
|
||||
"enable": true,
|
||||
"height": 50,
|
||||
"hidden": false,
|
||||
"menuAlign": "start",
|
||||
"mode": "fixed",
|
||||
},
|
||||
"logo": {
|
||||
"enable": true,
|
||||
"fit": "contain",
|
||||
"logoMode": "icon",
|
||||
"showText": true,
|
||||
"source": "https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp",
|
||||
},
|
||||
"navigation": {
|
||||
"accordion": true,
|
||||
"split": true,
|
||||
"styleType": "rounded",
|
||||
},
|
||||
"shortcutKeys": {
|
||||
"enable": true,
|
||||
"globalEscape": false,
|
||||
"globalLockScreen": true,
|
||||
"globalLogout": true,
|
||||
"globalPreferences": true,
|
||||
"globalSearch": true,
|
||||
},
|
||||
"sidebar": {
|
||||
"autoActivateChild": false,
|
||||
"collapseWidth": 60,
|
||||
"collapsed": false,
|
||||
"collapsedButton": true,
|
||||
"collapsedShowTitle": false,
|
||||
"draggable": true,
|
||||
"enable": true,
|
||||
"expandOnHover": true,
|
||||
"extraCollapse": false,
|
||||
"extraCollapsedWidth": 60,
|
||||
"fixedButton": true,
|
||||
"hidden": false,
|
||||
"mixedWidth": 80,
|
||||
"width": 224,
|
||||
},
|
||||
"tabbar": {
|
||||
"draggable": true,
|
||||
"enable": true,
|
||||
"height": 38,
|
||||
"keepAlive": true,
|
||||
"maxCount": 0,
|
||||
"middleClickToClose": false,
|
||||
"persist": true,
|
||||
"showIcon": true,
|
||||
"showMaximize": true,
|
||||
"showMore": true,
|
||||
"showRefresh": true,
|
||||
"styleType": "chrome",
|
||||
"visitHistory": true,
|
||||
"wheelable": true,
|
||||
},
|
||||
"theme": {
|
||||
"builtinType": "default",
|
||||
"colorDestructive": "hsl(348 100% 61%)",
|
||||
"colorPrimary": "hsl(212 100% 45%)",
|
||||
"colorSuccess": "hsl(144 57% 58%)",
|
||||
"colorWarning": "hsl(42 84% 61%)",
|
||||
"fontSize": 16,
|
||||
"mode": "dark",
|
||||
"radius": "0.5",
|
||||
"semiDarkHeader": false,
|
||||
"semiDarkSidebar": false,
|
||||
"semiDarkSidebarSub": false,
|
||||
},
|
||||
"transition": {
|
||||
"enable": true,
|
||||
"loading": true,
|
||||
"name": "fade-slide",
|
||||
"progress": true,
|
||||
},
|
||||
"widget": {
|
||||
"fullscreen": true,
|
||||
"fullscreenButtonPosition": "header",
|
||||
"globalSearch": true,
|
||||
"globalSearchButtonPosition": "header",
|
||||
"languageToggle": true,
|
||||
"languageToggleButtonPosition": "header",
|
||||
"lockScreen": true,
|
||||
"lockScreenButtonPosition": "header",
|
||||
"logoutButtonPosition": "header",
|
||||
"notification": true,
|
||||
"notificationButtonPosition": "header",
|
||||
"order": [
|
||||
"globalSearch",
|
||||
"preferences",
|
||||
"themeToggle",
|
||||
"languageToggle",
|
||||
"timezone",
|
||||
"fullscreen",
|
||||
"refresh",
|
||||
"notification",
|
||||
"lockScreenBtn",
|
||||
"logoutBtn",
|
||||
],
|
||||
"refresh": true,
|
||||
"refreshButtonPosition": "header",
|
||||
"sidebarToggle": true,
|
||||
"themeToggle": true,
|
||||
"themeToggleButtonPosition": "header",
|
||||
"timezone": true,
|
||||
"timezoneButtonPosition": "header",
|
||||
},
|
||||
}
|
||||
`;
|
||||
@@ -1,10 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { defaultPreferences } from '../src/config';
|
||||
|
||||
describe('defaultPreferences immutability test', () => {
|
||||
// 创建快照,确保默认配置对象不被修改
|
||||
it('should not modify the config object', () => {
|
||||
expect(defaultPreferences).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
@@ -1,546 +0,0 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { defaultPreferences } from '../src/config';
|
||||
import { isDarkTheme } from '../src/update-css-variables';
|
||||
|
||||
describe('preferences', () => {
|
||||
let PreferenceManager: typeof import('../src/preferences').PreferenceManager;
|
||||
let preferenceManager: InstanceType<
|
||||
typeof import('../src/preferences').PreferenceManager
|
||||
>;
|
||||
|
||||
// 模拟 window.matchMedia 方法
|
||||
vi.stubGlobal(
|
||||
'matchMedia',
|
||||
vi.fn().mockImplementation((query) => ({
|
||||
addEventListener: vi.fn(),
|
||||
addListener: vi.fn(), // Deprecated
|
||||
dispatchEvent: vi.fn(),
|
||||
matches: query === '(prefers-color-scheme: dark)',
|
||||
media: query,
|
||||
onchange: null,
|
||||
removeEventListener: vi.fn(),
|
||||
removeListener: vi.fn(), // Deprecated
|
||||
})),
|
||||
);
|
||||
|
||||
vi.stubGlobal('localStorage', {
|
||||
clear: vi.fn(),
|
||||
getItem: vi.fn(() => null),
|
||||
key: vi.fn(() => null),
|
||||
length: 0,
|
||||
removeItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
});
|
||||
|
||||
vi.stubGlobal('sessionStorage', {
|
||||
clear: vi.fn(),
|
||||
getItem: vi.fn(() => null),
|
||||
key: vi.fn(() => null),
|
||||
length: 0,
|
||||
removeItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
({ PreferenceManager } = await import('../src/preferences'));
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(localStorage.getItem).mockImplementation(() => null);
|
||||
vi.mocked(localStorage.removeItem).mockReset();
|
||||
vi.mocked(localStorage.setItem).mockReset();
|
||||
vi.mocked(sessionStorage.getItem).mockImplementation(() => null);
|
||||
vi.mocked(sessionStorage.removeItem).mockReset();
|
||||
vi.mocked(sessionStorage.setItem).mockReset();
|
||||
preferenceManager = new PreferenceManager();
|
||||
});
|
||||
|
||||
it('loads default preferences if no saved preferences found', () => {
|
||||
const preferences = preferenceManager.getPreferences();
|
||||
expect(preferences).toEqual(defaultPreferences);
|
||||
});
|
||||
|
||||
it('initializes preferences with overrides', async () => {
|
||||
const overrides: any = {
|
||||
app: {
|
||||
locale: 'en-US',
|
||||
},
|
||||
};
|
||||
await preferenceManager.initPreferences({
|
||||
namespace: 'testNamespace',
|
||||
overrides,
|
||||
});
|
||||
|
||||
// 等待防抖动操作完成
|
||||
// await new Promise((resolve) => setTimeout(resolve, 300)); // 等待100毫秒
|
||||
|
||||
const expected = {
|
||||
...defaultPreferences,
|
||||
app: {
|
||||
...defaultPreferences.app,
|
||||
...overrides.app,
|
||||
},
|
||||
};
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(expected);
|
||||
});
|
||||
|
||||
it('updates theme mode correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
theme: {
|
||||
mode: 'light',
|
||||
},
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().theme.mode).toBe('light');
|
||||
});
|
||||
|
||||
it('updates color modes correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
app: { colorGrayMode: true, colorWeakMode: true },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().app.colorGrayMode).toBe(true);
|
||||
expect(preferenceManager.getPreferences().app.colorWeakMode).toBe(true);
|
||||
});
|
||||
|
||||
it('resets preferences to default', async () => {
|
||||
// 先更新一些偏好设置
|
||||
preferenceManager.updatePreferences({
|
||||
theme: {
|
||||
mode: 'light',
|
||||
},
|
||||
});
|
||||
|
||||
// 然后重置偏好设置
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(defaultPreferences);
|
||||
});
|
||||
|
||||
it('updates isMobile correctly', () => {
|
||||
// 模拟移动端状态
|
||||
vi.stubGlobal(
|
||||
'matchMedia',
|
||||
vi.fn().mockImplementation((query) => ({
|
||||
addEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
matches: query === '(max-width: 768px)',
|
||||
media: query,
|
||||
onchange: null,
|
||||
removeEventListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
})),
|
||||
);
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
app: { isMobile: true },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().app.isMobile).toBe(true);
|
||||
});
|
||||
|
||||
it('updates the locale preference correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
app: { locale: 'en-US' },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().app.locale).toBe('en-US');
|
||||
});
|
||||
|
||||
it('updates the sidebar width correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
sidebar: { width: 200 },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().sidebar.width).toBe(200);
|
||||
});
|
||||
it('updates the sidebar collapse state correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
sidebar: { collapsed: true },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().sidebar.collapsed).toBe(true);
|
||||
});
|
||||
it('updates the navigation style type correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
navigation: { styleType: 'flat' },
|
||||
} as any);
|
||||
|
||||
expect(preferenceManager.getPreferences().navigation.styleType).toBe(
|
||||
'flat',
|
||||
);
|
||||
});
|
||||
|
||||
it('resets preferences to default correctly', async () => {
|
||||
// 先更新一些偏好设置
|
||||
preferenceManager.updatePreferences({
|
||||
app: { locale: 'en-US' },
|
||||
sidebar: { collapsed: true, width: 200 },
|
||||
theme: {
|
||||
mode: 'light',
|
||||
},
|
||||
});
|
||||
|
||||
// 然后重置偏好设置
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(defaultPreferences);
|
||||
});
|
||||
|
||||
it('does not update undefined preferences', () => {
|
||||
const originalPreferences = preferenceManager.getPreferences();
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
app: { nonexistentField: 'value' },
|
||||
} as any);
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(originalPreferences);
|
||||
});
|
||||
|
||||
it('reverts to default when a preference field is deleted', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
app: { locale: 'en-US' },
|
||||
});
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
app: { locale: undefined },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().app.locale).toBe('en-US');
|
||||
});
|
||||
|
||||
it('ignores updates with invalid preference value types', () => {
|
||||
const originalPreferences = preferenceManager.getPreferences();
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
app: { isMobile: 'true' as unknown as boolean }, // 错误类型
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(originalPreferences);
|
||||
});
|
||||
|
||||
it('merges nested preference objects correctly', () => {
|
||||
preferenceManager.updatePreferences({
|
||||
app: { name: 'New App Name' },
|
||||
});
|
||||
|
||||
const expected = {
|
||||
...defaultPreferences,
|
||||
app: {
|
||||
...defaultPreferences.app,
|
||||
name: 'New App Name',
|
||||
},
|
||||
};
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(expected);
|
||||
});
|
||||
|
||||
it('applies updates immediately after initialization', async () => {
|
||||
const overrides: any = {
|
||||
app: {
|
||||
locale: 'en-US',
|
||||
},
|
||||
};
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
namespace: 'apply-updates',
|
||||
overrides,
|
||||
});
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
theme: { mode: 'light' },
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferences().theme.mode).toBe('light');
|
||||
});
|
||||
|
||||
it('initializes custom preferences extension with default values', async () => {
|
||||
const extension = {
|
||||
fields: [
|
||||
{
|
||||
component: 'switch',
|
||||
defaultValue: true,
|
||||
key: 'enableWorkbench',
|
||||
label: '启用工作台',
|
||||
},
|
||||
{
|
||||
component: 'select',
|
||||
defaultValue: 'single',
|
||||
key: 'tenantMode',
|
||||
label: '租户模式',
|
||||
options: [
|
||||
{ label: '单租户', value: 'single' },
|
||||
{ label: '多租户', value: 'multi' },
|
||||
],
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
title: '业务偏好',
|
||||
} as const;
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension,
|
||||
namespace: 'custom-defaults',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferencesExtension()).toEqual(extension);
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
enableWorkbench: true,
|
||||
tenantMode: 'single',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not expose mutable custom preference baselines or extension schema', async () => {
|
||||
const extension = {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
title: '业务偏好',
|
||||
} as const;
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension,
|
||||
namespace: 'custom-readonly',
|
||||
});
|
||||
|
||||
const initialCustomPreferences =
|
||||
preferenceManager.getInitialCustomPreferences<{
|
||||
pageSize: number;
|
||||
}>() as { pageSize: number };
|
||||
const preferencesExtension = preferenceManager.getPreferencesExtension<{
|
||||
pageSize: number;
|
||||
}>() as {
|
||||
fields: Array<{ componentProps?: { max?: number }; label: string }>;
|
||||
};
|
||||
const [firstField] = preferencesExtension.fields;
|
||||
|
||||
initialCustomPreferences.pageSize = 8;
|
||||
expect(firstField).toBeDefined();
|
||||
expect(firstField?.componentProps).toBeDefined();
|
||||
|
||||
if (!firstField || !firstField.componentProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
firstField.label = '已修改';
|
||||
firstField.componentProps.max = 20;
|
||||
|
||||
expect(preferenceManager.getInitialCustomPreferences()).toEqual({
|
||||
pageSize: 4,
|
||||
});
|
||||
expect(preferenceManager.getPreferencesExtension()).toEqual(extension);
|
||||
});
|
||||
|
||||
it('updates and resets custom preferences correctly', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
defaultValue: 20,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
{
|
||||
component: 'input',
|
||||
defaultValue: '日报',
|
||||
key: 'reportTitle',
|
||||
label: '报表标题',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-reset',
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 50,
|
||||
reportTitle: '月报',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 50,
|
||||
reportTitle: '月报',
|
||||
});
|
||||
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 20,
|
||||
reportTitle: '日报',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores invalid custom preferences updates', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'switch',
|
||||
defaultValue: true,
|
||||
key: 'enableWorkbench',
|
||||
label: '启用工作台',
|
||||
},
|
||||
{
|
||||
component: 'select',
|
||||
defaultValue: 'single',
|
||||
key: 'tenantMode',
|
||||
label: '租户模式',
|
||||
options: [
|
||||
{ label: '单租户', value: 'single' },
|
||||
{ label: '多租户', value: 'multi' },
|
||||
],
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-invalid',
|
||||
});
|
||||
|
||||
const originalCustomPreferences = preferenceManager.getCustomPreferences();
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
enableWorkbench: 'true' as unknown as boolean,
|
||||
tenantMode: 'unknown',
|
||||
unknownField: 'value',
|
||||
} as any);
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual(
|
||||
originalCustomPreferences,
|
||||
);
|
||||
});
|
||||
|
||||
it('enforces custom number field min max and step constraints', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-number-constraints',
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 1,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 12,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 5,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
});
|
||||
|
||||
it('filters cached custom number values that violate field constraints', async () => {
|
||||
vi.mocked(localStorage.getItem).mockImplementation((key) => {
|
||||
if (key.endsWith('cache-preferences-custom')) {
|
||||
return JSON.stringify({
|
||||
value: {
|
||||
pageSize: 5,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-number-cache',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDarkTheme', () => {
|
||||
it('should return true for dark theme', () => {
|
||||
expect(isDarkTheme('dark')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for light theme', () => {
|
||||
expect(isDarkTheme('light')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return system preference for auto theme', () => {
|
||||
vi.spyOn(window, 'matchMedia').mockImplementation((query) => ({
|
||||
addEventListener: vi.fn(),
|
||||
addListener: vi.fn(), // Deprecated
|
||||
dispatchEvent: vi.fn(),
|
||||
matches: query === '(prefers-color-scheme: dark)',
|
||||
media: query,
|
||||
onchange: null,
|
||||
removeEventListener: vi.fn(),
|
||||
removeListener: vi.fn(), // Deprecated
|
||||
}));
|
||||
|
||||
expect(isDarkTheme('auto')).toBe(true);
|
||||
expect(window.matchMedia).toHaveBeenCalledWith(
|
||||
'(prefers-color-scheme: dark)',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineComponent, h } from 'vue';
|
||||
|
||||
export const TestInput = defineComponent({
|
||||
inheritAttrs: false,
|
||||
emits: ['update:modelValue'],
|
||||
setup(_props, { attrs, emit }) {
|
||||
function handleInput(event: Event) {
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) {
|
||||
emit('update:modelValue', target.value);
|
||||
}
|
||||
}
|
||||
|
||||
return () =>
|
||||
h('input', {
|
||||
...attrs,
|
||||
onInput: handleInput,
|
||||
value: attrs.modelValue ?? '',
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,596 +0,0 @@
|
||||
import type { BaseFormComponentType } from '../src/types';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { FormApi } from '../src/form-api';
|
||||
import { FormCodecError } from '../src/form-codec';
|
||||
|
||||
describe('formApi', () => {
|
||||
let formApi: FormApi;
|
||||
|
||||
beforeEach(() => {
|
||||
formApi = new FormApi();
|
||||
});
|
||||
|
||||
it('should initialize with default state', () => {
|
||||
expect(formApi.state).toEqual(
|
||||
expect.objectContaining({
|
||||
actionWrapperClass: '',
|
||||
collapsed: false,
|
||||
collapsedRows: 1,
|
||||
commonConfig: {},
|
||||
handleReset: undefined,
|
||||
handleSubmit: undefined,
|
||||
layout: 'horizontal',
|
||||
resetButtonOptions: {},
|
||||
schema: [],
|
||||
showCollapseButton: false,
|
||||
showDefaultActions: true,
|
||||
submitButtonOptions: {},
|
||||
wrapperClass: 'grid-cols-1',
|
||||
}),
|
||||
);
|
||||
expect(formApi.isMounted).toBe(false);
|
||||
});
|
||||
|
||||
it('should mount form actions', async () => {
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
resetForm: vi.fn(),
|
||||
setFieldValue: vi.fn(),
|
||||
setValues: vi.fn(),
|
||||
submitForm: vi.fn(),
|
||||
validate: vi.fn(),
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions);
|
||||
expect(formApi.isMounted).toBe(true);
|
||||
expect(formApi.form).toEqual(formActions);
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get values from form', async () => {
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
const values = await formApi.getValues();
|
||||
expect(values).toEqual({ name: 'test' });
|
||||
});
|
||||
|
||||
it('should set a field error through the public api', async () => {
|
||||
const setFieldError = vi.fn();
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
setFieldError,
|
||||
values: {},
|
||||
};
|
||||
|
||||
formApi.mount(formActions, new Map());
|
||||
await formApi.setFieldError('password', 'Invalid password');
|
||||
|
||||
expect(setFieldError).toHaveBeenCalledWith('password', 'Invalid password');
|
||||
});
|
||||
|
||||
it('should format schema values when getting values', async () => {
|
||||
formApi.setState({
|
||||
schema: [
|
||||
{
|
||||
component: 'range-picker',
|
||||
fieldName: 'filters.range',
|
||||
valueFormat: (value, setValue) => {
|
||||
setValue('filters.startTime', value?.[0]);
|
||||
setValue('filters.endTime', value?.[1]);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
values: {
|
||||
filters: {
|
||||
range: [1_710_000_000_000, 1_720_000_000_000],
|
||||
},
|
||||
},
|
||||
};
|
||||
const originalValuesSnapshot = structuredClone(formActions.values);
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
expect(formApi.getLatestSubmissionValues()).toEqual({
|
||||
filters: {
|
||||
endTime: 1_720_000_000_000,
|
||||
startTime: 1_710_000_000_000,
|
||||
},
|
||||
});
|
||||
|
||||
const values = await formApi.getValues();
|
||||
expect(values).toEqual({
|
||||
filters: {
|
||||
endTime: 1_720_000_000_000,
|
||||
startTime: 1_710_000_000_000,
|
||||
},
|
||||
});
|
||||
expect(await formApi.getRawValues()).toEqual(originalValuesSnapshot);
|
||||
expect(await formApi.getValueSnapshot()).toEqual({
|
||||
rawValues: originalValuesSnapshot,
|
||||
values,
|
||||
});
|
||||
expect(formActions.values).toEqual(originalValuesSnapshot);
|
||||
});
|
||||
|
||||
it('should encode submissions and decode complete values with a codec', async () => {
|
||||
interface FilterFormValues {
|
||||
period: [number, number];
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
interface FilterSubmitValues {
|
||||
endTime: number;
|
||||
startTime: number;
|
||||
tags: string;
|
||||
}
|
||||
|
||||
const setValues = vi.fn();
|
||||
const codecFormApi = new FormApi<
|
||||
FilterFormValues,
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
FilterSubmitValues
|
||||
>({
|
||||
codec: {
|
||||
decode(values) {
|
||||
return {
|
||||
period: [values.startTime, values.endTime],
|
||||
tags: values.tags.split(','),
|
||||
};
|
||||
},
|
||||
encode(values) {
|
||||
return {
|
||||
endTime: values.period[1],
|
||||
startTime: values.period[0],
|
||||
tags: values.tags.join(','),
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
setValues,
|
||||
values: { period: [1, 2], tags: ['admin', 'user'] },
|
||||
};
|
||||
|
||||
await codecFormApi.mount(formActions, new Map());
|
||||
|
||||
expect(await codecFormApi.getValues()).toEqual({
|
||||
endTime: 2,
|
||||
startTime: 1,
|
||||
tags: 'admin,user',
|
||||
});
|
||||
expect(await codecFormApi.getValueSnapshot()).toEqual({
|
||||
rawValues: { period: [1, 2], tags: ['admin', 'user'] },
|
||||
values: { endTime: 2, startTime: 1, tags: 'admin,user' },
|
||||
});
|
||||
|
||||
await codecFormApi.setSubmitValues(
|
||||
{ endTime: 4, startTime: 3, tags: 'editor' },
|
||||
false,
|
||||
);
|
||||
expect(setValues).toHaveBeenCalledWith(
|
||||
{ period: [3, 4], tags: ['editor'] },
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should isolate codec results from live form values', async () => {
|
||||
interface ProfileFormValues {
|
||||
profile: { name: string };
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
const values: ProfileFormValues = {
|
||||
profile: { name: 'Ada' },
|
||||
tags: ['admin'],
|
||||
};
|
||||
const codecFormApi = new FormApi<ProfileFormValues>({
|
||||
codec: {
|
||||
decode: (submitValues) => submitValues,
|
||||
encode: (formValues) => ({
|
||||
profile: formValues.profile,
|
||||
tags: formValues.tags,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const formActions: any = { meta: {}, values };
|
||||
|
||||
codecFormApi.mount(formActions, new Map());
|
||||
const initialSubmissionValues = codecFormApi.getLatestSubmissionValues();
|
||||
values.profile.name = 'Grace';
|
||||
values.tags.push('user');
|
||||
|
||||
expect(initialSubmissionValues).toEqual({
|
||||
profile: { name: 'Ada' },
|
||||
tags: ['admin'],
|
||||
});
|
||||
const submissionValues = await codecFormApi.getValues();
|
||||
expect(submissionValues.profile).not.toBe(values.profile);
|
||||
expect(submissionValues.tags).not.toBe(values.tags);
|
||||
});
|
||||
|
||||
it('should fall back to raw values when the initial codec encode fails', async () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const codecFormApi = new FormApi<
|
||||
{ name?: string },
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
{ normalizedName: string }
|
||||
>({
|
||||
codec: {
|
||||
decode: (values) => ({ name: values.normalizedName }),
|
||||
encode() {
|
||||
throw new Error('incomplete initial values');
|
||||
},
|
||||
},
|
||||
});
|
||||
const formActions: any = { meta: {}, values: { name: 'Ada' } };
|
||||
|
||||
expect(() => codecFormApi.mount(formActions, new Map())).not.toThrow();
|
||||
|
||||
expect(codecFormApi.isMounted).toBe(true);
|
||||
expect(codecFormApi.getLatestSubmissionValues()).toEqual({ name: 'Ada' });
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] Failed to encode initial values. Falling back to raw form values.',
|
||||
expect.objectContaining({ phase: 'encode' }),
|
||||
);
|
||||
await expect(codecFormApi.getValues()).rejects.toBeInstanceOf(
|
||||
FormCodecError,
|
||||
);
|
||||
});
|
||||
|
||||
it('should scan deprecated schema transforms once for unchanged state', async () => {
|
||||
const getChildren = vi.fn(() => []);
|
||||
const schema = {
|
||||
component: 'text',
|
||||
fieldName: 'name',
|
||||
get children() {
|
||||
return getChildren();
|
||||
},
|
||||
} as any;
|
||||
const codecFormApi = new FormApi({
|
||||
codec: {
|
||||
decode: (values) => values,
|
||||
encode: (values) => values,
|
||||
},
|
||||
schema: [schema],
|
||||
});
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
values: { name: 'Ada' },
|
||||
};
|
||||
|
||||
await codecFormApi.mount(formActions, new Map());
|
||||
expect(getChildren).toHaveBeenCalledTimes(1);
|
||||
|
||||
await codecFormApi.getValues();
|
||||
await codecFormApi.getValues();
|
||||
|
||||
expect(getChildren).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should format child schema values inside array fields', async () => {
|
||||
formApi.setState({
|
||||
schema: [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
component: 'text',
|
||||
fieldName: 'name',
|
||||
valueFormat: (
|
||||
value: any,
|
||||
setValue: any,
|
||||
_values: any,
|
||||
ctx: any,
|
||||
) => {
|
||||
setValue('normalizedName', value?.trim());
|
||||
setValue('$root.firstRow', ctx?.rowIndex);
|
||||
},
|
||||
},
|
||||
],
|
||||
fieldName: 'contacts',
|
||||
type: 'array',
|
||||
} as any,
|
||||
],
|
||||
});
|
||||
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
values: {
|
||||
contacts: [{ name: ' Ada ' }, { name: ' Grace ' }],
|
||||
},
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
const values = await formApi.getValues();
|
||||
expect(values).toEqual({
|
||||
contacts: [{ normalizedName: 'Ada' }, { normalizedName: 'Grace' }],
|
||||
firstRow: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('should set field value', async () => {
|
||||
const setFieldValueMock = vi.fn();
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
setFieldValue: setFieldValueMock,
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
await formApi.setFieldValue('name', 'new value');
|
||||
expect(setFieldValueMock).toHaveBeenCalledWith(
|
||||
'name',
|
||||
'new value',
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('should set only known fields without losing provided values', async () => {
|
||||
const setValuesMock = vi.fn();
|
||||
formApi.setState({
|
||||
schema: [
|
||||
{ component: 'text', fieldName: 'name' },
|
||||
{ component: 'text', fieldName: 'profile.email' },
|
||||
],
|
||||
});
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
setValues: setValuesMock,
|
||||
values: {},
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
await formApi.setValues({
|
||||
name: 'Ada',
|
||||
profile: {
|
||||
email: 'ada@example.com',
|
||||
ignored: true,
|
||||
},
|
||||
unknown: 'ignored',
|
||||
});
|
||||
|
||||
expect(setValuesMock).toHaveBeenCalledWith(
|
||||
{
|
||||
name: 'Ada',
|
||||
profile: {
|
||||
email: 'ada@example.com',
|
||||
},
|
||||
},
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should reset form', async () => {
|
||||
const resetMock = vi.fn();
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
reset: resetMock,
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
await formApi.reset();
|
||||
expect(resetMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call handleSubmit on submit', async () => {
|
||||
const handleSubmitMock = vi.fn();
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
submit: vi.fn().mockResolvedValue(true),
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
const state = {
|
||||
handleSubmit: handleSubmitMock,
|
||||
};
|
||||
|
||||
formApi.setState(state);
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
const result = await formApi.submit();
|
||||
expect(formActions.submit).toHaveBeenCalled();
|
||||
expect(handleSubmitMock).toHaveBeenCalledWith(
|
||||
{ name: 'test' },
|
||||
{ name: 'test' },
|
||||
);
|
||||
expect(result).toEqual({ name: 'test' });
|
||||
});
|
||||
|
||||
it('should unmount form and reset state', () => {
|
||||
formApi.unmount();
|
||||
expect(formApi.isMounted).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear component refs on unmount before mounting again', async () => {
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
resetForm: vi.fn(),
|
||||
values: { name: 'test' },
|
||||
};
|
||||
const staleMap = new Map<string, unknown>([
|
||||
[
|
||||
'name',
|
||||
{
|
||||
$: {
|
||||
type: { name: 'MockComponent' },
|
||||
},
|
||||
$el: {},
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
await formApi.mount(formActions, staleMap);
|
||||
expect(formApi.getFieldComponentRef('name')).toEqual({
|
||||
$: {
|
||||
type: { name: 'MockComponent' },
|
||||
},
|
||||
$el: {},
|
||||
});
|
||||
|
||||
formApi.unmount();
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
|
||||
await formApi.mount(formActions);
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should validate form', async () => {
|
||||
const validateMock = vi.fn().mockResolvedValue(true);
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
validate: validateMock,
|
||||
};
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
const isValid = await formApi.validate();
|
||||
expect(validateMock).toHaveBeenCalled();
|
||||
expect(isValid).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate only once before submitting valid values', async () => {
|
||||
const handleSubmit = vi.fn();
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
submit: vi.fn(),
|
||||
validate: vi.fn().mockResolvedValue({ errors: {}, valid: true }),
|
||||
values: { name: 'Ada' },
|
||||
};
|
||||
|
||||
formApi.setState({ handleSubmit });
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
await expect(formApi.validateAndSubmit()).resolves.toEqual({ name: 'Ada' });
|
||||
expect(formActions.validate).toHaveBeenCalledOnce();
|
||||
expect(formActions.submit).not.toHaveBeenCalled();
|
||||
expect(handleSubmit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should not submit invalid values', async () => {
|
||||
const handleSubmit = vi.fn();
|
||||
const errors = { name: 'Name is required' };
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
submit: vi.fn(),
|
||||
validate: vi.fn().mockResolvedValue({ errors, valid: false }),
|
||||
values: { name: '' },
|
||||
};
|
||||
const scrollToFirstError = vi
|
||||
.spyOn(formApi as any, 'scrollToFirstError')
|
||||
.mockImplementation(() => {});
|
||||
|
||||
formApi.setState({ handleSubmit, scrollToFirstError: true });
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
await expect(formApi.validateAndSubmit()).resolves.toBeUndefined();
|
||||
expect(formActions.validate).toHaveBeenCalledOnce();
|
||||
expect(formActions.submit).not.toHaveBeenCalled();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
expect(scrollToFirstError).toHaveBeenCalledOnce();
|
||||
expect(scrollToFirstError).toHaveBeenCalledWith(errors);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateSchema', () => {
|
||||
let instance: FormApi;
|
||||
|
||||
beforeEach(() => {
|
||||
instance = new FormApi();
|
||||
instance.state = {
|
||||
schema: [
|
||||
{ component: 'text', fieldName: 'name' },
|
||||
{ component: 'number', fieldName: 'age', label: 'Age' },
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
it('should update the schema correctly when fieldName matches', () => {
|
||||
const newSchema = [
|
||||
{ component: 'text', fieldName: 'name' },
|
||||
{ component: 'number', fieldName: 'age', label: 'Age' },
|
||||
];
|
||||
|
||||
instance.updateSchema(newSchema);
|
||||
|
||||
expect(instance.state?.schema?.[0]?.component).toBe('text');
|
||||
expect(instance.state?.schema?.[1]?.label).toBe('Age');
|
||||
});
|
||||
|
||||
it('should update child schema by parent path', () => {
|
||||
instance.state = {
|
||||
schema: [
|
||||
{
|
||||
children: [
|
||||
{ component: 'text', fieldName: 'name', label: 'Name' },
|
||||
{ component: 'text', fieldName: 'phone', label: 'Phone' },
|
||||
],
|
||||
fieldName: 'contacts',
|
||||
type: 'array',
|
||||
} as any,
|
||||
],
|
||||
};
|
||||
|
||||
instance.updateSchema([
|
||||
{
|
||||
fieldName: 'contacts.name',
|
||||
label: 'Full Name',
|
||||
},
|
||||
]);
|
||||
|
||||
expect((instance.state?.schema?.[0] as any)?.children?.[0]?.label).toBe(
|
||||
'Full Name',
|
||||
);
|
||||
expect((instance.state?.schema?.[0] as any)?.children?.[1]?.label).toBe(
|
||||
'Phone',
|
||||
);
|
||||
});
|
||||
|
||||
it('should log an error if fieldName is missing in some items', () => {
|
||||
const newSchema: any[] = [
|
||||
{ component: 'textarea', fieldName: 'name' },
|
||||
{ component: 'number' },
|
||||
];
|
||||
|
||||
const consoleErrorSpy = vi
|
||||
.spyOn(console, 'error')
|
||||
.mockImplementation(() => {});
|
||||
|
||||
instance.updateSchema(newSchema);
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
'All items in the schema array must have a valid `fieldName` property to be updated',
|
||||
);
|
||||
});
|
||||
|
||||
it('should not update schema if fieldName does not match', () => {
|
||||
const newSchema = [{ component: 'textarea', fieldName: 'unknown' }];
|
||||
|
||||
instance.updateSchema(newSchema);
|
||||
|
||||
expect(instance.state?.schema?.[0]?.component).toBe('text');
|
||||
expect(instance.state?.schema?.[1]?.component).toBe('number');
|
||||
});
|
||||
|
||||
it('should not update schema if updatedMap is empty', () => {
|
||||
const newSchema: any[] = [{ component: 'textarea' }];
|
||||
|
||||
instance.updateSchema(newSchema);
|
||||
|
||||
expect(instance.state?.schema?.[0]?.component).toBe('text');
|
||||
expect(instance.state?.schema?.[1]?.component).toBe('number');
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import type { FormCodec } from '../src/types';
|
||||
|
||||
import { describe, expect, expectTypeOf, it } from 'vitest';
|
||||
|
||||
import {
|
||||
decodeFormValues,
|
||||
encodeFormValues,
|
||||
FormCodecError,
|
||||
} from '../src/form-codec';
|
||||
|
||||
interface FilterFormValues {
|
||||
period: [number, number];
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
interface FilterSubmitValues {
|
||||
endTime: number;
|
||||
startTime: number;
|
||||
tags: string;
|
||||
}
|
||||
|
||||
const filterCodec: FormCodec<FilterFormValues, FilterSubmitValues> = {
|
||||
decode(values) {
|
||||
return {
|
||||
period: [values.startTime, values.endTime],
|
||||
tags: values.tags ? values.tags.split(',') : [],
|
||||
};
|
||||
},
|
||||
encode(values) {
|
||||
return {
|
||||
endTime: values.period[1],
|
||||
startTime: values.period[0],
|
||||
tags: values.tags.join(','),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
describe('form codec', () => {
|
||||
it('encodes and decodes complete form values', () => {
|
||||
const submitValues = encodeFormValues(filterCodec, {
|
||||
period: [1, 2],
|
||||
tags: ['admin', 'user'],
|
||||
});
|
||||
|
||||
expect(submitValues).toEqual({
|
||||
endTime: 2,
|
||||
startTime: 1,
|
||||
tags: 'admin,user',
|
||||
});
|
||||
expect(decodeFormValues(filterCodec, submitValues)).toEqual({
|
||||
period: [1, 2],
|
||||
tags: ['admin', 'user'],
|
||||
});
|
||||
expectTypeOf(submitValues).toEqualTypeOf<FilterSubmitValues>();
|
||||
});
|
||||
|
||||
it('reports the failed codec phase without mutating inputs', () => {
|
||||
const values = Object.freeze({ period: [1, 2], tags: ['admin'] }) as {
|
||||
period: [number, number];
|
||||
tags: string[];
|
||||
};
|
||||
const codec: FormCodec<FilterFormValues, FilterSubmitValues> = {
|
||||
decode: filterCodec.decode,
|
||||
encode() {
|
||||
throw new Error('broken encoder');
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => encodeFormValues(codec, values)).toThrowError(FormCodecError);
|
||||
|
||||
let codecError: unknown;
|
||||
try {
|
||||
encodeFormValues(codec, values);
|
||||
} catch (error) {
|
||||
codecError = error;
|
||||
}
|
||||
expect(codecError).toBeInstanceOf(FormCodecError);
|
||||
expect(codecError).toMatchObject({ phase: 'encode' });
|
||||
expect(values).toEqual({ period: [1, 2], tags: ['admin'] });
|
||||
});
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
import type { BaseFormComponentType } from '../src/types';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { setupVbenForm } from '../src/config';
|
||||
import {
|
||||
resetDeprecationWarnings,
|
||||
warnDeprecatedOnce,
|
||||
} from '../src/deprecation';
|
||||
import { FormApi } from '../src/form-api';
|
||||
import { getFormRule } from '../src/rule-registry';
|
||||
|
||||
afterEach(() => {
|
||||
resetDeprecationWarnings();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('form api compatibility', () => {
|
||||
it('keeps deprecated value transforms and warns once per API', async () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const formApi = new FormApi({
|
||||
arrayToStringFields: ['tags'],
|
||||
fieldMappingTime: [['period', ['startTime', 'endTime'], null]],
|
||||
schema: [
|
||||
{
|
||||
component: 'input',
|
||||
fieldName: 'name',
|
||||
valueFormat: (value: string) => value.trim(),
|
||||
},
|
||||
],
|
||||
});
|
||||
const form = {
|
||||
meta: {},
|
||||
values: {
|
||||
name: ' Ada ',
|
||||
period: [1, 2],
|
||||
tags: ['admin', 'user'],
|
||||
},
|
||||
} as any;
|
||||
|
||||
formApi.mount(form);
|
||||
|
||||
expect(await formApi.getValues()).toEqual({
|
||||
endTime: 2,
|
||||
name: 'Ada',
|
||||
startTime: 1,
|
||||
tags: 'admin,user',
|
||||
});
|
||||
expect(warning).toHaveBeenCalledTimes(3);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `schema.valueFormat` is deprecated. Use the form-level `codec` instead.',
|
||||
);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `fieldMappingTime` is deprecated. Use the form-level `codec` instead.',
|
||||
);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `arrayToStringFields` is deprecated. Use the form-level `codec` instead.',
|
||||
);
|
||||
});
|
||||
|
||||
it('prefers the codec when deprecated transforms are also configured', async () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const formApi = new FormApi<
|
||||
{ name: string },
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
{ normalizedName: string }
|
||||
>({
|
||||
codec: {
|
||||
decode(values) {
|
||||
return { name: values.normalizedName };
|
||||
},
|
||||
encode(values) {
|
||||
return { normalizedName: values.name.toUpperCase() };
|
||||
},
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
component: 'input',
|
||||
fieldName: 'name',
|
||||
valueFormat: () => 'legacy',
|
||||
},
|
||||
],
|
||||
});
|
||||
const form = { meta: {}, values: { name: 'Ada' } } as any;
|
||||
|
||||
formApi.mount(form);
|
||||
|
||||
expect(await formApi.getValues()).toEqual({ normalizedName: 'ADA' });
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] The form `codec` takes precedence over deprecated `valueFormat`, `fieldMappingTime`, and `arrayToStringFields` options.',
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards defineRules and warns only once in development', async () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const legacyRule = () => 'legacy error';
|
||||
|
||||
setupVbenForm({ defineRules: { legacy: legacyRule } });
|
||||
setupVbenForm({ defineRules: { legacy: legacyRule } });
|
||||
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `setupVbenForm({ defineRules })` is deprecated. Use `setupVbenForm({ rules })` instead.',
|
||||
);
|
||||
const registeredRule = getFormRule('legacy');
|
||||
expect(registeredRule).toBeDefined();
|
||||
if (!registeredRule) return;
|
||||
expect(
|
||||
await registeredRule('', [], {
|
||||
field: { name: 'legacy' },
|
||||
name: 'legacy',
|
||||
}),
|
||||
).toBe('legacy error');
|
||||
});
|
||||
|
||||
it('prefers the new rules option when both APIs define the same rule', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
setupVbenForm({
|
||||
defineRules: { required: () => 'legacy error' },
|
||||
rules: { required: () => 'new error' },
|
||||
});
|
||||
|
||||
const registeredRule = getFormRule('required');
|
||||
expect(registeredRule).toBeDefined();
|
||||
if (!registeredRule) return;
|
||||
expect(
|
||||
await registeredRule('', [], {
|
||||
field: { name: 'required' },
|
||||
name: 'required',
|
||||
}),
|
||||
).toBe('new error');
|
||||
});
|
||||
|
||||
it('does not emit deprecation warnings in production', () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
warnDeprecatedOnce('legacy-api', 'deprecated', { production: true });
|
||||
|
||||
expect(warning).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps legacy form methods and warns once for each name', async () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const formApi = new FormApi();
|
||||
const form = {
|
||||
clearValidation: vi.fn(),
|
||||
meta: {},
|
||||
reset: vi.fn(),
|
||||
submit: vi.fn(),
|
||||
validate: vi.fn().mockResolvedValue({ errors: {}, valid: true }),
|
||||
values: { name: 'Ada' },
|
||||
} as any;
|
||||
formApi.mount(form);
|
||||
|
||||
await formApi.resetForm();
|
||||
await formApi.resetForm();
|
||||
await formApi.resetValidate();
|
||||
await formApi.submitForm();
|
||||
await formApi.validateAndSubmitForm();
|
||||
|
||||
expect(form.reset).toHaveBeenCalledTimes(2);
|
||||
expect(form.clearValidation).toHaveBeenCalledOnce();
|
||||
expect(form.submit).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledTimes(4);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `formApi.resetForm()` is deprecated. Use `formApi.reset()` instead.',
|
||||
);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `formApi.resetValidate()` is deprecated. Use `formApi.clearValidation()` instead.',
|
||||
);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `formApi.submitForm()` is deprecated. Use `formApi.submit()` instead.',
|
||||
);
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[Vben Form] `formApi.validateAndSubmitForm()` is deprecated. Use `formApi.validateAndSubmit()` instead.',
|
||||
);
|
||||
});
|
||||
});
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
import type { FormSchema } from '../src/types';
|
||||
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { nextTick } from 'vue';
|
||||
|
||||
import { afterAll, bench, describe } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { setupVbenForm } from '../src/config';
|
||||
import { useVbenForm } from '../src/use-vben-form';
|
||||
import { TestInput } from './benchmark-fixtures';
|
||||
|
||||
const BENCHMARK_OPTIONS = { time: 750, warmupTime: 150 } as const;
|
||||
const FIELD_COUNT = 100;
|
||||
const MOUNT_FIELD_COUNT = 50;
|
||||
|
||||
function createFlatSchema(
|
||||
fieldCount: number,
|
||||
withRules: boolean = false,
|
||||
): FormSchema[] {
|
||||
const rule = withRules ? z.string().min(1) : undefined;
|
||||
return Array.from({ length: fieldCount }, (_, index) => ({
|
||||
component: TestInput,
|
||||
defaultValue: `Value ${index}`,
|
||||
fieldName: `field${index}`,
|
||||
label: `Field ${index}`,
|
||||
rules: rule,
|
||||
}));
|
||||
}
|
||||
|
||||
function createFlatValues(prefix: string) {
|
||||
return Object.fromEntries(
|
||||
Array.from({ length: FIELD_COUNT }, (_, index) => [
|
||||
`field${index}`,
|
||||
`${prefix} ${index}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
setupVbenForm({ config: {}, rules: {} });
|
||||
|
||||
const flatSchema = createFlatSchema(FIELD_COUNT);
|
||||
const [FlatForm, flatFormApi] = useVbenForm<Record<string, string>>({
|
||||
schema: flatSchema,
|
||||
showDefaultActions: false,
|
||||
});
|
||||
const flatWrapper = mount(FlatForm);
|
||||
|
||||
const [ValidationForm, validationFormApi] = useVbenForm<Record<string, string>>(
|
||||
{
|
||||
schema: createFlatSchema(FIELD_COUNT, true),
|
||||
showDefaultActions: false,
|
||||
},
|
||||
);
|
||||
const validationWrapper = mount(ValidationForm);
|
||||
|
||||
const dependencySchema: FormSchema[] = [
|
||||
{
|
||||
component: TestInput,
|
||||
defaultValue: 'editable',
|
||||
fieldName: 'mode',
|
||||
label: 'Mode',
|
||||
},
|
||||
...Array.from({ length: 50 }, (_, index) => ({
|
||||
component: TestInput,
|
||||
defaultValue: `Value ${index}`,
|
||||
dependencies: {
|
||||
resolve: ({ values }: { values: Record<string, string> }) => ({
|
||||
disabled: values.mode === 'locked',
|
||||
}),
|
||||
triggerFields: ['mode'],
|
||||
},
|
||||
fieldName: `dependent${index}`,
|
||||
label: `Dependent ${index}`,
|
||||
})),
|
||||
];
|
||||
const [DependencyForm, dependencyFormApi] = useVbenForm<Record<string, string>>(
|
||||
{
|
||||
schema: dependencySchema,
|
||||
showDefaultActions: false,
|
||||
},
|
||||
);
|
||||
const dependencyWrapper = mount(DependencyForm);
|
||||
|
||||
await flushPromises();
|
||||
|
||||
const batchValues = [createFlatValues('Alpha'), createFlatValues('Beta')];
|
||||
const schemaPatches = [false, true].map((disabled) =>
|
||||
Array.from({ length: FIELD_COUNT }, (_, index) => ({
|
||||
componentProps: { disabled },
|
||||
fieldName: `field${index}`,
|
||||
})),
|
||||
);
|
||||
let batchIteration = 0;
|
||||
let dependencyIteration = 0;
|
||||
let fieldIteration = 0;
|
||||
let resetIteration = 0;
|
||||
let schemaIteration = 0;
|
||||
|
||||
afterAll(() => {
|
||||
dependencyWrapper.unmount();
|
||||
flatWrapper.unmount();
|
||||
validationWrapper.unmount();
|
||||
});
|
||||
|
||||
describe('form render performance', () => {
|
||||
bench(
|
||||
'initialize, mount, and unmount 50 fields',
|
||||
async () => {
|
||||
const [Form] = useVbenForm<Record<string, string>>({
|
||||
schema: createFlatSchema(MOUNT_FIELD_COUNT),
|
||||
showDefaultActions: false,
|
||||
});
|
||||
const wrapper = mount(Form);
|
||||
await flushPromises();
|
||||
wrapper.unmount();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
});
|
||||
|
||||
describe('form value performance', () => {
|
||||
bench(
|
||||
'update one field in a 100-field form',
|
||||
async () => {
|
||||
fieldIteration += 1;
|
||||
await flatFormApi.setFieldValue('field50', `Value ${fieldIteration}`);
|
||||
await nextTick();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
|
||||
bench(
|
||||
'set 100 fields in one batch',
|
||||
async () => {
|
||||
batchIteration += 1;
|
||||
await flatFormApi.setValues(batchValues[batchIteration % 2] ?? {});
|
||||
await nextTick();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
|
||||
bench(
|
||||
'reset 100 fields to alternate values',
|
||||
async () => {
|
||||
resetIteration += 1;
|
||||
await flatFormApi.reset(
|
||||
{ values: batchValues[resetIteration % 2] ?? {} },
|
||||
{ force: true },
|
||||
);
|
||||
await nextTick();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
});
|
||||
|
||||
describe('form validation performance', () => {
|
||||
bench(
|
||||
'validate 100 fields with zod rules',
|
||||
async () => {
|
||||
await validationFormApi.validate();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
});
|
||||
|
||||
describe('form schema performance', () => {
|
||||
bench(
|
||||
'update 100 schema entries',
|
||||
async () => {
|
||||
schemaIteration += 1;
|
||||
flatFormApi.updateSchema(schemaPatches[schemaIteration % 2] ?? []);
|
||||
await nextTick();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
|
||||
bench(
|
||||
'resolve 50 dependencies from one trigger',
|
||||
async () => {
|
||||
dependencyIteration += 1;
|
||||
await dependencyFormApi.setFieldValue(
|
||||
'mode',
|
||||
dependencyIteration % 2 === 0 ? 'editable' : 'locked',
|
||||
);
|
||||
await flushPromises();
|
||||
},
|
||||
BENCHMARK_OPTIONS,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,177 +0,0 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { nextTick } from 'vue';
|
||||
|
||||
import { afterAll, bench, describe } from 'vitest';
|
||||
|
||||
import { setupVbenForm } from '../src/config';
|
||||
import { encodeFormValues } from '../src/form-codec';
|
||||
import { useVbenForm } from '../src/use-vben-form';
|
||||
import { TestInput } from './benchmark-fixtures';
|
||||
|
||||
interface ContactValues {
|
||||
enabled: boolean;
|
||||
metadata: {
|
||||
permissions: string[];
|
||||
team: string;
|
||||
};
|
||||
name: string;
|
||||
phone: string;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
interface PerformanceFormValues extends Record<string, unknown> {
|
||||
contacts: ContactValues[];
|
||||
settings: {
|
||||
alerts: boolean;
|
||||
locale: string;
|
||||
sections: string[];
|
||||
};
|
||||
}
|
||||
|
||||
const ROW_COUNT = 100;
|
||||
|
||||
function createFormValues(): PerformanceFormValues {
|
||||
return {
|
||||
contacts: Array.from({ length: ROW_COUNT }, (_, index) => ({
|
||||
enabled: index % 2 === 0,
|
||||
metadata: {
|
||||
permissions: ['read', 'write', 'review'],
|
||||
team: `team-${index % 10}`,
|
||||
},
|
||||
name: ` Contact ${index} `,
|
||||
phone: `10086-${index}`,
|
||||
tags: ['primary', 'on-call', `group-${index % 5}`],
|
||||
})),
|
||||
settings: {
|
||||
alerts: true,
|
||||
locale: 'zh-CN',
|
||||
sections: ['profile', 'security', 'notifications'],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const codec = {
|
||||
decode: (values: Readonly<PerformanceFormValues>) => ({ ...values }),
|
||||
encode: (values: Readonly<PerformanceFormValues>) => ({
|
||||
...values,
|
||||
contacts: values.contacts.map((contact) => ({
|
||||
...contact,
|
||||
name: contact.name.trim(),
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
const formValues = createFormValues();
|
||||
setupVbenForm({ config: {}, rules: {} });
|
||||
const [CodecForm, codecFormApi] = useVbenForm<PerformanceFormValues>({
|
||||
codec,
|
||||
schema: [
|
||||
{
|
||||
component: TestInput,
|
||||
defaultValue: formValues.contacts,
|
||||
fieldName: 'contacts',
|
||||
},
|
||||
{
|
||||
component: TestInput,
|
||||
defaultValue: formValues.settings,
|
||||
fieldName: 'settings',
|
||||
},
|
||||
],
|
||||
showDefaultActions: false,
|
||||
});
|
||||
const codecWrapper = mount(CodecForm);
|
||||
const [ArrayForm, arrayFormApi] = useVbenForm({
|
||||
schema: [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
component: TestInput,
|
||||
fieldName: 'name',
|
||||
label: 'Name',
|
||||
},
|
||||
],
|
||||
defaultValue: Array.from({ length: ROW_COUNT }, (_, index) => ({
|
||||
name: `Contact ${index}`,
|
||||
})),
|
||||
fieldName: 'contacts',
|
||||
type: 'array',
|
||||
},
|
||||
],
|
||||
});
|
||||
const arrayWrapper = mount(ArrayForm);
|
||||
await flushPromises();
|
||||
const arraySchemaPatches = [false, true].map((disabled) => ({
|
||||
componentProps: { disabled },
|
||||
fieldName: 'contacts.name',
|
||||
}));
|
||||
let arrayEditIteration = 0;
|
||||
let arraySchemaIteration = 0;
|
||||
|
||||
afterAll(() => {
|
||||
arrayWrapper.unmount();
|
||||
codecWrapper.unmount();
|
||||
});
|
||||
|
||||
describe('form codec performance', () => {
|
||||
bench(
|
||||
'encode 100 nested rows without isolation',
|
||||
() => {
|
||||
encodeFormValues(codec, formValues);
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
|
||||
bench(
|
||||
'encode 100 nested rows with isolated input',
|
||||
() => {
|
||||
codecFormApi.formatValues(formValues);
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
|
||||
bench(
|
||||
'create submit snapshot for 100 nested rows',
|
||||
async () => {
|
||||
await codecFormApi.getValueSnapshot();
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
});
|
||||
|
||||
describe('form array performance', () => {
|
||||
bench(
|
||||
'edit one field in a 100-row array',
|
||||
async () => {
|
||||
arrayEditIteration += 1;
|
||||
await arrayFormApi.setFieldValue(
|
||||
'contacts[50].name',
|
||||
`Contact ${arrayEditIteration}`,
|
||||
);
|
||||
await nextTick();
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
|
||||
bench(
|
||||
'append and remove one row from a 100-row array',
|
||||
async () => {
|
||||
arrayFormApi.form.pushFieldValue('contacts', { name: 'Temporary' });
|
||||
await nextTick();
|
||||
await arrayFormApi.form.removeFieldValue('contacts', ROW_COUNT);
|
||||
await nextTick();
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
|
||||
bench(
|
||||
'update one child schema across 100 rows',
|
||||
async () => {
|
||||
arraySchemaIteration += 1;
|
||||
arrayFormApi.updateSchema([
|
||||
arraySchemaPatches[arraySchemaIteration % 2] ?? {},
|
||||
]);
|
||||
await nextTick();
|
||||
},
|
||||
{ time: 1000, warmupTime: 200 },
|
||||
);
|
||||
});
|
||||
@@ -1,236 +0,0 @@
|
||||
import type { FormActions } from '../src/types';
|
||||
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { defineComponent, h, nextTick, watch } from 'vue';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useFormRuntime } from '../src/form-runtime';
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
|
||||
function mountRuntime(
|
||||
defaultValues: Record<string, any>,
|
||||
validator?: (input: { value: any }) => Promise<string | undefined>,
|
||||
) {
|
||||
let form: FormActions | undefined;
|
||||
const RuntimeHarness = defineComponent({
|
||||
setup() {
|
||||
const runtime = useFormRuntime(defaultValues);
|
||||
form = runtime;
|
||||
return () => {
|
||||
if (!validator) {
|
||||
return h('div');
|
||||
}
|
||||
return h(
|
||||
runtime.fieldComponent,
|
||||
{
|
||||
name: 'name',
|
||||
validators: {
|
||||
onSubmitAsync: validator,
|
||||
},
|
||||
},
|
||||
{
|
||||
default: ({ field }: Record<string, any>) =>
|
||||
h('input', {
|
||||
name: 'name',
|
||||
onBlur: field.handleBlur,
|
||||
onInput: (event: Event) => {
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) {
|
||||
field.handleChange(target.value);
|
||||
}
|
||||
},
|
||||
value: field.state.value,
|
||||
}),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
const wrapper = mount(RuntimeHarness);
|
||||
wrappers.push(wrapper);
|
||||
return { form, wrapper };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const wrapper of wrappers.splice(0)) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe('form runtime', () => {
|
||||
it('updates values and resets to defaults', async () => {
|
||||
const { form } = mountRuntime({ name: 'initial' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
await form.setFieldValue('name', 'updated');
|
||||
await nextTick();
|
||||
expect(form.values).toEqual({ name: 'updated' });
|
||||
|
||||
await form.reset();
|
||||
await nextTick();
|
||||
expect(form.values).toEqual({ name: 'initial' });
|
||||
});
|
||||
|
||||
it('preserves empty string field updates', async () => {
|
||||
const { form, wrapper } = mountRuntime(
|
||||
{ name: 'initial' },
|
||||
async () => undefined,
|
||||
);
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
await wrapper.find('input').setValue('');
|
||||
await nextTick();
|
||||
|
||||
expect(form.values).toEqual({ name: '' });
|
||||
});
|
||||
|
||||
it('exposes reactive selectors', async () => {
|
||||
const { form } = mountRuntime({ name: 'initial' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
const name = form.useSelector((state) => state.values.name);
|
||||
|
||||
await form.setFieldValue('name', 'updated');
|
||||
await nextTick();
|
||||
expect(name.value).toBe('updated');
|
||||
});
|
||||
|
||||
it('updates only changed field value selectors', async () => {
|
||||
const { form } = mountRuntime({ email: '', name: 'initial' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
const name = form.useFieldValue('name');
|
||||
const selectedValues = form.useFieldValues(['name'] as const);
|
||||
const onNameChange = vi.fn();
|
||||
const stop = watch(name, onNameChange);
|
||||
|
||||
await form.setFieldValue('email', 'ada@example.com');
|
||||
await nextTick();
|
||||
expect(onNameChange).not.toHaveBeenCalled();
|
||||
expect(selectedValues.value).toEqual(['initial']);
|
||||
|
||||
await form.setFieldValue('name', 'Ada');
|
||||
await nextTick();
|
||||
expect(onNameChange).toHaveBeenCalledOnce();
|
||||
expect(name.value).toBe('Ada');
|
||||
expect(selectedValues.value).toEqual(['Ada']);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('exposes reactive field error selectors', async () => {
|
||||
const { form } = mountRuntime({ email: '', name: '' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
const nameError = form.useFieldError('name');
|
||||
const onNameErrorChange = vi.fn();
|
||||
const stop = watch(nameError, onNameErrorChange);
|
||||
|
||||
form.setFieldError('email', 'Email error');
|
||||
await nextTick();
|
||||
expect(onNameErrorChange).not.toHaveBeenCalled();
|
||||
|
||||
form.setFieldError('name', 'Name error');
|
||||
await nextTick();
|
||||
expect(nameError.value).toBe('Name error');
|
||||
expect(onNameErrorChange).toHaveBeenCalledOnce();
|
||||
stop();
|
||||
});
|
||||
|
||||
it('validates mounted fields and clears stale errors', async () => {
|
||||
const { form } = mountRuntime({ name: '' }, async ({ value }) => {
|
||||
return value ? undefined : 'Name is required';
|
||||
});
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
expect(await form.validate()).toEqual({
|
||||
errors: { name: 'Name is required' },
|
||||
valid: false,
|
||||
});
|
||||
|
||||
await form.setFieldValue('name', 'Ada');
|
||||
await flushPromises();
|
||||
expect(await form.validateField('name')).toEqual({
|
||||
errors: {},
|
||||
valid: true,
|
||||
});
|
||||
expect(form.isFieldValid('name')).toBe(true);
|
||||
});
|
||||
|
||||
it('sets and clears manual field errors', async () => {
|
||||
const { form } = mountRuntime({ name: '' }, async () => undefined);
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
form.setFieldError('name', 'Server error');
|
||||
await nextTick();
|
||||
expect(form.getFieldError('name')).toBe('Server error');
|
||||
expect(form.meta.valid).toBe(false);
|
||||
|
||||
form.setFieldError('name');
|
||||
await nextTick();
|
||||
expect(form.getFieldError('name')).toBeUndefined();
|
||||
expect(form.meta.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('clears manual errors when resetting the form', async () => {
|
||||
const { form } = mountRuntime({ name: '' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
form.setFieldError('name', 'Server error');
|
||||
await nextTick();
|
||||
expect(form.errors).toEqual({ name: 'Server error' });
|
||||
|
||||
await form.reset();
|
||||
await nextTick();
|
||||
expect(form.errors).toEqual({});
|
||||
expect(form.meta.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('invalidates in-flight async validation when clearing validation', async () => {
|
||||
let resolveValidation: ((error: string | undefined) => void) | undefined;
|
||||
let notifyValidationStarted: (() => void) | undefined;
|
||||
const validationStarted = new Promise<void>((resolve) => {
|
||||
notifyValidationStarted = resolve;
|
||||
});
|
||||
const validator = vi.fn(() => {
|
||||
notifyValidationStarted?.();
|
||||
return new Promise<string | undefined>((resolve) => {
|
||||
resolveValidation = resolve;
|
||||
});
|
||||
});
|
||||
const { form } = mountRuntime({ name: '' }, validator);
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
const pendingValidation = form.validateField('name');
|
||||
await validationStarted;
|
||||
form.clearValidation();
|
||||
resolveValidation?.('Name is already used');
|
||||
await pendingValidation;
|
||||
await flushPromises();
|
||||
|
||||
expect(form.errors).toEqual({});
|
||||
expect(form.meta.validating).toBe(false);
|
||||
});
|
||||
|
||||
it('clears only the requested field validation state', async () => {
|
||||
const { form } = mountRuntime({ email: '', name: '' });
|
||||
expect(form).toBeDefined();
|
||||
if (!form) return;
|
||||
|
||||
form.setFieldError('name', 'Name error');
|
||||
form.setFieldError('email', 'Email error');
|
||||
await nextTick();
|
||||
|
||||
form.clearValidation('name');
|
||||
await nextTick();
|
||||
|
||||
expect(form.errors).toEqual({ email: 'Email error' });
|
||||
});
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
createArrayChildSchema,
|
||||
createFormFieldSchema,
|
||||
} from '../src/form-render/schema';
|
||||
|
||||
describe('form schema normalization', () => {
|
||||
it('resolves common component props with the field context', () => {
|
||||
const componentProps = vi.fn(({ fieldName }) => ({
|
||||
placeholder: `Enter ${fieldName}`,
|
||||
}));
|
||||
|
||||
const schema = createFormFieldSchema(
|
||||
{ component: 'VbenInput', fieldName: 'name' },
|
||||
{ commonConfig: { componentProps } },
|
||||
);
|
||||
|
||||
expect(componentProps).toHaveBeenCalledWith({ fieldName: 'name' });
|
||||
expect(schema.commonComponentProps).toEqual({
|
||||
placeholder: 'Enter name',
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves common component props objects', () => {
|
||||
const schema = createFormFieldSchema(
|
||||
{ component: 'VbenInput', fieldName: 'name' },
|
||||
{ commonConfig: { componentProps: { placeholder: 'Enter a name' } } },
|
||||
);
|
||||
|
||||
expect(schema.commonComponentProps).toEqual({
|
||||
placeholder: 'Enter a name',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves global common component props functions', () => {
|
||||
const componentProps = vi.fn(({ fieldName }) => ({
|
||||
title: `Global ${fieldName}`,
|
||||
}));
|
||||
|
||||
const schema = createFormFieldSchema(
|
||||
{ component: 'VbenInput', fieldName: 'email' },
|
||||
{ globalCommonConfig: { componentProps } },
|
||||
);
|
||||
|
||||
expect(componentProps).toHaveBeenCalledWith({ fieldName: 'email' });
|
||||
expect(schema.commonComponentProps).toEqual({ title: 'Global email' });
|
||||
});
|
||||
|
||||
it('resolves array common props with the row context', () => {
|
||||
const componentProps = vi.fn(() => ({ placeholder: 'Contact name' }));
|
||||
|
||||
const schema = createArrayChildSchema(
|
||||
{ component: 'VbenInput', fieldName: 'name' },
|
||||
{
|
||||
arrayField: 'contacts',
|
||||
commonConfig: { componentProps },
|
||||
index: 1,
|
||||
},
|
||||
);
|
||||
|
||||
expect(componentProps).toHaveBeenCalledWith({
|
||||
arrayField: 'contacts',
|
||||
fieldName: 'contacts[1].name',
|
||||
originalFieldName: 'name',
|
||||
rowIndex: 1,
|
||||
rowPath: 'contacts[1]',
|
||||
});
|
||||
expect(schema.commonComponentProps).toEqual({
|
||||
placeholder: 'Contact name',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,275 +0,0 @@
|
||||
import type {
|
||||
BaseFormComponentType,
|
||||
ExtendedFormApi,
|
||||
FormActions,
|
||||
FormContextApi,
|
||||
FormFieldOptions,
|
||||
FormItemDependencies,
|
||||
FormValidationResult,
|
||||
FormValueSnapshot,
|
||||
VbenFormAdapterOptions,
|
||||
VbenFormProps,
|
||||
} from '../src/types';
|
||||
|
||||
import { describe, expectTypeOf, it } from 'vitest';
|
||||
|
||||
import { useVbenForm } from '../src/use-vben-form';
|
||||
|
||||
interface AccountFormValues {
|
||||
email: string;
|
||||
profile: {
|
||||
nickname: string;
|
||||
};
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
interface AccountSubmitValues {
|
||||
email: string;
|
||||
nickname: string;
|
||||
roles: string;
|
||||
}
|
||||
|
||||
describe('form public types', () => {
|
||||
it('keeps the compatibility alias and stable method signatures', () => {
|
||||
expectTypeOf<FormActions>().toEqualTypeOf<FormContextApi>();
|
||||
expectTypeOf<FormActions['setFieldValue']>()
|
||||
.parameter(0)
|
||||
.toMatchTypeOf<string>();
|
||||
expectTypeOf<
|
||||
FormActions['validate']
|
||||
>().returns.resolves.toEqualTypeOf<FormValidationResult>();
|
||||
expectTypeOf<Parameters<FormActions['validate']>>().toEqualTypeOf<[]>();
|
||||
expectTypeOf<Parameters<FormActions['validateField']>>().toEqualTypeOf<
|
||||
[fieldName: string]
|
||||
>();
|
||||
});
|
||||
|
||||
it('accepts both new and deprecated rule registration options', () => {
|
||||
expectTypeOf<VbenFormAdapterOptions>().toMatchTypeOf<{
|
||||
defineRules?: Record<string, unknown>;
|
||||
rules?: Record<string, unknown>;
|
||||
}>();
|
||||
});
|
||||
|
||||
it('supports resolve and legacy dependency contracts', () => {
|
||||
const resolveDependencies: FormItemDependencies<AccountFormValues> = {
|
||||
resolve({ actions, controller, schema, values }) {
|
||||
expectTypeOf(values).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
expectTypeOf(actions).toEqualTypeOf<FormActions<AccountFormValues>>();
|
||||
expectTypeOf(controller).toEqualTypeOf<
|
||||
ExtendedFormApi<AccountFormValues>
|
||||
>();
|
||||
expectTypeOf(schema.fieldName).toEqualTypeOf<string | undefined>();
|
||||
return { disabled: !values.email, rules: null };
|
||||
},
|
||||
triggerFields: ['email'],
|
||||
};
|
||||
const legacyDependencies: FormItemDependencies<AccountFormValues> = {
|
||||
show(values) {
|
||||
expectTypeOf(values).toEqualTypeOf<Partial<AccountFormValues>>();
|
||||
return Boolean(values.email);
|
||||
},
|
||||
triggerFields: ['email'],
|
||||
};
|
||||
const fieldOptions: FormFieldOptions = {
|
||||
asyncDebounceMs: 200,
|
||||
validateOn: ['blur', 'change'],
|
||||
};
|
||||
|
||||
expectTypeOf(resolveDependencies).toMatchTypeOf<
|
||||
FormItemDependencies<AccountFormValues>
|
||||
>();
|
||||
expectTypeOf(legacyDependencies).toMatchTypeOf<
|
||||
FormItemDependencies<AccountFormValues>
|
||||
>();
|
||||
expectTypeOf(fieldOptions).toMatchTypeOf<FormFieldOptions>();
|
||||
});
|
||||
|
||||
it('propagates form value types through public APIs and callbacks', () => {
|
||||
const options: VbenFormProps<
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
AccountFormValues
|
||||
> = {
|
||||
handleSubmit(values, rawValues) {
|
||||
expectTypeOf(values).toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf(rawValues).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
},
|
||||
handleValuesChange(values, _fieldsChanged, getFormattedValues) {
|
||||
expectTypeOf(values).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
expectTypeOf(getFormattedValues()).toEqualTypeOf<AccountFormValues>();
|
||||
},
|
||||
schema: [],
|
||||
};
|
||||
const [Form, formApi] = useVbenForm<AccountFormValues>(options);
|
||||
|
||||
expectTypeOf(formApi).toEqualTypeOf<ExtendedFormApi<AccountFormValues>>();
|
||||
|
||||
function assertContextApi(
|
||||
contextApi: FormContextApi<AccountFormValues>,
|
||||
typedFormApi: ExtendedFormApi<AccountFormValues>,
|
||||
) {
|
||||
expectTypeOf(
|
||||
typedFormApi.getValues(),
|
||||
).resolves.toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf(
|
||||
typedFormApi.getRawValues(),
|
||||
).resolves.toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf(typedFormApi.getValueSnapshot()).resolves.toEqualTypeOf<{
|
||||
rawValues: Readonly<AccountFormValues>;
|
||||
values: AccountFormValues;
|
||||
}>();
|
||||
expectTypeOf(typedFormApi.setValues)
|
||||
.parameter(0)
|
||||
.toEqualTypeOf<Partial<AccountFormValues>>();
|
||||
expectTypeOf(typedFormApi.form.values).toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf(contextApi.getFieldValue('email')).toEqualTypeOf<string>();
|
||||
expectTypeOf(
|
||||
contextApi.useSelector((state) => state.values.profile.nickname),
|
||||
).toEqualTypeOf<Readonly<import('vue').Ref<string>>>();
|
||||
}
|
||||
|
||||
expectTypeOf(assertContextApi).toBeFunction();
|
||||
|
||||
type FormSlots = InstanceType<typeof Form>['$slots'];
|
||||
type EmailSlot = NonNullable<FormSlots['email']>;
|
||||
type EmailSlotProps = Parameters<EmailSlot>[0];
|
||||
type DefaultSlot = NonNullable<FormSlots['default']>;
|
||||
type DefaultSlotProps = Parameters<DefaultSlot>[0];
|
||||
|
||||
expectTypeOf<
|
||||
EmailSlotProps['field']['state']['value']
|
||||
>().toEqualTypeOf<string>();
|
||||
expectTypeOf<EmailSlotProps['values']>().toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf<
|
||||
EmailSlotProps['componentProps']['modelValue']
|
||||
>().toEqualTypeOf<string | undefined>();
|
||||
expectTypeOf<EmailSlotProps['formApi']>().toEqualTypeOf<
|
||||
ExtendedFormApi<AccountFormValues>
|
||||
>();
|
||||
expectTypeOf<
|
||||
DefaultSlotProps['values']
|
||||
>().toEqualTypeOf<AccountFormValues>();
|
||||
|
||||
const [WideForm] = useVbenForm<Record<string, unknown>>({ schema: [] });
|
||||
type WideFormSlots = InstanceType<typeof WideForm>['$slots'];
|
||||
type WideFieldSlot = NonNullable<WideFormSlots['dynamic-field']>;
|
||||
type WideFieldSlotProps = Parameters<WideFieldSlot>[0];
|
||||
|
||||
expectTypeOf<WideFieldSlotProps>().not.toBeAny();
|
||||
expectTypeOf<WideFieldSlotProps['modelValue']>().toEqualTypeOf<unknown>();
|
||||
expectTypeOf<
|
||||
WideFieldSlotProps['field']['state']['value']
|
||||
>().toEqualTypeOf<unknown>();
|
||||
expectTypeOf<
|
||||
WideFieldSlotProps['componentField']['modelValue']
|
||||
>().toEqualTypeOf<unknown>();
|
||||
expectTypeOf<WideFieldSlotProps['name']>().toBeString();
|
||||
expectTypeOf<WideFieldSlotProps['values']>().toEqualTypeOf<
|
||||
Record<string, unknown>
|
||||
>();
|
||||
});
|
||||
|
||||
it('keeps form and submit values distinct with a codec', () => {
|
||||
const options: VbenFormProps<
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
AccountFormValues,
|
||||
AccountSubmitValues
|
||||
> = {
|
||||
codec: {
|
||||
decode(values) {
|
||||
return {
|
||||
email: values.email,
|
||||
profile: { nickname: values.nickname },
|
||||
roles: values.roles.split(','),
|
||||
};
|
||||
},
|
||||
encode(values) {
|
||||
return {
|
||||
email: values.email,
|
||||
nickname: values.profile.nickname,
|
||||
roles: values.roles.join(','),
|
||||
};
|
||||
},
|
||||
},
|
||||
handleSubmit(values, rawValues) {
|
||||
expectTypeOf(values).toEqualTypeOf<AccountSubmitValues>();
|
||||
expectTypeOf(rawValues).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
},
|
||||
handleReset(values) {
|
||||
expectTypeOf(values).toEqualTypeOf<AccountSubmitValues>();
|
||||
},
|
||||
handleValuesChange(values, _fieldsChanged, getFormattedValues) {
|
||||
expectTypeOf(values).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
expectTypeOf(getFormattedValues()).toEqualTypeOf<AccountSubmitValues>();
|
||||
},
|
||||
schema: [],
|
||||
};
|
||||
const [, formApi] = useVbenForm<
|
||||
AccountFormValues,
|
||||
BaseFormComponentType,
|
||||
Record<never, never>,
|
||||
AccountSubmitValues
|
||||
>(options);
|
||||
|
||||
expectTypeOf(
|
||||
formApi.getValues(),
|
||||
).resolves.toEqualTypeOf<AccountSubmitValues>();
|
||||
expectTypeOf(
|
||||
formApi.getRawValues(),
|
||||
).resolves.toEqualTypeOf<AccountFormValues>();
|
||||
expectTypeOf(formApi.getValueSnapshot()).resolves.toEqualTypeOf<
|
||||
FormValueSnapshot<AccountFormValues, AccountSubmitValues>
|
||||
>();
|
||||
expectTypeOf(formApi.setSubmitValues)
|
||||
.parameter(0)
|
||||
.toEqualTypeOf<AccountSubmitValues>();
|
||||
});
|
||||
|
||||
it('infers submit values from an inline codec', () => {
|
||||
const [, formApi] = useVbenForm({
|
||||
codec: {
|
||||
decode(values) {
|
||||
expectTypeOf(values).toEqualTypeOf<Readonly<AccountSubmitValues>>();
|
||||
return {
|
||||
email: values.email,
|
||||
profile: { nickname: values.nickname },
|
||||
roles: values.roles.split(','),
|
||||
};
|
||||
},
|
||||
encode(values: Readonly<AccountFormValues>) {
|
||||
return {
|
||||
email: values.email,
|
||||
nickname: values.profile.nickname,
|
||||
roles: values.roles.join(','),
|
||||
};
|
||||
},
|
||||
},
|
||||
handleReset(values) {
|
||||
expectTypeOf(values).toEqualTypeOf<AccountSubmitValues>();
|
||||
},
|
||||
handleSubmit(values, rawValues) {
|
||||
expectTypeOf(values).toEqualTypeOf<AccountSubmitValues>();
|
||||
expectTypeOf(rawValues).toEqualTypeOf<Readonly<AccountFormValues>>();
|
||||
},
|
||||
schema: [],
|
||||
});
|
||||
|
||||
expectTypeOf(
|
||||
formApi.getValues(),
|
||||
).resolves.toEqualTypeOf<AccountSubmitValues>();
|
||||
expectTypeOf(
|
||||
formApi.getRawValues(),
|
||||
).resolves.toEqualTypeOf<AccountFormValues>();
|
||||
});
|
||||
|
||||
it('exposes canonical names alongside deprecated aliases', () => {
|
||||
expectTypeOf<FormContextApi['reset']>().toEqualTypeOf<
|
||||
FormContextApi['resetForm']
|
||||
>();
|
||||
expectTypeOf<FormContextApi['submit']>().toEqualTypeOf<
|
||||
FormContextApi['submitForm']
|
||||
>();
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
applyFormValueFormats,
|
||||
formatFormValues,
|
||||
transformRangeTimeValues,
|
||||
} from '../src/form-value-transform';
|
||||
|
||||
describe('form value transforms', () => {
|
||||
it('maps array and range fields without mutating input values', () => {
|
||||
const input = {
|
||||
period: [1_710_000_000_000, 1_720_000_000_000],
|
||||
tags: ['admin', 'editor'],
|
||||
};
|
||||
|
||||
const result = transformRangeTimeValues(
|
||||
input,
|
||||
[['period', ['startTime', 'endTime'], null]],
|
||||
['tags'],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
endTime: 1_720_000_000_000,
|
||||
startTime: 1_710_000_000_000,
|
||||
tags: 'admin,editor',
|
||||
});
|
||||
expect(input).toEqual({
|
||||
period: [1_710_000_000_000, 1_720_000_000_000],
|
||||
tags: ['admin', 'editor'],
|
||||
});
|
||||
});
|
||||
|
||||
it('formats array children with row and root paths', () => {
|
||||
const values = {
|
||||
contacts: [{ name: ' Ada ' }, { name: ' Grace ' }],
|
||||
};
|
||||
const schema = [
|
||||
{
|
||||
children: [
|
||||
{
|
||||
component: 'text',
|
||||
fieldName: 'name',
|
||||
valueFormat(value: string, setValue: any, _values: any, ctx: any) {
|
||||
setValue('$row.normalizedName', value.trim());
|
||||
setValue('$root.lastRow', ctx.rowIndex);
|
||||
},
|
||||
},
|
||||
],
|
||||
fieldName: 'contacts',
|
||||
type: 'array',
|
||||
},
|
||||
] as any;
|
||||
|
||||
const result = applyFormValueFormats(values, schema);
|
||||
|
||||
expect(result).toEqual({
|
||||
contacts: [{ normalizedName: 'Ada' }, { normalizedName: 'Grace' }],
|
||||
lastRow: 1,
|
||||
});
|
||||
expect(values).toEqual({
|
||||
contacts: [{ name: ' Ada ' }, { name: ' Grace ' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('runs the unified formatting pipeline in a stable order', () => {
|
||||
const result = formatFormValues(
|
||||
{
|
||||
period: [1, 2],
|
||||
tags: ['admin', 'editor'],
|
||||
title: ' Ada ',
|
||||
},
|
||||
[
|
||||
{
|
||||
component: 'text',
|
||||
fieldName: 'title',
|
||||
valueFormat: (value: string) => value.trim(),
|
||||
},
|
||||
],
|
||||
[['period', ['startTime', 'endTime'], null]],
|
||||
['tags'],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
endTime: 2,
|
||||
startTime: 1,
|
||||
tags: 'admin,editor',
|
||||
title: 'Ada',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
/* eslint-disable vue/one-component-per-file */
|
||||
|
||||
import type { PropType } from 'vue';
|
||||
|
||||
import type { FormLayout, FormRenderProps } from '../src/types';
|
||||
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { defineComponent, h, reactive, toRefs } from 'vue';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
provideFormRenderProps,
|
||||
useFormContext,
|
||||
} from '../src/form-render/context';
|
||||
import { resolveLabelStyle, useFormLabelWidth } from '../src/form-render/utils';
|
||||
|
||||
describe('form label width context', () => {
|
||||
it('keeps layout reactive when label width context is provided', async () => {
|
||||
const Consumer = defineComponent({
|
||||
setup() {
|
||||
const { isVertical } = useFormContext();
|
||||
return () =>
|
||||
h('div', {
|
||||
'data-layout': isVertical.value ? 'vertical' : 'horizontal',
|
||||
});
|
||||
},
|
||||
});
|
||||
const Provider = defineComponent({
|
||||
props: {
|
||||
layout: {
|
||||
required: true,
|
||||
type: String as PropType<FormLayout>,
|
||||
},
|
||||
},
|
||||
setup(props) {
|
||||
provideFormRenderProps(
|
||||
reactive({
|
||||
...toRefs(props as FormRenderProps),
|
||||
...useFormLabelWidth(),
|
||||
}),
|
||||
);
|
||||
return () => h(Consumer);
|
||||
},
|
||||
});
|
||||
const wrapper = mount(Provider, {
|
||||
props: { layout: 'horizontal' },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-layout]').attributes('data-layout')).toBe(
|
||||
'horizontal',
|
||||
);
|
||||
|
||||
await wrapper.setProps({ layout: 'vertical' });
|
||||
|
||||
expect(wrapper.get('[data-layout]').attributes('data-layout')).toBe(
|
||||
'vertical',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveLabelStyle', () => {
|
||||
it('returns empty style for vertical layout', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: 'auto',
|
||||
labelClass: undefined,
|
||||
isVertical: true,
|
||||
autoLabelWidth: '120px',
|
||||
computedWidth: 80,
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it('returns empty style when labelClass includes w-', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: 100,
|
||||
labelClass: 'w-32',
|
||||
isVertical: false,
|
||||
autoLabelWidth: '120px',
|
||||
computedWidth: 80,
|
||||
}),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it('aligns auto width with max label using marginLeft by default', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: 'auto',
|
||||
labelClass: undefined,
|
||||
isVertical: false,
|
||||
autoLabelWidth: '120px',
|
||||
computedWidth: 80,
|
||||
}),
|
||||
).toEqual({
|
||||
width: 'auto',
|
||||
marginLeft: '40px',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses marginRight when labelClass is justify-start', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: 'auto',
|
||||
labelClass: 'justify-start',
|
||||
isVertical: false,
|
||||
autoLabelWidth: '100px',
|
||||
computedWidth: 60,
|
||||
}),
|
||||
).toEqual({
|
||||
width: 'auto',
|
||||
marginRight: '40px',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses numeric labelWidth as px', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: 100,
|
||||
labelClass: undefined,
|
||||
isVertical: false,
|
||||
autoLabelWidth: '0',
|
||||
computedWidth: 0,
|
||||
}),
|
||||
).toEqual({ width: '100px' });
|
||||
});
|
||||
|
||||
it('passes through string labelWidth', () => {
|
||||
expect(
|
||||
resolveLabelStyle({
|
||||
labelWidth: '8rem',
|
||||
labelClass: undefined,
|
||||
isVertical: false,
|
||||
autoLabelWidth: '0',
|
||||
computedWidth: 0,
|
||||
}),
|
||||
).toEqual({ width: '8rem' });
|
||||
});
|
||||
});
|
||||
@@ -1,69 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { z, ZodString } from 'zod';
|
||||
import { getDefaultsForSchema } from 'zod-defaults';
|
||||
|
||||
import {
|
||||
getBaseRules,
|
||||
getDefaultValueInZodStack,
|
||||
} from '../src/form-render/helper';
|
||||
|
||||
describe('zod v4 schema helpers', () => {
|
||||
it('unwraps optional and default schemas with public APIs', () => {
|
||||
const schema = z.string().default('default value').optional();
|
||||
|
||||
expect(getBaseRules(schema)).toBeInstanceOf(ZodString);
|
||||
expect(getDefaultValueInZodStack(schema)).toBe('default value');
|
||||
});
|
||||
|
||||
it('unwraps the input side of a transform pipe', () => {
|
||||
const schema = z.string().transform((value) => value.length);
|
||||
|
||||
expect(getBaseRules(schema)).toBeInstanceOf(ZodString);
|
||||
});
|
||||
|
||||
it('returns undefined when a schema rejects undefined', () => {
|
||||
expect(getDefaultValueInZodStack(z.string())).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not throw for an asynchronous default pipeline', () => {
|
||||
const schema = z
|
||||
.string()
|
||||
.default('default value')
|
||||
.transform(async (value) => value.toUpperCase());
|
||||
|
||||
expect(getDefaultValueInZodStack(schema)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses zod v4 error callbacks for required and invalid inputs', () => {
|
||||
const schema = z.number({
|
||||
error: (issue) =>
|
||||
issue.input === undefined ? 'required' : 'invalid number',
|
||||
});
|
||||
|
||||
expect(schema.safeParse(undefined).error?.issues[0]?.message).toBe(
|
||||
'required',
|
||||
);
|
||||
expect(schema.safeParse('1').error?.issues[0]?.message).toBe(
|
||||
'invalid number',
|
||||
);
|
||||
});
|
||||
|
||||
it('extracts defaults from intersections without private schema access', () => {
|
||||
const schema = z.intersection(
|
||||
z.object({ enabled: z.boolean().default(true), name: z.string() }),
|
||||
z.object({ count: z.number(), note: z.string().default('note') }),
|
||||
);
|
||||
|
||||
expect(getDefaultsForSchema(schema)).toEqual({
|
||||
count: 0,
|
||||
enabled: true,
|
||||
name: '',
|
||||
note: 'note',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps nullable and coerce input semantics explicit', () => {
|
||||
expect(z.string().nullable().safeParse(undefined).success).toBe(false);
|
||||
expect(z.coerce.number().parse('42')).toBe(42);
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { resolveHeaderHiddenOnScroll } from '../header-scroll-state';
|
||||
|
||||
const baseOptions = {
|
||||
arrivedTop: false,
|
||||
currentHidden: false,
|
||||
directionDown: false,
|
||||
directionUp: false,
|
||||
headerHeight: 90,
|
||||
scrollTop: 120,
|
||||
};
|
||||
|
||||
describe('resolveHeaderHiddenOnScroll', () => {
|
||||
it('should show the header near the top', () => {
|
||||
expect(
|
||||
resolveHeaderHiddenOnScroll({
|
||||
...baseOptions,
|
||||
directionDown: true,
|
||||
scrollTop: 89,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should show the header when the top is reached', () => {
|
||||
expect(
|
||||
resolveHeaderHiddenOnScroll({
|
||||
...baseOptions,
|
||||
arrivedTop: true,
|
||||
currentHidden: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should show the header while scrolling up', () => {
|
||||
expect(
|
||||
resolveHeaderHiddenOnScroll({
|
||||
...baseOptions,
|
||||
currentHidden: true,
|
||||
directionUp: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('should hide the header while scrolling down', () => {
|
||||
expect(
|
||||
resolveHeaderHiddenOnScroll({
|
||||
...baseOptions,
|
||||
directionDown: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should preserve the current state without a direction', () => {
|
||||
expect(
|
||||
resolveHeaderHiddenOnScroll({
|
||||
...baseOptions,
|
||||
currentHidden: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,125 +0,0 @@
|
||||
import type { DrawerState } from '../drawer';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { DrawerApi } from '../drawer-api';
|
||||
|
||||
// 模拟 Store 类
|
||||
vi.mock('@vben-core/shared/store', () => {
|
||||
return {
|
||||
isFunction: (fn: any) => typeof fn === 'function',
|
||||
Store: class {
|
||||
get state() {
|
||||
return this._state;
|
||||
}
|
||||
private _state: DrawerState;
|
||||
private subscribers: Array<(state: DrawerState) => void> = [];
|
||||
|
||||
constructor(initialState: DrawerState) {
|
||||
this._state = initialState;
|
||||
}
|
||||
|
||||
setState(fn: (prev: DrawerState) => DrawerState) {
|
||||
this._state = fn(this._state);
|
||||
this.subscribers.forEach((sub) => sub(this._state));
|
||||
}
|
||||
|
||||
subscribe(fn: (state: DrawerState) => void) {
|
||||
this.subscribers.push(fn);
|
||||
return { unsubscribe: () => {} };
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('drawerApi', () => {
|
||||
let drawerApi: DrawerApi;
|
||||
let drawerState: DrawerState;
|
||||
|
||||
beforeEach(() => {
|
||||
drawerApi = new DrawerApi();
|
||||
drawerState = drawerApi.store.state;
|
||||
});
|
||||
|
||||
it('should initialize with default state', () => {
|
||||
expect(drawerState.isOpen).toBe(false);
|
||||
expect(drawerState.cancelText).toBe(undefined);
|
||||
expect(drawerState.confirmText).toBe(undefined);
|
||||
});
|
||||
|
||||
it('should open the drawer', () => {
|
||||
drawerApi.open();
|
||||
expect(drawerApi.store.state.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('should close the drawer if onBeforeClose allows it', () => {
|
||||
drawerApi.close();
|
||||
expect(drawerApi.store.state.isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it('should not close the drawer if onBeforeClose returns false', () => {
|
||||
const onBeforeClose = vi.fn(() => false);
|
||||
const drawerApiWithHook = new DrawerApi({ onBeforeClose });
|
||||
drawerApiWithHook.open();
|
||||
drawerApiWithHook.close();
|
||||
expect(drawerApiWithHook.store.state.isOpen).toBe(true);
|
||||
expect(onBeforeClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should trigger onCancel and keep drawer open if onCancel is provided', () => {
|
||||
const onCancel = vi.fn();
|
||||
const drawerApiWithHook = new DrawerApi({ onCancel });
|
||||
drawerApiWithHook.open();
|
||||
drawerApiWithHook.onCancel();
|
||||
expect(onCancel).toHaveBeenCalled();
|
||||
expect(drawerApiWithHook.store.state.isOpen).toBe(true); // 关闭逻辑不在 onCancel 内
|
||||
});
|
||||
|
||||
it('should update shared data correctly', () => {
|
||||
const testData = { key: 'value' };
|
||||
drawerApi.setData(testData);
|
||||
expect(drawerApi.getData()).toEqual(testData);
|
||||
});
|
||||
|
||||
it('should return undefined before shared data is set', () => {
|
||||
expect(drawerApi.getData()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should preserve null shared data', () => {
|
||||
const nullableDrawerApi = new DrawerApi<null | Record<string, unknown>>();
|
||||
nullableDrawerApi.setData(null);
|
||||
expect(nullableDrawerApi.getData()).toBeNull();
|
||||
});
|
||||
|
||||
it('should set state correctly using an object', () => {
|
||||
drawerApi.setState({ title: 'New Title' });
|
||||
expect(drawerApi.store.state.title).toBe('New Title');
|
||||
});
|
||||
|
||||
it('should set state correctly using a function', () => {
|
||||
drawerApi.setState((prev) => ({ ...prev, confirmText: 'Yes' }));
|
||||
expect(drawerApi.store.state.confirmText).toBe('Yes');
|
||||
});
|
||||
|
||||
it('should call onOpenChange when state changes', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const drawerApiWithHook = new DrawerApi({ onOpenChange });
|
||||
drawerApiWithHook.open();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call onClosed callback when provided', () => {
|
||||
const onClosed = vi.fn();
|
||||
const drawerApiWithHook = new DrawerApi({ onClosed });
|
||||
drawerApiWithHook.onClosed();
|
||||
expect(onClosed).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call onOpened callback when provided', () => {
|
||||
const onOpened = vi.fn();
|
||||
const drawerApiWithHook = new DrawerApi({ onOpened });
|
||||
drawerApiWithHook.open();
|
||||
drawerApiWithHook.onOpened();
|
||||
expect(onOpened).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import type { ExtendedDrawerApi, InferDrawerData } from '../drawer';
|
||||
import type { createVbenDrawer, useVbenDrawer } from '../use-drawer';
|
||||
import type TypedDrawer from './fixtures/typed-drawer.vue';
|
||||
|
||||
import { describe, expectTypeOf, it } from 'vitest';
|
||||
|
||||
interface TypedDrawerData {
|
||||
id: number;
|
||||
mode: 'edit' | 'view';
|
||||
}
|
||||
|
||||
type DrawerData = null | TypedDrawerData;
|
||||
|
||||
declare const createDrawer: typeof createVbenDrawer;
|
||||
declare const useDrawer: typeof useVbenDrawer;
|
||||
|
||||
describe('drawer public data types', () => {
|
||||
it('infers data from the connected component exposed api', () => {
|
||||
function assertInferredData(connectedComponent: typeof TypedDrawer) {
|
||||
const [, drawerApi] = useDrawer({ connectedComponent });
|
||||
|
||||
expectTypeOf(drawerApi).toEqualTypeOf<ExtendedDrawerApi<DrawerData>>();
|
||||
expectTypeOf(drawerApi.getData()).toEqualTypeOf<DrawerData | undefined>();
|
||||
expectTypeOf(drawerApi.setData).parameter(0).toEqualTypeOf<DrawerData>();
|
||||
expectTypeOf(drawerApi.setData(null).open()).toBeVoid();
|
||||
// @ts-expect-error invalid payload type
|
||||
drawerApi.setData({ id: '1', mode: 'edit' });
|
||||
}
|
||||
|
||||
expectTypeOf<
|
||||
InferDrawerData<typeof TypedDrawer>
|
||||
>().toEqualTypeOf<DrawerData>();
|
||||
expectTypeOf(assertInferredData).toBeFunction();
|
||||
});
|
||||
|
||||
it('supports explicit and pre-bound data contracts', () => {
|
||||
function assertExplicitData() {
|
||||
const [, explicitApi] = useDrawer<DrawerData>();
|
||||
const useTypedDrawer = createDrawer<DrawerData>();
|
||||
const [, preBoundApi] = useTypedDrawer();
|
||||
|
||||
expectTypeOf(explicitApi).toEqualTypeOf<ExtendedDrawerApi<DrawerData>>();
|
||||
expectTypeOf(preBoundApi).toEqualTypeOf<ExtendedDrawerApi<DrawerData>>();
|
||||
}
|
||||
|
||||
expectTypeOf(assertExplicitData).toBeFunction();
|
||||
});
|
||||
|
||||
it('falls back to unknown without a data contract', () => {
|
||||
function assertUnknownData() {
|
||||
const [, drawerApi] = useDrawer();
|
||||
|
||||
expectTypeOf(drawerApi).toEqualTypeOf<ExtendedDrawerApi<unknown>>();
|
||||
expectTypeOf(drawerApi.getData()).toBeUnknown();
|
||||
}
|
||||
|
||||
expectTypeOf(assertUnknownData).toBeFunction();
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { App } from 'vue';
|
||||
|
||||
import { createApp, defineComponent, h, nextTick } from 'vue';
|
||||
|
||||
import { ELEMENT_ID_MAIN_CONTENT } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useVbenDrawer } from '../use-drawer';
|
||||
|
||||
vi.mock('@vben-core/preferences', () => ({
|
||||
usePreferences: () => ({
|
||||
globalEscapeShortcutKey: { value: true },
|
||||
}),
|
||||
}));
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
async function mountPreopenedDrawer() {
|
||||
const mainContent = document.createElement('main');
|
||||
mainContent.id = ELEMENT_ID_MAIN_CONTENT;
|
||||
mainContent.innerHTML = '<div><div></div></div>';
|
||||
document.body.append(mainContent);
|
||||
|
||||
const Consumer = defineComponent(() => {
|
||||
const [Drawer, drawerApi] = useVbenDrawer({ appendToMain: true });
|
||||
drawerApi.open();
|
||||
return () => h(Drawer);
|
||||
});
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp(() => h(Consumer));
|
||||
activeApp.mount(host);
|
||||
await nextTick();
|
||||
|
||||
return mainContent;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('vben drawer', () => {
|
||||
it('mounts an initially open drawer directly in the main content', async () => {
|
||||
const mainContent = await mountPreopenedDrawer();
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
|
||||
expect(dialog).toBeInstanceOf(HTMLElement);
|
||||
if (!(dialog instanceof HTMLElement)) return;
|
||||
expect(dialog.parentElement).toBe(mainContent);
|
||||
});
|
||||
|
||||
it('shows a drawer that is opened before mounting', async () => {
|
||||
await mountPreopenedDrawer();
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
|
||||
expect(dialog).toBeInstanceOf(HTMLElement);
|
||||
if (!(dialog instanceof HTMLElement)) return;
|
||||
expect(dialog.classList.contains('hidden')).toBe(false);
|
||||
});
|
||||
});
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { useVbenDrawer } from '../../use-drawer';
|
||||
|
||||
interface TypedDrawerData {
|
||||
id: number;
|
||||
mode: 'edit' | 'view';
|
||||
}
|
||||
|
||||
const [, drawerApi] = useVbenDrawer<TypedDrawerData | null>();
|
||||
|
||||
defineExpose({ drawerApi });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div />
|
||||
</template>
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { App, Ref } from 'vue';
|
||||
|
||||
import type { ExtendedDrawerApi } from '../drawer';
|
||||
|
||||
import { createApp, defineComponent, h, nextTick, ref } from 'vue';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useVbenDrawer } from '../use-drawer';
|
||||
|
||||
vi.mock('@vben-core/preferences', () => ({
|
||||
usePreferences: () => ({
|
||||
globalEscapeShortcutKey: { value: true },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../drawer.vue', () => ({
|
||||
default: {
|
||||
name: 'VbenDrawerStub',
|
||||
render: () => null,
|
||||
},
|
||||
}));
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
async function mountRebindingHarness() {
|
||||
const consumerKey = ref(0);
|
||||
let currentApi: ExtendedDrawerApi | undefined;
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
const Consumer = defineComponent(() => {
|
||||
const [Drawer, drawerApi] = useVbenDrawer();
|
||||
currentApi = drawerApi;
|
||||
return () => h(Drawer);
|
||||
});
|
||||
|
||||
const ConnectedDrawer = defineComponent(() => {
|
||||
return () => h(Consumer, { key: consumerKey.value });
|
||||
});
|
||||
|
||||
const [ParentDrawer, parentApi] = useVbenDrawer({
|
||||
connectedComponent: ConnectedDrawer,
|
||||
onOpenChange,
|
||||
title: 'Parent drawer title',
|
||||
});
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp(() => h(ParentDrawer));
|
||||
activeApp.mount(host);
|
||||
await nextTick();
|
||||
|
||||
return {
|
||||
consumerKey,
|
||||
getCurrentApi: () => currentApi,
|
||||
onOpenChange,
|
||||
parentApi,
|
||||
};
|
||||
}
|
||||
|
||||
async function remountConsumer(consumerKey: Ref<number>) {
|
||||
consumerKey.value += 1;
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useVbenDrawer', () => {
|
||||
it('rebinds the parent api when the consumer is recreated', async () => {
|
||||
const { consumerKey, getCurrentApi, onOpenChange, parentApi } =
|
||||
await mountRebindingHarness();
|
||||
const initialApi = getCurrentApi();
|
||||
|
||||
expect(initialApi).toBeDefined();
|
||||
if (!initialApi) return;
|
||||
expect(parentApi.store).toBe(initialApi.store);
|
||||
const initialData = { id: 1 };
|
||||
parentApi.setData(initialData);
|
||||
expect(initialApi.getData()).toBe(initialData);
|
||||
|
||||
await remountConsumer(consumerKey);
|
||||
const recreatedApi = getCurrentApi();
|
||||
|
||||
expect(recreatedApi).toBeDefined();
|
||||
if (!recreatedApi) return;
|
||||
expect(recreatedApi).not.toBe(initialApi);
|
||||
expect(recreatedApi.store.state.title).toBe('Parent drawer title');
|
||||
expect(parentApi.store).toBe(recreatedApi.store);
|
||||
const recreatedData = { id: 2 };
|
||||
parentApi.setData(recreatedData);
|
||||
expect(recreatedApi.getData()).toBe(recreatedData);
|
||||
|
||||
parentApi.open();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
expect(recreatedApi.store.state.isOpen).toBe(true);
|
||||
expect(initialApi.store.state.isOpen).toBe(false);
|
||||
|
||||
await parentApi.close();
|
||||
expect(recreatedApi.store.state.isOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { useVbenModal } from '../../use-modal';
|
||||
|
||||
interface TypedModalData {
|
||||
id: number;
|
||||
mode: 'edit' | 'view';
|
||||
}
|
||||
|
||||
const [, modalApi] = useVbenModal<TypedModalData | null>();
|
||||
|
||||
defineExpose({ modalApi });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div />
|
||||
</template>
|
||||
@@ -1,126 +0,0 @@
|
||||
import type { ModalState } from '../modal';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ModalApi } from '../modal-api';
|
||||
|
||||
vi.mock('@vben-core/shared/store', () => {
|
||||
return {
|
||||
isFunction: (fn: any) => typeof fn === 'function',
|
||||
Store: class {
|
||||
get state() {
|
||||
return this._state;
|
||||
}
|
||||
private _state: ModalState;
|
||||
private subscribers: Array<(state: ModalState) => void> = [];
|
||||
|
||||
constructor(initialState: ModalState) {
|
||||
this._state = initialState;
|
||||
}
|
||||
|
||||
setState(fn: (prev: ModalState) => ModalState) {
|
||||
this._state = fn(this._state);
|
||||
this.subscribers.forEach((sub) => sub(this._state));
|
||||
}
|
||||
|
||||
subscribe(fn: (state: ModalState) => void) {
|
||||
this.subscribers.push(fn);
|
||||
return { unsubscribe: () => {} };
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('modalApi', () => {
|
||||
let modalApi: ModalApi;
|
||||
// 使用 modalState 而不是 state
|
||||
let modalState: ModalState;
|
||||
|
||||
beforeEach(() => {
|
||||
modalApi = new ModalApi();
|
||||
// 获取 modalApi 内的 state
|
||||
modalState = modalApi.store.state;
|
||||
});
|
||||
|
||||
it('should initialize with default state', () => {
|
||||
expect(modalState.isOpen).toBe(false);
|
||||
expect(modalState.cancelText).toBe(undefined);
|
||||
expect(modalState.confirmText).toBe(undefined);
|
||||
});
|
||||
|
||||
it('should open the modal', () => {
|
||||
modalApi.open();
|
||||
expect(modalApi.store.state.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('should close the modal if onBeforeClose allows it', () => {
|
||||
modalApi.close();
|
||||
expect(modalApi.store.state.isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it('should not close the modal if onBeforeClose returns false', () => {
|
||||
const onBeforeClose = vi.fn(() => false);
|
||||
const modalApiWithHook = new ModalApi({ onBeforeClose });
|
||||
modalApiWithHook.open();
|
||||
modalApiWithHook.close();
|
||||
expect(modalApiWithHook.store.state.isOpen).toBe(true);
|
||||
expect(onBeforeClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should trigger onCancel and close the modal if no onCancel hook is provided', () => {
|
||||
const onCancel = vi.fn();
|
||||
const modalApiWithHook = new ModalApi({ onCancel });
|
||||
modalApiWithHook.open();
|
||||
modalApiWithHook.onCancel();
|
||||
expect(onCancel).toHaveBeenCalled();
|
||||
expect(modalApiWithHook.store.state.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('should update shared data correctly', () => {
|
||||
const testData = { key: 'value' };
|
||||
modalApi.setData(testData);
|
||||
expect(modalApi.getData()).toEqual(testData);
|
||||
});
|
||||
|
||||
it('should return undefined before shared data is set', () => {
|
||||
expect(modalApi.getData()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should preserve null shared data', () => {
|
||||
const nullableModalApi = new ModalApi<null | Record<string, unknown>>();
|
||||
nullableModalApi.setData(null);
|
||||
expect(nullableModalApi.getData()).toBeNull();
|
||||
});
|
||||
|
||||
it('should set state correctly using an object', () => {
|
||||
modalApi.setState({ title: 'New Title' });
|
||||
expect(modalApi.store.state.title).toBe('New Title');
|
||||
});
|
||||
|
||||
it('should set state correctly using a function', () => {
|
||||
modalApi.setState((prev) => ({ ...prev, confirmText: 'Yes' }));
|
||||
expect(modalApi.store.state.confirmText).toBe('Yes');
|
||||
});
|
||||
|
||||
it('should call onOpenChange when state changes', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const modalApiWithHook = new ModalApi({ onOpenChange });
|
||||
modalApiWithHook.open();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call onClosed callback when provided', () => {
|
||||
const onClosed = vi.fn();
|
||||
const modalApiWithHook = new ModalApi({ onClosed });
|
||||
modalApiWithHook.onClosed();
|
||||
expect(onClosed).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call onOpened callback when provided', () => {
|
||||
const onOpened = vi.fn();
|
||||
const modalApiWithHook = new ModalApi({ onOpened });
|
||||
modalApiWithHook.open();
|
||||
modalApiWithHook.onOpened();
|
||||
expect(onOpened).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import type { ExtendedModalApi, InferModalData } from '../modal';
|
||||
import type { createVbenModal, useVbenModal } from '../use-modal';
|
||||
import type TypedModal from './fixtures/typed-modal.vue';
|
||||
|
||||
import { describe, expectTypeOf, it } from 'vitest';
|
||||
|
||||
interface TypedModalData {
|
||||
id: number;
|
||||
mode: 'edit' | 'view';
|
||||
}
|
||||
|
||||
type ModalData = null | TypedModalData;
|
||||
|
||||
declare const createModal: typeof createVbenModal;
|
||||
declare const useModal: typeof useVbenModal;
|
||||
|
||||
describe('modal public data types', () => {
|
||||
it('infers data from the connected component exposed api', () => {
|
||||
function assertInferredData(connectedComponent: typeof TypedModal) {
|
||||
const [, modalApi] = useModal({ connectedComponent });
|
||||
|
||||
expectTypeOf(modalApi).toEqualTypeOf<ExtendedModalApi<ModalData>>();
|
||||
expectTypeOf(modalApi.getData()).toEqualTypeOf<ModalData | undefined>();
|
||||
expectTypeOf(modalApi.setData).parameter(0).toEqualTypeOf<ModalData>();
|
||||
expectTypeOf(modalApi.setData(null).open()).toBeVoid();
|
||||
// @ts-expect-error invalid payload type
|
||||
modalApi.setData({ id: '1', mode: 'edit' });
|
||||
}
|
||||
|
||||
expectTypeOf<
|
||||
InferModalData<typeof TypedModal>
|
||||
>().toEqualTypeOf<ModalData>();
|
||||
expectTypeOf(assertInferredData).toBeFunction();
|
||||
});
|
||||
|
||||
it('supports explicit and pre-bound data contracts', () => {
|
||||
function assertExplicitData() {
|
||||
const [, explicitApi] = useModal<ModalData>();
|
||||
const useTypedModal = createModal<ModalData>();
|
||||
const [, preBoundApi] = useTypedModal();
|
||||
|
||||
expectTypeOf(explicitApi).toEqualTypeOf<ExtendedModalApi<ModalData>>();
|
||||
expectTypeOf(preBoundApi).toEqualTypeOf<ExtendedModalApi<ModalData>>();
|
||||
}
|
||||
|
||||
expectTypeOf(assertExplicitData).toBeFunction();
|
||||
});
|
||||
|
||||
it('falls back to unknown without a data contract', () => {
|
||||
function assertUnknownData() {
|
||||
const [, modalApi] = useModal();
|
||||
|
||||
expectTypeOf(modalApi).toEqualTypeOf<ExtendedModalApi<unknown>>();
|
||||
expectTypeOf(modalApi.getData()).toBeUnknown();
|
||||
}
|
||||
|
||||
expectTypeOf(assertUnknownData).toBeFunction();
|
||||
});
|
||||
});
|
||||
@@ -1,158 +0,0 @@
|
||||
import type { App } from 'vue';
|
||||
|
||||
import { createApp, defineComponent, h, nextTick, onMounted } from 'vue';
|
||||
|
||||
import { ELEMENT_ID_MAIN_CONTENT } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useVbenModal } from '../use-modal';
|
||||
|
||||
vi.mock('@vben-core/preferences', () => ({
|
||||
usePreferences: () => ({
|
||||
globalEscapeShortcutKey: { value: true },
|
||||
}),
|
||||
}));
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
async function mountModal(options: { onClosed?: () => void } = {}) {
|
||||
const mainContent = document.createElement('main');
|
||||
mainContent.id = ELEMENT_ID_MAIN_CONTENT;
|
||||
mainContent.innerHTML = '<div><div></div></div>';
|
||||
document.body.append(mainContent);
|
||||
|
||||
let capturedApi: ReturnType<typeof useVbenModal>[1] | undefined;
|
||||
const Consumer = defineComponent(() => {
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
appendToMain: true,
|
||||
draggable: true,
|
||||
title: 'Draggable modal',
|
||||
...(options.onClosed ? { onClosed: options.onClosed } : {}),
|
||||
});
|
||||
capturedApi = modalApi;
|
||||
onMounted(() => {
|
||||
modalApi.open();
|
||||
});
|
||||
return () => h(Modal);
|
||||
});
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp(() => h(Consumer));
|
||||
activeApp.mount(host);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
|
||||
if (!capturedApi) {
|
||||
throw new Error('modal api was not captured');
|
||||
}
|
||||
return { mainContent, modalApi: capturedApi };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('vben modal', () => {
|
||||
it('mounts an open modal directly in the main content', async () => {
|
||||
const { mainContent } = await mountModal();
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
const overlay = document.querySelector('[data-dismissable-modal]');
|
||||
|
||||
expect(dialog).toBeInstanceOf(HTMLElement);
|
||||
if (!(dialog instanceof HTMLElement)) return;
|
||||
expect(overlay).toBeInstanceOf(HTMLElement);
|
||||
if (!(overlay instanceof HTMLElement)) return;
|
||||
expect(dialog.parentElement).toBe(mainContent);
|
||||
expect(overlay.parentElement).toBe(mainContent);
|
||||
});
|
||||
|
||||
it('constrains dragging to the main content', async () => {
|
||||
const { mainContent } = await mountModal();
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
const header = document.querySelector('.cursor-move');
|
||||
|
||||
expect(dialog).toBeInstanceOf(HTMLElement);
|
||||
if (!(dialog instanceof HTMLElement)) return;
|
||||
expect(header).toBeInstanceOf(HTMLElement);
|
||||
if (!(header instanceof HTMLElement)) return;
|
||||
|
||||
vi.spyOn(mainContent, 'getBoundingClientRect').mockReturnValue(
|
||||
new DOMRect(100, 100, 800, 600),
|
||||
);
|
||||
vi.spyOn(dialog, 'getBoundingClientRect').mockReturnValue(
|
||||
new DOMRect(300, 200, 400, 300),
|
||||
);
|
||||
|
||||
header.dispatchEvent(
|
||||
new MouseEvent('mousedown', {
|
||||
bubbles: true,
|
||||
clientX: 400,
|
||||
clientY: 300,
|
||||
}),
|
||||
);
|
||||
document.dispatchEvent(
|
||||
new MouseEvent('mousemove', {
|
||||
clientX: 1400,
|
||||
clientY: 1300,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dialog.style.transform).toBe('translate(200px, 200px)');
|
||||
document.dispatchEvent(new MouseEvent('mouseup'));
|
||||
});
|
||||
|
||||
it('fires onClosed via the fallback when no animation event arrives', async () => {
|
||||
vi.useFakeTimers({
|
||||
toFake: [
|
||||
'cancelAnimationFrame',
|
||||
'clearTimeout',
|
||||
'requestAnimationFrame',
|
||||
'setTimeout',
|
||||
],
|
||||
});
|
||||
try {
|
||||
const onClosed = vi.fn();
|
||||
const { modalApi } = await mountModal({ onClosed });
|
||||
// happy-dom fires no animation events — without the fallback the
|
||||
// `closed` event (and with it `onClosed`) would never fire and the
|
||||
// close chain would hang. The fallback timer must acknowledge it.
|
||||
await modalApi.close();
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
expect(onClosed).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('emits closed exactly once when the animation event and the fallback both fire', async () => {
|
||||
vi.useFakeTimers({
|
||||
toFake: [
|
||||
'cancelAnimationFrame',
|
||||
'clearTimeout',
|
||||
'requestAnimationFrame',
|
||||
'setTimeout',
|
||||
],
|
||||
});
|
||||
try {
|
||||
const onClosed = vi.fn();
|
||||
const { modalApi } = await mountModal({ onClosed });
|
||||
await modalApi.close();
|
||||
// The exit animation ends normally — acknowledged immediately...
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
if (!(dialog instanceof HTMLElement)) {
|
||||
throw new Error('dialog content not found');
|
||||
}
|
||||
dialog.dispatchEvent(new Event('animationend'));
|
||||
// ...and the fallback must not emit a second `closed`.
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
expect(onClosed).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { App, Ref } from 'vue';
|
||||
|
||||
import type { ExtendedModalApi } from '../modal';
|
||||
|
||||
import { createApp, defineComponent, h, nextTick, ref, toRaw } from 'vue';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useVbenModal } from '../use-modal';
|
||||
|
||||
vi.mock('@vben-core/preferences', () => ({
|
||||
usePreferences: () => ({
|
||||
globalEscapeShortcutKey: { value: true },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../modal.vue', () => ({
|
||||
default: {
|
||||
name: 'VbenModalStub',
|
||||
render: () => null,
|
||||
},
|
||||
}));
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
async function mountRebindingHarness() {
|
||||
const consumerKey = ref(0);
|
||||
let currentApi: ExtendedModalApi | undefined;
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
const Consumer = defineComponent(() => {
|
||||
const [Modal, modalApi] = useVbenModal();
|
||||
currentApi = modalApi;
|
||||
return () => h(Modal);
|
||||
});
|
||||
|
||||
const ConnectedModal = defineComponent(() => {
|
||||
return () => h(Consumer, { key: consumerKey.value });
|
||||
});
|
||||
|
||||
const [ParentModal, parentApi] = useVbenModal({
|
||||
connectedComponent: ConnectedModal,
|
||||
onOpenChange,
|
||||
title: 'Parent modal title',
|
||||
});
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
|
||||
activeApp = createApp(() => h(ParentModal));
|
||||
activeApp.mount(host);
|
||||
await nextTick();
|
||||
|
||||
return {
|
||||
consumerKey,
|
||||
getCurrentApi: () => currentApi,
|
||||
onOpenChange,
|
||||
parentApi,
|
||||
};
|
||||
}
|
||||
|
||||
async function remountConsumer(consumerKey: Ref<number>) {
|
||||
consumerKey.value += 1;
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useVbenModal', () => {
|
||||
it('rebinds the parent api when the consumer is recreated', async () => {
|
||||
const { consumerKey, getCurrentApi, onOpenChange, parentApi } =
|
||||
await mountRebindingHarness();
|
||||
const initialApi = getCurrentApi();
|
||||
|
||||
expect(initialApi).toBeDefined();
|
||||
if (!initialApi) return;
|
||||
expect(toRaw(parentApi.store)).toBe(initialApi.store);
|
||||
const initialData = { id: 1 };
|
||||
parentApi.setData(initialData);
|
||||
expect(initialApi.getData()).toBe(initialData);
|
||||
|
||||
await remountConsumer(consumerKey);
|
||||
const recreatedApi = getCurrentApi();
|
||||
|
||||
expect(recreatedApi).toBeDefined();
|
||||
if (!recreatedApi) return;
|
||||
expect(recreatedApi).not.toBe(initialApi);
|
||||
expect(recreatedApi.store.state.title).toBe('Parent modal title');
|
||||
expect(toRaw(parentApi.store)).toBe(recreatedApi.store);
|
||||
const recreatedData = { id: 2 };
|
||||
parentApi.setData(recreatedData);
|
||||
expect(recreatedApi.getData()).toBe(recreatedData);
|
||||
|
||||
parentApi.open();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
expect(recreatedApi.store.state.isOpen).toBe(true);
|
||||
expect(initialApi.store.state.isOpen).toBe(false);
|
||||
|
||||
await parentApi.close();
|
||||
expect(recreatedApi.store.state.isOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,240 +0,0 @@
|
||||
import type { RouteRecordRaw } from '@vben/types';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { generateAccessible } from '../accessible';
|
||||
|
||||
// generateAccessible 会操作传入的 router 实例。这里用最小 stub 覆盖它实际调用的方法:
|
||||
// - getRoutes(): 返回 [] -> 不存在根路由 '/', 走 router.addRoute 分支
|
||||
// - addRoute/removeRoute: 空实现
|
||||
// 我们只断言返回的 accessibleRoutes 上自动生成的 redirect。
|
||||
function createRouterStub() {
|
||||
return {
|
||||
addRoute: () => {},
|
||||
getRoutes: () => [],
|
||||
removeRoute: () => {},
|
||||
} as any;
|
||||
}
|
||||
|
||||
async function generate(routes: RouteRecordRaw[]) {
|
||||
const { accessibleRoutes } = await generateAccessible('frontend', {
|
||||
router: createRouterStub(),
|
||||
routes,
|
||||
});
|
||||
return accessibleRoutes;
|
||||
}
|
||||
|
||||
function findByName(
|
||||
routes: RouteRecordRaw[],
|
||||
name: string,
|
||||
): RouteRecordRaw | undefined {
|
||||
for (const route of routes) {
|
||||
if (route.name === name) {
|
||||
return route;
|
||||
}
|
||||
if (route.children) {
|
||||
const found = findByName(route.children as RouteRecordRaw[], name);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
describe('generateAccessible - redirect normalization', () => {
|
||||
it('不为动态参数(:id)首子路由的父级生成 redirect', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'DyeSets',
|
||||
path: 'dye-sets',
|
||||
children: [
|
||||
{
|
||||
name: 'DyeSetDetail',
|
||||
path: ':id',
|
||||
meta: { hideInMenu: true, title: 'detail' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'dye-sets' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
expect(findByName(result, 'DyeSets')?.redirect).toBeUndefined();
|
||||
});
|
||||
|
||||
it('父级为对象 redirect({name}) 且含 :id 子路由时不抛异常且不生成 redirect', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'Production',
|
||||
path: '/production',
|
||||
redirect: { name: 'ProductionTasks' },
|
||||
children: [
|
||||
{
|
||||
name: 'ProductionTasks',
|
||||
path: 'production-tasks',
|
||||
children: [
|
||||
{
|
||||
name: 'ProductionTaskDetail',
|
||||
path: ':id',
|
||||
meta: { hideInMenu: true, title: 'detail' },
|
||||
},
|
||||
{
|
||||
name: 'ProductionTaskMatch',
|
||||
path: ':id/match',
|
||||
meta: { hideInMenu: true, title: 'match' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'tasks' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'production' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
// 顶级对象 redirect 保持不变
|
||||
expect(findByName(result, 'Production')?.redirect).toEqual({
|
||||
name: 'ProductionTasks',
|
||||
});
|
||||
// :id 首子路由的父级不生成 redirect
|
||||
expect(findByName(result, 'ProductionTasks')?.redirect).toBeUndefined();
|
||||
});
|
||||
|
||||
it('父级为对象 redirect 时,普通相对首子路由回退用 parent.path 拼接', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'Setting',
|
||||
path: '/setting',
|
||||
redirect: { name: 'SettingService' },
|
||||
children: [
|
||||
{
|
||||
name: 'SettingGroup',
|
||||
path: 'group',
|
||||
children: [
|
||||
{
|
||||
name: 'SettingService',
|
||||
path: 'service',
|
||||
meta: { title: 'service' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'group' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'setting' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
expect(findByName(result, 'SettingGroup')?.redirect).toBe(
|
||||
'/setting/group/service',
|
||||
);
|
||||
});
|
||||
|
||||
it('深层嵌套(上游风格)相对路径逐级生成正确的累计绝对 redirect', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'Demos',
|
||||
path: '/demos',
|
||||
children: [
|
||||
{
|
||||
name: 'NestedDemos',
|
||||
path: 'nested',
|
||||
children: [
|
||||
{
|
||||
name: 'Menu1Demo',
|
||||
path: 'menu1',
|
||||
meta: { title: 'menu1' },
|
||||
},
|
||||
{
|
||||
name: 'Menu2Demo',
|
||||
path: 'menu2',
|
||||
children: [
|
||||
{
|
||||
name: 'Menu21Demo',
|
||||
path: 'menu2-1',
|
||||
meta: { title: 'menu2-1' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'menu2' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'nested' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'demos' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
// Demos 重定向到第一级子路由,子路由继续级联到叶子
|
||||
expect(findByName(result, 'Demos')?.redirect).toBe('/demos/nested');
|
||||
expect(findByName(result, 'NestedDemos')?.redirect).toBe(
|
||||
'/demos/nested/menu1',
|
||||
);
|
||||
expect(findByName(result, 'Menu2Demo')?.redirect).toBe(
|
||||
'/demos/nested/menu2/menu2-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('首子路由为绝对路径(/foo)时不生成 redirect', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'Dashboard',
|
||||
path: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
name: 'Analytics',
|
||||
path: '/analytics',
|
||||
meta: { title: 'analytics' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'dashboard' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
expect(findByName(result, 'Dashboard')?.redirect).toBeUndefined();
|
||||
});
|
||||
|
||||
it('首子路由为空 path 时不生成 redirect', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'HideChildrenParent',
|
||||
path: 'hide-menu-children',
|
||||
children: [
|
||||
{
|
||||
name: 'HideChildren',
|
||||
path: '',
|
||||
meta: { title: 'hide' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'parent' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
expect(findByName(result, 'HideChildrenParent')?.redirect).toBeUndefined();
|
||||
});
|
||||
|
||||
it('已存在的 redirect 保持不变', async () => {
|
||||
const routes = [
|
||||
{
|
||||
name: 'Custom',
|
||||
path: '/custom',
|
||||
redirect: '/custom/keep',
|
||||
children: [
|
||||
{
|
||||
name: 'CustomChild',
|
||||
path: 'child',
|
||||
meta: { title: 'child' },
|
||||
},
|
||||
],
|
||||
meta: { title: 'custom' },
|
||||
},
|
||||
] as unknown as RouteRecordRaw[];
|
||||
|
||||
const result = await generate(routes);
|
||||
expect(findByName(result, 'Custom')?.redirect).toBe('/custom/keep');
|
||||
});
|
||||
});
|
||||
@@ -1,132 +0,0 @@
|
||||
import { mount } from '@vue/test-utils';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { Page } from '..';
|
||||
|
||||
describe('page.vue', () => {
|
||||
it('renders title when passed', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
title: 'Test Title',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('Test Title');
|
||||
});
|
||||
|
||||
it('renders description when passed', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
description: 'Test Description',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('Test Description');
|
||||
});
|
||||
|
||||
it('renders default slot content', () => {
|
||||
const wrapper = mount(Page, {
|
||||
slots: {
|
||||
default: '<p>Default Slot Content</p>',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain('<p>Default Slot Content</p>');
|
||||
});
|
||||
|
||||
it('renders footer slot when showFooter is true', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
showFooter: true,
|
||||
},
|
||||
slots: {
|
||||
footer: '<p>Footer Slot Content</p>',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain('<p>Footer Slot Content</p>');
|
||||
});
|
||||
|
||||
it('applies the custom contentClass', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
contentClass: 'custom-class',
|
||||
},
|
||||
});
|
||||
|
||||
const contentDiv = wrapper.find('.p-4');
|
||||
expect(contentDiv.classes()).toContain('custom-class');
|
||||
});
|
||||
|
||||
it('uses flex layout for automatic content height', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
autoContentHeight: true,
|
||||
heightOffset: 12,
|
||||
title: 'Auto height page',
|
||||
},
|
||||
});
|
||||
|
||||
const content = wrapper.find('[data-layout-region="page-content"]');
|
||||
const header = wrapper.find('.border-b');
|
||||
|
||||
expect(wrapper.classes()).toContain('min-h-0');
|
||||
expect(wrapper.classes()).toContain('overflow-hidden');
|
||||
expect(header.classes()).toContain('shrink-0');
|
||||
expect(content.exists()).toBe(true);
|
||||
expect(content.classes()).toContain('min-h-0');
|
||||
expect(content.classes()).toContain('flex-1');
|
||||
expect(content.classes()).toContain('overflow-y-auto');
|
||||
expect(content.attributes('style')).toContain(
|
||||
'--page-content-height-offset: 12px',
|
||||
);
|
||||
expect(content.attributes('style')).not.toContain('--vben-content-height');
|
||||
});
|
||||
|
||||
it('positions the footer according to footerFixed', async () => {
|
||||
const wrapper = mount(Page, {
|
||||
slots: {
|
||||
footer: '<p>Footer</p>',
|
||||
},
|
||||
});
|
||||
|
||||
const footer = wrapper.find('.bg-card');
|
||||
expect(footer.classes()).toContain('shrink-0');
|
||||
expect(footer.classes()).not.toContain('absolute');
|
||||
|
||||
await wrapper.setProps({ footerFixed: true });
|
||||
|
||||
expect(footer.classes()).toContain('mt-auto');
|
||||
expect(footer.classes()).toContain('shrink-0');
|
||||
expect(footer.classes()).not.toContain('absolute');
|
||||
});
|
||||
|
||||
it('does not render title slot if title prop is provided', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
title: 'Test Title',
|
||||
},
|
||||
slots: {
|
||||
title: '<p>Title Slot Content</p>',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('Title Slot Content');
|
||||
expect(wrapper.html()).not.toContain('Test Title');
|
||||
});
|
||||
|
||||
it('does not render description slot if description prop is provided', () => {
|
||||
const wrapper = mount(Page, {
|
||||
props: {
|
||||
description: 'Test Description',
|
||||
},
|
||||
slots: {
|
||||
description: '<p>Description Slot Content</p>',
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('Description Slot Content');
|
||||
expect(wrapper.html()).not.toContain('Test Description');
|
||||
});
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
import type { App } from 'vue';
|
||||
import type { NavigationGuard, NavigationHookAfter, Router } from 'vue-router';
|
||||
|
||||
import { createApp } from 'vue';
|
||||
|
||||
import { ELEMENT_ID_LAYOUT_SCROLL } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useLayoutScroll } from '../use-layout-scroll';
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
function createRouterMock() {
|
||||
let afterHook: NavigationHookAfter | undefined;
|
||||
let beforeGuard: NavigationGuard | undefined;
|
||||
const removeAfterHook = vi.fn();
|
||||
const removeBeforeGuard = vi.fn();
|
||||
|
||||
const router = {
|
||||
afterEach: vi.fn((hook: NavigationHookAfter) => {
|
||||
afterHook = hook;
|
||||
return removeAfterHook;
|
||||
}),
|
||||
beforeEach: vi.fn((guard: NavigationGuard) => {
|
||||
beforeGuard = guard;
|
||||
return removeBeforeGuard;
|
||||
}),
|
||||
} as unknown as Router;
|
||||
|
||||
function getHooks() {
|
||||
if (!afterHook || !beforeGuard) {
|
||||
throw new Error('Router hooks were not registered');
|
||||
}
|
||||
return { afterHook, beforeGuard };
|
||||
}
|
||||
|
||||
return {
|
||||
getHooks,
|
||||
removeAfterHook,
|
||||
removeBeforeGuard,
|
||||
router,
|
||||
};
|
||||
}
|
||||
|
||||
function createScrollElement() {
|
||||
const element = document.createElement('div');
|
||||
element.id = ELEMENT_ID_LAYOUT_SCROLL;
|
||||
element.scrollTo = vi.fn();
|
||||
document.body.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function mountLayoutScroll(router: Router) {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
activeApp = createApp({
|
||||
setup() {
|
||||
useLayoutScroll(router);
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
activeApp.mount(host);
|
||||
}
|
||||
|
||||
async function runBeforeGuard(guard: NavigationGuard) {
|
||||
await guard({} as never, {} as never, vi.fn());
|
||||
}
|
||||
|
||||
async function runAfterHook(hook: NavigationHookAfter, hash = '') {
|
||||
await hook({ hash } as never, {} as never, undefined);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
window.history.replaceState({}, '');
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useLayoutScroll', () => {
|
||||
it('should scroll to top after a normal navigation', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
element.scrollTop = 240;
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook, beforeGuard } = routerMock.getHooks();
|
||||
|
||||
await runBeforeGuard(beforeGuard);
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
expect(element.scrollTo).toHaveBeenCalledWith({ top: 0 });
|
||||
});
|
||||
|
||||
it('should scroll a hash target into view', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
const hashTarget = document.createElement('div');
|
||||
hashTarget.id = 'section';
|
||||
hashTarget.scrollIntoView = vi.fn();
|
||||
element.append(hashTarget);
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook } = routerMock.getHooks();
|
||||
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook, '#section');
|
||||
|
||||
expect(hashTarget.scrollIntoView).toHaveBeenCalledWith({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
});
|
||||
expect(element.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore matching hash targets outside the layout', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const hostTarget = document.createElement('div');
|
||||
hostTarget.id = 'section';
|
||||
hostTarget.scrollIntoView = vi.fn();
|
||||
document.body.append(hostTarget);
|
||||
const element = createScrollElement();
|
||||
const layoutTarget = document.createElement('div');
|
||||
layoutTarget.id = 'section';
|
||||
layoutTarget.scrollIntoView = vi.fn();
|
||||
element.append(layoutTarget);
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook } = routerMock.getHooks();
|
||||
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook, '#section');
|
||||
|
||||
expect(layoutTarget.scrollIntoView).toHaveBeenCalledWith({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
});
|
||||
expect(hostTarget.scrollIntoView).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should restore a saved position on history navigation', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
element.scrollTop = 240;
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook, beforeGuard } = routerMock.getHooks();
|
||||
|
||||
await runBeforeGuard(beforeGuard);
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
element.scrollTop = 80;
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
await runBeforeGuard(beforeGuard);
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
expect(element.scrollTo).toHaveBeenLastCalledWith({ top: 240 });
|
||||
});
|
||||
|
||||
it('should remove router hooks when the scope is disposed', () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
createScrollElement();
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
|
||||
expect(routerMock.removeBeforeGuard).toHaveBeenCalledOnce();
|
||||
expect(routerMock.removeAfterHook).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -1,157 +0,0 @@
|
||||
import type { AxiosRequestConfig } from 'axios';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { FileDownloader } from './downloader';
|
||||
|
||||
describe('fileDownloader', () => {
|
||||
let fileDownloader: FileDownloader;
|
||||
const mockAxiosInstance = {
|
||||
get: vi.fn(),
|
||||
} as any;
|
||||
|
||||
beforeEach(() => {
|
||||
fileDownloader = new FileDownloader(mockAxiosInstance);
|
||||
});
|
||||
|
||||
it('should create an instance of FileDownloader', () => {
|
||||
expect(fileDownloader).toBeInstanceOf(FileDownloader);
|
||||
});
|
||||
|
||||
it('should download a file and return a Blob', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
|
||||
const mockResponse: Blob = mockBlob;
|
||||
|
||||
mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
|
||||
|
||||
const result = await fileDownloader.download(url);
|
||||
|
||||
expect(result).toBeInstanceOf(Blob);
|
||||
expect(result).toEqual(mockBlob);
|
||||
expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
|
||||
method: 'GET',
|
||||
responseType: 'blob',
|
||||
responseReturn: 'body',
|
||||
});
|
||||
});
|
||||
|
||||
it('should merge provided config with default config', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
|
||||
const mockResponse: Blob = mockBlob;
|
||||
|
||||
mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
|
||||
|
||||
const customConfig: AxiosRequestConfig = {
|
||||
headers: { 'Custom-Header': 'value' },
|
||||
};
|
||||
|
||||
const result = await fileDownloader.download(url, customConfig);
|
||||
expect(result).toBeInstanceOf(Blob);
|
||||
expect(result).toEqual(mockBlob);
|
||||
expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
|
||||
...customConfig,
|
||||
method: 'GET',
|
||||
responseType: 'blob',
|
||||
responseReturn: 'body',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle errors gracefully', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
mockAxiosInstance.get.mockRejectedValueOnce(new Error('Network Error'));
|
||||
await expect(fileDownloader.download(url)).rejects.toThrow('Network Error');
|
||||
});
|
||||
|
||||
it('should handle empty URL gracefully', async () => {
|
||||
const url = '';
|
||||
mockAxiosInstance.get.mockRejectedValueOnce(
|
||||
new Error('Request failed with status code 404'),
|
||||
);
|
||||
|
||||
await expect(fileDownloader.download(url)).rejects.toThrow(
|
||||
'Request failed with status code 404',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle null URL gracefully', async () => {
|
||||
const url = null as unknown as string;
|
||||
mockAxiosInstance.get.mockRejectedValueOnce(
|
||||
new Error('Request failed with status code 404'),
|
||||
);
|
||||
|
||||
await expect(fileDownloader.download(url)).rejects.toThrow(
|
||||
'Request failed with status code 404',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fileDownloader use other method', () => {
|
||||
let fileDownloader: FileDownloader;
|
||||
|
||||
it('should call request using get', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
|
||||
const mockResponse: Blob = mockBlob;
|
||||
|
||||
const mockAxiosInstance = {
|
||||
request: vi.fn(),
|
||||
} as any;
|
||||
|
||||
fileDownloader = new FileDownloader(mockAxiosInstance);
|
||||
|
||||
mockAxiosInstance.request.mockResolvedValueOnce(mockResponse);
|
||||
|
||||
const result = await fileDownloader.download(url);
|
||||
|
||||
expect(result).toBeInstanceOf(Blob);
|
||||
expect(result).toEqual(mockBlob);
|
||||
expect(mockAxiosInstance.request).toHaveBeenCalledWith(url, {
|
||||
method: 'GET',
|
||||
responseType: 'blob',
|
||||
responseReturn: 'body',
|
||||
});
|
||||
});
|
||||
|
||||
it('should call post', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
|
||||
const mockAxiosInstance = {
|
||||
post: vi.fn(),
|
||||
} as any;
|
||||
|
||||
fileDownloader = new FileDownloader(mockAxiosInstance);
|
||||
|
||||
const customConfig: AxiosRequestConfig = {
|
||||
method: 'POST',
|
||||
data: { name: 'aa' },
|
||||
};
|
||||
|
||||
await fileDownloader.download(url, customConfig);
|
||||
|
||||
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
|
||||
url,
|
||||
{ name: 'aa' },
|
||||
{
|
||||
method: 'POST',
|
||||
responseType: 'blob',
|
||||
responseReturn: 'body',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle errors gracefully', async () => {
|
||||
const url = 'https://example.com/file';
|
||||
const mockAxiosInstance = {
|
||||
post: vi.fn(),
|
||||
} as any;
|
||||
|
||||
fileDownloader = new FileDownloader(mockAxiosInstance);
|
||||
await expect(() =>
|
||||
fileDownloader.download(url, { method: 'postt' }),
|
||||
).rejects.toThrow(
|
||||
'RequestClient does not support method "POSTT". Please ensure the method is properly implemented in your RequestClient instance.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
import type { RequestClient } from '../request-client';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { SSE } from './sse';
|
||||
|
||||
// 模拟 TextDecoder
|
||||
const OriginalTextDecoder = globalThis.TextDecoder;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal(
|
||||
'TextDecoder',
|
||||
class {
|
||||
private decoder = new OriginalTextDecoder();
|
||||
decode(value: Uint8Array, opts?: any) {
|
||||
return this.decoder.decode(value, opts);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// 创建 fetch mock
|
||||
const createFetchMock = (chunks: string[], ok = true) => {
|
||||
const encoder = new TextEncoder();
|
||||
let index = 0;
|
||||
return vi.fn().mockResolvedValue({
|
||||
ok,
|
||||
status: ok ? 200 : 500,
|
||||
body: {
|
||||
getReader: () => ({
|
||||
read: async () => {
|
||||
if (index < chunks.length) {
|
||||
return { done: false, value: encoder.encode(chunks[index++]) };
|
||||
}
|
||||
return { done: true, value: undefined };
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
describe('sSE', () => {
|
||||
let client: RequestClient;
|
||||
let sse: SSE;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
client = {
|
||||
getBaseUrl: () => 'http://localhost',
|
||||
instance: {
|
||||
interceptors: {
|
||||
request: {
|
||||
handlers: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as RequestClient;
|
||||
sse = new SSE(client);
|
||||
});
|
||||
|
||||
it('should call requestSSE when postSSE is used', async () => {
|
||||
const spy = vi.spyOn(sse, 'requestSSE').mockResolvedValue(undefined);
|
||||
await sse.postSSE('/test', { foo: 'bar' }, { headers: { a: '1' } });
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
'/test',
|
||||
{ foo: 'bar' },
|
||||
{
|
||||
headers: { a: '1' },
|
||||
method: 'POST',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error if fetch response not ok', async () => {
|
||||
vi.stubGlobal('fetch', createFetchMock([], false));
|
||||
await expect(sse.requestSSE('/bad')).rejects.toThrow(
|
||||
'HTTP error! status: 500',
|
||||
);
|
||||
});
|
||||
|
||||
it('should trigger onMessage and onEnd callbacks', async () => {
|
||||
const messages: string[] = [];
|
||||
const onMessage = vi.fn((msg: string) => messages.push(msg));
|
||||
const onEnd = vi.fn();
|
||||
|
||||
vi.stubGlobal('fetch', createFetchMock(['hello', ' world']));
|
||||
|
||||
await sse.requestSSE('/sse', undefined, { onMessage, onEnd });
|
||||
|
||||
expect(onMessage).toHaveBeenCalledTimes(2);
|
||||
expect(messages.join('')).toBe('hello world');
|
||||
// onEnd 不再带参数
|
||||
expect(onEnd).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should apply request interceptors', async () => {
|
||||
const interceptor = vi.fn(async (config) => {
|
||||
config.headers['x-test'] = 'intercepted';
|
||||
return config;
|
||||
});
|
||||
(client.instance.interceptors.request as any).handlers.push({
|
||||
fulfilled: interceptor,
|
||||
});
|
||||
|
||||
// 创建 fetch mock,并挂到全局
|
||||
const fetchMock = createFetchMock(['data']);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await sse.requestSSE('/sse', undefined, {});
|
||||
|
||||
expect(interceptor).toHaveBeenCalled();
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/sse',
|
||||
expect.objectContaining({
|
||||
headers: expect.any(Headers),
|
||||
}),
|
||||
);
|
||||
|
||||
const calls = fetchMock.mock?.calls;
|
||||
expect(calls).toBeDefined();
|
||||
expect(calls?.length).toBeGreaterThan(0);
|
||||
|
||||
const init = calls?.[0]?.[1] as RequestInit;
|
||||
expect(init).toBeDefined();
|
||||
|
||||
const headers = init?.headers as Headers;
|
||||
expect(headers?.get('x-test')).toBe('intercepted');
|
||||
expect(headers?.get('accept')).toBe('text/event-stream');
|
||||
});
|
||||
|
||||
it('should throw error when no reader', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
body: null,
|
||||
}),
|
||||
);
|
||||
await expect(sse.requestSSE('/sse')).rejects.toThrow('No reader');
|
||||
});
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { FileUploader } from './uploader';
|
||||
|
||||
describe('fileUploader', () => {
|
||||
let fileUploader: FileUploader;
|
||||
// Mock the AxiosInstance
|
||||
const mockAxiosInstance = {
|
||||
post: vi.fn(),
|
||||
} as any;
|
||||
|
||||
beforeEach(() => {
|
||||
fileUploader = new FileUploader(mockAxiosInstance);
|
||||
});
|
||||
|
||||
it('should create an instance of FileUploader', () => {
|
||||
expect(fileUploader).toBeInstanceOf(FileUploader);
|
||||
});
|
||||
|
||||
it('should upload a file and return the response', async () => {
|
||||
const url = 'https://example.com/upload';
|
||||
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
|
||||
const mockResponse: AxiosResponse = {
|
||||
config: {} as any,
|
||||
data: { success: true },
|
||||
headers: {},
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
};
|
||||
|
||||
(
|
||||
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
|
||||
).mockResolvedValueOnce(mockResponse);
|
||||
|
||||
const result = await fileUploader.upload(url, { file });
|
||||
expect(result).toEqual(mockResponse);
|
||||
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
|
||||
url,
|
||||
expect.any(FormData),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should merge provided config with default config', async () => {
|
||||
const url = 'https://example.com/upload';
|
||||
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
|
||||
const mockResponse: AxiosResponse = {
|
||||
config: {} as any,
|
||||
data: { success: true },
|
||||
headers: {},
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
};
|
||||
|
||||
(
|
||||
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
|
||||
).mockResolvedValueOnce(mockResponse);
|
||||
|
||||
const customConfig: AxiosRequestConfig = {
|
||||
headers: { 'Custom-Header': 'value' },
|
||||
};
|
||||
|
||||
const result = await fileUploader.upload(url, { file }, customConfig);
|
||||
expect(result).toEqual(mockResponse);
|
||||
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
|
||||
url,
|
||||
expect.any(FormData),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'Custom-Header': 'value',
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle errors gracefully', async () => {
|
||||
const url = 'https://example.com/upload';
|
||||
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
|
||||
(
|
||||
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
|
||||
).mockRejectedValueOnce(new Error('Network Error'));
|
||||
|
||||
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
|
||||
'Network Error',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle empty URL gracefully', async () => {
|
||||
const url = '';
|
||||
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
|
||||
(
|
||||
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
|
||||
).mockRejectedValueOnce(new Error('Request failed with status code 404'));
|
||||
|
||||
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
|
||||
'Request failed with status code 404',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle null URL gracefully', async () => {
|
||||
const url = null as unknown as string;
|
||||
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
|
||||
(
|
||||
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
|
||||
).mockRejectedValueOnce(new Error('Request failed with status code 404'));
|
||||
|
||||
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
|
||||
'Request failed with status code 404',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,93 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import MockAdapter from 'axios-mock-adapter';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { RequestClient } from './request-client';
|
||||
|
||||
describe('requestClient', () => {
|
||||
let mock: MockAdapter;
|
||||
let requestClient: RequestClient;
|
||||
|
||||
beforeEach(() => {
|
||||
mock = new MockAdapter(axios);
|
||||
requestClient = new RequestClient();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mock.reset();
|
||||
});
|
||||
|
||||
it('should successfully make a GET request', async () => {
|
||||
mock.onGet('test/url').reply(200, { data: 'response' });
|
||||
|
||||
const response = await requestClient.get('test/url');
|
||||
|
||||
expect(response.data).toEqual({ data: 'response' });
|
||||
});
|
||||
|
||||
it('should successfully make a POST request', async () => {
|
||||
const postData = { key: 'value' };
|
||||
const mockData = { data: 'response' };
|
||||
mock.onPost('/test/post', postData).reply(200, mockData);
|
||||
const response = await requestClient.post('/test/post', postData);
|
||||
expect(response.data).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('should successfully make a PUT request', async () => {
|
||||
const putData = { key: 'updatedValue' };
|
||||
const mockData = { data: 'updated response' };
|
||||
mock.onPut('/test/put', putData).reply(200, mockData);
|
||||
const response = await requestClient.put('/test/put', putData);
|
||||
expect(response.data).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('should successfully make a DELETE request', async () => {
|
||||
const mockData = { data: 'delete response' };
|
||||
mock.onDelete('/test/delete').reply(200, mockData);
|
||||
const response = await requestClient.delete('/test/delete');
|
||||
expect(response.data).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('should handle network errors', async () => {
|
||||
mock.onGet('/test/error').networkError();
|
||||
await expect(requestClient.get('/test/error')).rejects.toMatchObject({
|
||||
isAxiosError: true,
|
||||
message: 'Network Error',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle timeout', async () => {
|
||||
mock.onGet('/test/timeout').timeout();
|
||||
await expect(requestClient.get('/test/timeout')).rejects.toMatchObject({
|
||||
isAxiosError: true,
|
||||
code: 'ECONNABORTED',
|
||||
});
|
||||
});
|
||||
|
||||
it('should successfully upload a file', async () => {
|
||||
const fileData = new Blob(['file contents'], { type: 'text/plain' });
|
||||
|
||||
mock.onPost('/test/upload').reply((config) => {
|
||||
return config.data instanceof FormData && config.data.has('file')
|
||||
? [200, { data: 'file uploaded' }]
|
||||
: [400, { error: 'Bad Request' }];
|
||||
});
|
||||
|
||||
const response = await requestClient.upload('/test/upload', {
|
||||
file: fileData,
|
||||
});
|
||||
expect(response.data).toEqual({ data: 'file uploaded' });
|
||||
});
|
||||
|
||||
it('should successfully download a file as a blob', async () => {
|
||||
const mockFileContent = new Blob(['mock file content'], {
|
||||
type: 'text/plain',
|
||||
});
|
||||
|
||||
mock.onGet('/test/download').reply(200, mockFileContent);
|
||||
|
||||
const res = await requestClient.download<any>('/test/download');
|
||||
|
||||
expect(res.data).toBeInstanceOf(Blob);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import { createPinia, setActivePinia } from 'pinia';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { useAccessStore } from './access';
|
||||
|
||||
describe('useAccessStore', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it('updates accessMenus state', () => {
|
||||
const store = useAccessStore();
|
||||
expect(store.accessMenus).toEqual([]);
|
||||
store.setAccessMenus([{ name: 'Dashboard', path: '/dashboard' }]);
|
||||
expect(store.accessMenus).toEqual([
|
||||
{ name: 'Dashboard', path: '/dashboard' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('updates accessToken state correctly', () => {
|
||||
const store = useAccessStore();
|
||||
expect(store.accessToken).toBeNull(); // 初始状态
|
||||
store.setAccessToken('abc123');
|
||||
expect(store.accessToken).toBe('abc123');
|
||||
});
|
||||
|
||||
it('returns the correct accessToken', () => {
|
||||
const store = useAccessStore();
|
||||
store.setAccessToken('xyz789');
|
||||
expect(store.accessToken).toBe('xyz789');
|
||||
});
|
||||
|
||||
// 测试设置空的访问菜单列表
|
||||
it('handles empty accessMenus correctly', () => {
|
||||
const store = useAccessStore();
|
||||
store.setAccessMenus([]);
|
||||
expect(store.accessMenus).toEqual([]);
|
||||
});
|
||||
|
||||
// 测试设置空的访问路由列表
|
||||
it('handles empty accessRoutes correctly', () => {
|
||||
const store = useAccessStore();
|
||||
store.setAccessRoutes([]);
|
||||
expect(store.accessRoutes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,300 +0,0 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
|
||||
import { createPinia, setActivePinia } from 'pinia';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useTabbarStore } from './tabbar';
|
||||
|
||||
describe('useAccessStore', () => {
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [],
|
||||
});
|
||||
router.push = vi.fn();
|
||||
router.replace = vi.fn();
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('adds a new tab', () => {
|
||||
const store = useTabbarStore();
|
||||
const tab: any = {
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
key: '/home',
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
};
|
||||
const addNewTab = store.addTab(tab);
|
||||
expect(store.tabs.length).toBe(1);
|
||||
expect(store.tabs[0]).toEqual(addNewTab);
|
||||
});
|
||||
|
||||
it('adds a new tab if it does not exist', () => {
|
||||
const store = useTabbarStore();
|
||||
const newTab: any = {
|
||||
fullPath: '/new',
|
||||
meta: {},
|
||||
name: 'New',
|
||||
path: '/new',
|
||||
};
|
||||
const addNewTab = store.addTab(newTab);
|
||||
expect(store.tabs).toContainEqual(addNewTab);
|
||||
});
|
||||
|
||||
it('updates an existing tab instead of adding a new one', () => {
|
||||
const store = useTabbarStore();
|
||||
const initialTab: any = {
|
||||
fullPath: '/existing',
|
||||
meta: {
|
||||
fullPathKey: false,
|
||||
},
|
||||
name: 'Existing',
|
||||
path: '/existing',
|
||||
query: {},
|
||||
};
|
||||
store.addTab(initialTab);
|
||||
const updatedTab = { ...initialTab, query: { id: '1' } };
|
||||
store.addTab(updatedTab);
|
||||
expect(store.tabs.length).toBe(1);
|
||||
expect(store.tabs[0]?.query).toEqual({ id: '1' });
|
||||
});
|
||||
|
||||
it('closes all tabs', async () => {
|
||||
const store = useTabbarStore();
|
||||
store.addTab({
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
} as any);
|
||||
router.replace = vi.fn();
|
||||
|
||||
await store.closeAllTabs(router);
|
||||
|
||||
expect(store.tabs.length).toBe(1);
|
||||
});
|
||||
|
||||
it('closes a non-affix tab', () => {
|
||||
const store = useTabbarStore();
|
||||
const tab: any = {
|
||||
fullPath: '/closable',
|
||||
meta: {},
|
||||
name: 'Closable',
|
||||
path: '/closable',
|
||||
};
|
||||
store.tabs.push(tab);
|
||||
store._close(tab);
|
||||
expect(store.tabs.length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not close an affix tab', () => {
|
||||
const store = useTabbarStore();
|
||||
const affixTab: any = {
|
||||
fullPath: '/affix',
|
||||
meta: { affixTab: true },
|
||||
name: 'Affix',
|
||||
path: '/affix',
|
||||
};
|
||||
store.tabs.push(affixTab);
|
||||
store._close(affixTab);
|
||||
expect(store.tabs.length).toBe(1); // Affix tab should not be closed
|
||||
});
|
||||
|
||||
it('returns all cache tabs', () => {
|
||||
const store = useTabbarStore();
|
||||
store.cachedTabs.add('Home');
|
||||
store.cachedTabs.add('About');
|
||||
expect(store.getCachedTabs).toEqual(['Home', 'About']);
|
||||
});
|
||||
|
||||
it('returns all tabs, including affix tabs', () => {
|
||||
const store = useTabbarStore();
|
||||
const normalTab: any = {
|
||||
fullPath: '/normal',
|
||||
meta: {},
|
||||
name: 'Normal',
|
||||
path: '/normal',
|
||||
};
|
||||
const affixTab: any = {
|
||||
fullPath: '/affix',
|
||||
meta: { affixTab: true },
|
||||
name: 'Affix',
|
||||
path: '/affix',
|
||||
};
|
||||
store.tabs.push(normalTab);
|
||||
store.affixTabs.push(affixTab);
|
||||
expect(store.getTabs).toContainEqual(normalTab);
|
||||
expect(store.affixTabs).toContainEqual(affixTab);
|
||||
});
|
||||
|
||||
it('navigates to a specific tab', async () => {
|
||||
const store = useTabbarStore();
|
||||
const tab: any = { meta: {}, name: 'Dashboard', path: '/dashboard' };
|
||||
|
||||
await store._goToTab(tab, router);
|
||||
|
||||
expect(router.replace).toHaveBeenCalledWith({
|
||||
params: {},
|
||||
path: '/dashboard',
|
||||
query: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('closes multiple tabs by paths', async () => {
|
||||
const store = useTabbarStore();
|
||||
store.addTab({
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: '/about',
|
||||
meta: {},
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: '/contact',
|
||||
meta: {},
|
||||
name: 'Contact',
|
||||
path: '/contact',
|
||||
} as any);
|
||||
|
||||
await store._bulkCloseByKeys(['/home', '/contact']);
|
||||
|
||||
expect(store.tabs).toHaveLength(1);
|
||||
expect(store.tabs[0]?.name).toBe('About');
|
||||
});
|
||||
|
||||
it('closes all tabs to the left of the specified tab', async () => {
|
||||
const store = useTabbarStore();
|
||||
store.addTab({
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: '/about',
|
||||
meta: {},
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
} as any);
|
||||
const targetTab: any = {
|
||||
fullPath: '/contact',
|
||||
meta: {},
|
||||
name: 'Contact',
|
||||
path: '/contact',
|
||||
};
|
||||
const addTargetTab = store.addTab(targetTab);
|
||||
await store.closeLeftTabs(addTargetTab);
|
||||
|
||||
expect(store.tabs).toHaveLength(1);
|
||||
expect(store.tabs[0]?.name).toBe('Contact');
|
||||
});
|
||||
|
||||
it('closes all tabs except the specified tab', async () => {
|
||||
const store = useTabbarStore();
|
||||
store.addTab({
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
} as any);
|
||||
const targetTab: any = {
|
||||
fullPath: '/about',
|
||||
meta: {},
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
};
|
||||
const addTargetTab = store.addTab(targetTab);
|
||||
store.addTab({
|
||||
fullPath: '/contact',
|
||||
meta: {},
|
||||
name: 'Contact',
|
||||
path: '/contact',
|
||||
} as any);
|
||||
|
||||
await store.closeOtherTabs(addTargetTab);
|
||||
|
||||
expect(store.tabs).toHaveLength(1);
|
||||
expect(store.tabs[0]?.name).toBe('About');
|
||||
});
|
||||
|
||||
it('closes all tabs to the right of the specified tab', async () => {
|
||||
const store = useTabbarStore();
|
||||
const targetTab: any = {
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
};
|
||||
const addTargetTab = store.addTab(targetTab);
|
||||
store.addTab({
|
||||
fullPath: '/about',
|
||||
meta: {},
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: '/contact',
|
||||
meta: {},
|
||||
name: 'Contact',
|
||||
path: '/contact',
|
||||
} as any);
|
||||
|
||||
await store.closeRightTabs(addTargetTab);
|
||||
|
||||
expect(store.tabs).toHaveLength(1);
|
||||
expect(store.tabs[0]?.name).toBe('Home');
|
||||
});
|
||||
|
||||
it('closes the tab with the specified key', async () => {
|
||||
const store = useTabbarStore();
|
||||
const keyToClose = '/about';
|
||||
store.addTab({
|
||||
fullPath: '/home',
|
||||
meta: {},
|
||||
name: 'Home',
|
||||
path: '/home',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: keyToClose,
|
||||
meta: {},
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
} as any);
|
||||
store.addTab({
|
||||
fullPath: '/contact',
|
||||
meta: {},
|
||||
name: 'Contact',
|
||||
path: '/contact',
|
||||
} as any);
|
||||
|
||||
await store.closeTabByKey(keyToClose, router);
|
||||
|
||||
expect(store.tabs).toHaveLength(2);
|
||||
expect(
|
||||
store.tabs.find((tab) => tab.fullPath === keyToClose),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('refreshes the current tab', async () => {
|
||||
const store = useTabbarStore();
|
||||
const currentTab: any = {
|
||||
fullPath: '/dashboard',
|
||||
meta: { name: 'Dashboard' },
|
||||
name: 'Dashboard',
|
||||
path: '/dashboard',
|
||||
};
|
||||
router.currentRoute.value = currentTab;
|
||||
|
||||
await store.refresh(router);
|
||||
|
||||
expect(store.excludeCachedTabs.has('Dashboard')).toBe(false);
|
||||
expect(store.renderRouteView).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { createPinia, setActivePinia } from 'pinia';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { useUserStore } from './user';
|
||||
|
||||
describe('useUserStore', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it('returns correct userInfo', () => {
|
||||
const store = useUserStore();
|
||||
const userInfo: any = { name: 'Jane Doe', roles: [{ value: 'user' }] };
|
||||
store.setUserInfo(userInfo);
|
||||
expect(store.userInfo).toEqual(userInfo);
|
||||
});
|
||||
|
||||
// 测试重置用户信息时的行为
|
||||
it('clears userInfo and userRoles when setting null userInfo', () => {
|
||||
const store = useUserStore();
|
||||
store.setUserInfo({
|
||||
roles: [{ roleName: 'User', value: 'user' }],
|
||||
} as any);
|
||||
expect(store.userInfo).not.toBeNull();
|
||||
expect(store.userRoles.length).toBeGreaterThan(0);
|
||||
|
||||
store.setUserInfo(null as any);
|
||||
expect(store.userInfo).toBeNull();
|
||||
expect(store.userRoles).toEqual([]);
|
||||
});
|
||||
|
||||
// 测试在没有用户角色时返回空数组
|
||||
it('returns an empty array for userRoles if not set', () => {
|
||||
const store = useUserStore();
|
||||
expect(store.userRoles).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { findMenuByPath, findRootMenuByPath } from '../find-menu-by-path';
|
||||
|
||||
// 示例菜单数据
|
||||
const menus: any[] = [
|
||||
{ path: '/', children: [] },
|
||||
{ path: '/about', children: [] },
|
||||
{
|
||||
path: '/contact',
|
||||
children: [
|
||||
{ path: '/contact/email', children: [] },
|
||||
{ path: '/contact/phone', children: [] },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/services',
|
||||
children: [
|
||||
{ path: '/services/design', children: [] },
|
||||
{
|
||||
path: '/services/development',
|
||||
children: [{ path: '/services/development/web', children: [] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe('menu Finder Tests', () => {
|
||||
it('finds a top-level menu', () => {
|
||||
const menu = findMenuByPath(menus, '/about');
|
||||
expect(menu).toBeDefined();
|
||||
expect(menu?.path).toBe('/about');
|
||||
});
|
||||
|
||||
it('finds a nested menu', () => {
|
||||
const menu = findMenuByPath(menus, '/services/development/web');
|
||||
expect(menu).toBeDefined();
|
||||
expect(menu?.path).toBe('/services/development/web');
|
||||
});
|
||||
|
||||
it('returns null for a non-existent path', () => {
|
||||
const menu = findMenuByPath(menus, '/non-existent');
|
||||
expect(menu).toBeNull();
|
||||
});
|
||||
|
||||
it('handles empty menus list', () => {
|
||||
const menu = findMenuByPath([], '/about');
|
||||
expect(menu).toBeNull();
|
||||
});
|
||||
|
||||
it('handles menu items without children', () => {
|
||||
const menu = findMenuByPath(
|
||||
[{ path: '/only', children: undefined }] as any[],
|
||||
'/only',
|
||||
);
|
||||
expect(menu).toBeDefined();
|
||||
expect(menu?.path).toBe('/only');
|
||||
});
|
||||
|
||||
it('finds root menu by path', () => {
|
||||
const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
|
||||
menus,
|
||||
'/services/development/web',
|
||||
);
|
||||
|
||||
expect(findMenu).toBeDefined();
|
||||
expect(rootMenu).toBeUndefined();
|
||||
expect(rootMenuPath).toBeUndefined();
|
||||
expect(findMenu?.path).toBe('/services/development/web');
|
||||
});
|
||||
|
||||
it('returns null for undefined or empty path', () => {
|
||||
const menuUndefinedPath = findMenuByPath(menus);
|
||||
const menuEmptyPath = findMenuByPath(menus, '');
|
||||
expect(menuUndefinedPath).toBeNull();
|
||||
expect(menuEmptyPath).toBeNull();
|
||||
});
|
||||
|
||||
it('checks for root menu when path does not exist', () => {
|
||||
const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
|
||||
menus,
|
||||
'/non-existent',
|
||||
);
|
||||
expect(findMenu).toBeNull();
|
||||
expect(rootMenu).toBeUndefined();
|
||||
expect(rootMenuPath).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,233 +0,0 @@
|
||||
import type { Router, RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { generateMenus } from '../generate-menus';
|
||||
|
||||
// Nested route setup to test child inclusion and hideChildrenInMenu functionality
|
||||
|
||||
describe('generateMenus', () => {
|
||||
// 模拟路由数据
|
||||
const mockRoutes = [
|
||||
{
|
||||
meta: { icon: 'home-icon', title: '首页' },
|
||||
name: 'home',
|
||||
path: '/home',
|
||||
},
|
||||
{
|
||||
meta: { hideChildrenInMenu: true, icon: 'about-icon', title: '关于' },
|
||||
name: 'about',
|
||||
path: '/about',
|
||||
children: [
|
||||
{
|
||||
path: 'team',
|
||||
name: 'team',
|
||||
meta: { icon: 'team-icon', title: '团队' },
|
||||
},
|
||||
],
|
||||
},
|
||||
] as RouteRecordRaw[];
|
||||
|
||||
// 模拟 Vue 路由器实例
|
||||
const mockRouter = {
|
||||
getRoutes: vi.fn(() => [
|
||||
{ name: 'home', path: '/home' },
|
||||
{ name: 'about', path: '/about' },
|
||||
{ name: 'team', path: '/about/team' },
|
||||
]),
|
||||
};
|
||||
|
||||
it('the correct menu list should be generated according to the route', async () => {
|
||||
const expectedMenus = [
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: 'home-icon',
|
||||
name: '首页',
|
||||
order: undefined,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/home',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: 'about-icon',
|
||||
name: '关于',
|
||||
order: undefined,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/about',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
|
||||
const menus = generateMenus(mockRoutes, mockRouter as any);
|
||||
expect(menus).toEqual(expectedMenus);
|
||||
});
|
||||
|
||||
it('includes additional meta properties in menu items', async () => {
|
||||
const mockRoutesWithMeta = [
|
||||
{
|
||||
meta: { icon: 'user-icon', order: 1, title: 'Profile' },
|
||||
name: 'profile',
|
||||
path: '/profile',
|
||||
},
|
||||
] as RouteRecordRaw[];
|
||||
|
||||
const menus = generateMenus(mockRoutesWithMeta, mockRouter as any);
|
||||
expect(menus).toEqual([
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: 'user-icon',
|
||||
name: 'Profile',
|
||||
order: 1,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/profile',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles dynamic route parameters correctly', async () => {
|
||||
const mockRoutesWithParams = [
|
||||
{
|
||||
meta: { icon: 'details-icon', title: 'User Details' },
|
||||
name: 'userDetails',
|
||||
path: '/users/:userId',
|
||||
},
|
||||
] as RouteRecordRaw[];
|
||||
|
||||
const menus = generateMenus(mockRoutesWithParams, mockRouter as any);
|
||||
expect(menus).toEqual([
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: 'details-icon',
|
||||
name: 'User Details',
|
||||
order: undefined,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/users/:userId',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('processes routes with redirects correctly', async () => {
|
||||
const mockRoutesWithRedirect = [
|
||||
{
|
||||
name: 'redirectedRoute',
|
||||
path: '/old-path',
|
||||
redirect: '/new-path',
|
||||
},
|
||||
{
|
||||
meta: { icon: 'path-icon', title: 'New Path' },
|
||||
name: 'newPath',
|
||||
path: '/new-path',
|
||||
},
|
||||
] as RouteRecordRaw[];
|
||||
|
||||
const menus = generateMenus(mockRoutesWithRedirect, mockRouter as any);
|
||||
expect(menus).toEqual([
|
||||
// Assuming your generateMenus function excludes redirect routes from the menu
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: undefined,
|
||||
name: 'redirectedRoute',
|
||||
order: undefined,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/old-path',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: 'path-icon',
|
||||
name: 'New Path',
|
||||
order: undefined,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/new-path',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
const routes: any = [
|
||||
{
|
||||
meta: { order: 2, title: 'Home' },
|
||||
name: 'home',
|
||||
path: '/',
|
||||
},
|
||||
{
|
||||
meta: { order: 1, title: 'About' },
|
||||
name: 'about',
|
||||
path: '/about',
|
||||
},
|
||||
];
|
||||
|
||||
const router: Router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
});
|
||||
|
||||
it('should generate menu list with correct order', async () => {
|
||||
const menus = generateMenus(routes, router);
|
||||
const expectedMenus = [
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: undefined,
|
||||
name: 'About',
|
||||
order: 1,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/about',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
badge: undefined,
|
||||
badgeType: undefined,
|
||||
badgeVariants: undefined,
|
||||
icon: undefined,
|
||||
name: 'Home',
|
||||
order: 2,
|
||||
parent: undefined,
|
||||
parents: undefined,
|
||||
path: '/',
|
||||
show: true,
|
||||
children: [],
|
||||
},
|
||||
];
|
||||
|
||||
expect(menus).toEqual(expectedMenus);
|
||||
});
|
||||
|
||||
it('should handle empty routes', async () => {
|
||||
const emptyRoutes: any[] = [];
|
||||
const menus = generateMenus(emptyRoutes, router);
|
||||
expect(menus).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
generateRoutesByFrontend,
|
||||
hasAuthority,
|
||||
} from '../generate-routes-frontend';
|
||||
|
||||
// Mock 路由数据
|
||||
const mockRoutes = [
|
||||
{
|
||||
meta: {
|
||||
authority: ['admin', 'user'],
|
||||
hideInMenu: false,
|
||||
},
|
||||
path: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
path: '/dashboard/overview',
|
||||
meta: { authority: ['admin'], hideInMenu: false },
|
||||
},
|
||||
{
|
||||
path: '/dashboard/stats',
|
||||
meta: { authority: ['user'], hideInMenu: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
meta: { authority: ['admin'], hideInMenu: false },
|
||||
path: '/settings',
|
||||
},
|
||||
{
|
||||
meta: { hideInMenu: false },
|
||||
path: '/profile',
|
||||
},
|
||||
] as RouteRecordRaw[];
|
||||
|
||||
describe('hasAuthority', () => {
|
||||
it('should return true if there is no authority defined', () => {
|
||||
expect(hasAuthority(mockRoutes[2], ['admin'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if the user has the required authority', () => {
|
||||
expect(hasAuthority(mockRoutes[0], ['admin'])).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if the user does not have the required authority', () => {
|
||||
expect(hasAuthority(mockRoutes[1], ['user'])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateRoutesByFrontend', () => {
|
||||
it('should handle routes without children', async () => {
|
||||
const generatedRoutes = await generateRoutesByFrontend(mockRoutes, [
|
||||
'user',
|
||||
]);
|
||||
expect(generatedRoutes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: '/profile', // This route has no children and should be included
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle empty roles array', async () => {
|
||||
const generatedRoutes = await generateRoutesByFrontend(mockRoutes, []);
|
||||
expect(generatedRoutes).toEqual(
|
||||
expect.arrayContaining([
|
||||
// Only routes without authority should be included
|
||||
expect.objectContaining({
|
||||
path: '/profile',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(generatedRoutes).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: '/dashboard',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: '/settings',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle missing meta fields', async () => {
|
||||
const routesWithMissingMeta = [
|
||||
{ path: '/path1' }, // No meta
|
||||
{ meta: {}, path: '/path2' }, // Empty meta
|
||||
{ meta: { authority: ['admin'] }, path: '/path3' }, // Only authority
|
||||
];
|
||||
const generatedRoutes = await generateRoutesByFrontend(
|
||||
routesWithMissingMeta as RouteRecordRaw[],
|
||||
['admin'],
|
||||
);
|
||||
expect(generatedRoutes).toEqual([
|
||||
{ path: '/path1' },
|
||||
{ meta: {}, path: '/path2' },
|
||||
{ meta: { authority: ['admin'] }, path: '/path3' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import type { RouteModuleType } from '../merge-route-modules';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { mergeRouteModules } from '../merge-route-modules';
|
||||
|
||||
describe('mergeRouteModules', () => {
|
||||
it('should merge route modules correctly', () => {
|
||||
const routeModules: Record<string, RouteModuleType> = {
|
||||
'./dynamic-routes/about.ts': {
|
||||
default: [
|
||||
{
|
||||
component: () => Promise.resolve({ template: '<div>About</div>' }),
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
},
|
||||
],
|
||||
},
|
||||
'./dynamic-routes/home.ts': {
|
||||
default: [
|
||||
{
|
||||
component: () => Promise.resolve({ template: '<div>Home</div>' }),
|
||||
name: 'Home',
|
||||
path: '/',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const expectedRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
component: expect.any(Function),
|
||||
name: 'About',
|
||||
path: '/about',
|
||||
},
|
||||
{
|
||||
component: expect.any(Function),
|
||||
name: 'Home',
|
||||
path: '/',
|
||||
},
|
||||
];
|
||||
|
||||
const mergedRoutes = mergeRouteModules(routeModules);
|
||||
expect(mergedRoutes).toEqual(expectedRoutes);
|
||||
});
|
||||
|
||||
it('should handle empty modules', () => {
|
||||
const routeModules: Record<string, RouteModuleType> = {};
|
||||
const expectedRoutes: RouteRecordRaw[] = [];
|
||||
|
||||
const mergedRoutes = mergeRouteModules(routeModules);
|
||||
expect(mergedRoutes).toEqual(expectedRoutes);
|
||||
});
|
||||
|
||||
it('should handle modules with no default export', () => {
|
||||
const routeModules: Record<string, RouteModuleType> = {
|
||||
'./dynamic-routes/empty.ts': {
|
||||
default: [],
|
||||
},
|
||||
};
|
||||
const expectedRoutes: RouteRecordRaw[] = [];
|
||||
|
||||
const mergedRoutes = mergeRouteModules(routeModules);
|
||||
expect(mergedRoutes).toEqual(expectedRoutes);
|
||||
});
|
||||
});
|
||||
Generated
+8
@@ -668,6 +668,9 @@ importers:
|
||||
dayjs:
|
||||
specifier: 'catalog:'
|
||||
version: 1.11.21
|
||||
hash-wasm:
|
||||
specifier: 4.12.0
|
||||
version: 4.12.0
|
||||
pinia:
|
||||
specifier: ^4.0.2
|
||||
version: 4.0.2(@vue/devtools-api@8.1.5)(typescript@6.0.3)(vue@3.5.41(typescript@6.0.3))
|
||||
@@ -1693,6 +1696,9 @@ importers:
|
||||
|
||||
packages:
|
||||
|
||||
hash-wasm@4.12.0:
|
||||
resolution: {integrity: sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==}
|
||||
|
||||
'@ant-design/colors@6.0.0':
|
||||
resolution: {integrity: sha512-qAZRvPzfdWHtfameEGP2Qvuf838NhergR35o+EuVyB5XvSA98xod5r4utvi4TJ3ywmevm290g9nsCG5MryrdWQ==}
|
||||
|
||||
@@ -10201,6 +10207,8 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
hash-wasm@4.12.0: {}
|
||||
|
||||
'@ant-design/colors@6.0.0':
|
||||
dependencies:
|
||||
'@ctrl/tinycolor': 4.2.0
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { resolve, dirname, relative, extname } from 'node:path';
|
||||
|
||||
// Inspect only the graph reached from index.html; old chunks left in dist do not count.
|
||||
export function verifyTokenBuild(directory) {
|
||||
const root = resolve(directory);
|
||||
const visited = new Set();
|
||||
function visit(path) {
|
||||
path = resolve(path);
|
||||
const rel = relative(root, path);
|
||||
if (rel.startsWith('..') || !existsSync(path) || visited.has(path)) return;
|
||||
visited.add(path);
|
||||
const text = readFileSync(path, 'utf8');
|
||||
for (const match of text.matchAll(/["'`]((?:\.{0,2}\/)?[\w./-]+\.js)["'`]/g)) {
|
||||
const ref = match[1];
|
||||
visit(ref.startsWith('/') ? resolve(root, ref.slice(1)) : resolve(dirname(path), ref));
|
||||
}
|
||||
}
|
||||
visit(resolve(root, 'index.html'));
|
||||
const stats = [...visited].filter((path) => /[\\/]call-stats-[^\\/]+\.js$/.test(path));
|
||||
if (stats.length !== 1 || !readFileSync(stats[0], 'utf8').includes('ModelUsageStats-')) {
|
||||
throw new Error('The active call statistics page does not include Token usage. Refusing this build.');
|
||||
}
|
||||
const usage = [...visited].filter((path) => /[\\/]ModelUsageStats-[^\\/]+\.js$/.test(path));
|
||||
const hasApi = [...visited].some((path) => extname(path) === '.js' && readFileSync(path, 'utf8').includes('/stats/model-usage/log'));
|
||||
if (!usage.length || !hasApi) throw new Error('The active Token component or usage API is missing.');
|
||||
return { page: relative(root, stats[0]), component: relative(root, usage[0]), assets: visited.size };
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(verifyTokenBuild(process.argv[2] || 'dist')));
|
||||
Reference in New Issue
Block a user