i更新
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ui-static",
|
||||
"runtimeExecutable": "python",
|
||||
"runtimeArgs": ["-m", "http.server", "8791", "--directory", "assets/ui"],
|
||||
"port": 8791
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -18,3 +18,6 @@ build/
|
||||
dist/
|
||||
.installer-tools/
|
||||
dsh_desk/
|
||||
|
||||
conversation_blacklist.sqlite3*
|
||||
message_origins.sqlite3*
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
# 双版本安装包 v1.4.15
|
||||
# 三版本安装包 v1.4.30
|
||||
|
||||
同一个安装包包含企业微信 5.0.10.6023 x86 和 5.0.11.6018 x86 的独立接口布局。运行时按实际进程路径、客户端文件 SHA-256 和接口结构选择对应版本;无需统一安装盘符或手工选择版本。视觉回复、原账号协议回复、联系人验证自动跳过均保留。
|
||||
同一个安装包包含企业微信 5.0.10.6023、5.0.11.6018 和 5.0.11.6026 x86 的独立接口布局。运行时按实际进程路径、客户端文件 SHA-256 和接口结构选择对应版本;无需统一安装盘符或手工选择版本。视觉回复、原账号协议回复、联系人验证自动跳过均保留。
|
||||
|
||||
| 企业微信版本 | 启用方式 | 实测状态 |
|
||||
| --- | --- | --- |
|
||||
| 5.0.10.6023 x86 | 检测当前账号与消息库后启动 | 有历史真实发送和服务器回执记录 |
|
||||
| 5.0.11.6018 x86 | 在主程序中完成首次发送验证,取得真实回执后启用当前账号 | 开发机不能升级,尚无本次新版实机回执;不能把代码测试视为实机验收 |
|
||||
| 5.0.11.6018 x86 | 在主程序中完成首次发送验证,取得真实回执后启用当前账号 | 已登记,仍需当前账号首次回执 |
|
||||
| 5.0.11.6026 x86 | 按独立文件哈希选择接口,完成首次发送验证后启用当前账号 | 已完成静态接口核对;尚无本次新版实机回执 |
|
||||
|
||||
首次发送验证位于“自动化设置 → 协议模式”,环境检测通过后显示按钮。用户输入当前账号已有的专用测试单聊,确认后只发送“协议通道测试,请忽略”。程序核对原账号、会话、内容及服务器消息编号,将确认结果写入本机发送日志,再重新检测环境。之后可直接启动协议回复,不需要单独运行验证包或回传报告来手工开通。
|
||||
|
||||
版本识别采用三层判断:先规范化 Windows 文件版本(可识别 `v5.0.11.6026 x86` 这类返回值),再按三段版本号识别客户端系列,最后用 `WXWork.exe` 的 SHA-256 选择精确接口布局。因补丁版本可能移动原生地址,系列识别不会复用旧补丁的布局。
|
||||
|
||||
因此,截图中的 `5.0.11.6026 x86` 会被自动识别并匹配独立接口布局。当前状态应显示“需要首次发送验证”;程序会先核对当前账号和消息库,只有指定测试会话取得真实服务器回执后才启用协议回复。未验证前不会自动发送。
|
||||
|
||||
启用证据绑定客户端文件、接口修订和账号。导出的 JSON 报告、界面布尔值、失败记录、未知结果以及另一账号的回执均不能启用新版本。未取得证据前,默认发送入口甚至不会申请客户端写入权限;只有明确的单次测试可以进入验证调用。每次实际发送仍执行账号、服务、会话和回执核对,结果不明不自动重发。
|
||||
|
||||
## 构建与检查
|
||||
@@ -18,3 +23,11 @@
|
||||
- 未取消历史实测门槛。直接开放未验证版本自动发送的改动曾被自动审批拒绝,原因是缺少真实收发验收,可能错误调用或错发;该改动未执行。本版采用明确的首次测试和真实回执作为启用条件。
|
||||
- 杀毒软件行为告警的微软复核仍未完成;文件扫描和功能测试不能替代行为复核。程序不会关闭防护或添加排除。
|
||||
- 成品自检、扫描和哈希记录在 release_acceptance_v1.4.15.json;该记录不声称开发机已经实测 5.0.11 的真实收发。
|
||||
|
||||
## 后续自动适配方案
|
||||
|
||||
启动及客户端重启后识别实际进程的版本、架构和文件哈希;精确匹配已登记的适配包,核对当前账号和消息库后进入首次验证。版本检测、哈希匹配和 6026 的独立布局已经具备;适配包的自动分发仍待实现。
|
||||
|
||||
可把接口布局从程序内置表拆成带数字签名的适配包,通过现有更新服务增加独立分发入口。客户端只接受签名有效、版本/架构/哈希均匹配的包,保留上一版并支持撤回;接口调用约定发生变化时仍需升级程序。这样维护端完成一次新版适配后,各电脑可以自动获取,无需逐台更换完整安装包。
|
||||
|
||||
首次遇到未适配构建时,仅生成版本、架构、指纹和失败原因报告,不加载相近版本的地址。静态特征匹配可辅助生成候选布局,但不能据此声明发送兼容。候选布局经结构验证后,继续使用现有指定测试会话和真实回执闸门。未知版本暂停协议回复并提示切换通道;自动切换视觉模式还需处理两套待回复队列的去重,不能直接重发不确定结果。
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# 审核原因、消息来源与会话黑名单
|
||||
|
||||
桌面端「自动化设置 → 医疗助理处理提醒」新增「待处理会话与原因」。按当前绑定的企微账号列出待审核、需人工处理的客户、会话 ID 和具体进入原因,点击「查看任务」可进入任务队列。列表不受队列筛选条件影响,已完成和取消的任务不再展示。
|
||||
|
||||
管理端「会话与消息」在每条消息旁显示 AI 发送、人工发送、系统发送、客户发送或来源未知。审核通过后由系统发送的 AI 草稿仍标记为 AI;人工草稿超时发送保留人工来源。发送留痕按账号、会话、消息回执匹配。旧消息没有可靠留痕时保留来源未知;不根据文字内容猜测。视觉发送的消息库回执延迟时,在后续归档同步中补齐来源。
|
||||
|
||||
桌面端「微信消息库」选择会话后,可「加入黑名单」或「移出黑名单」。黑名单按账号和会话 ID 保存,重启后保留。协议发送、视觉发送、Ctrl+Enter 发送回退及助理提醒均在发送前核对黑名单。加入前已经实际发出的消息无法撤回;用户在微信里直接人工发送不受应用黑名单控制。
|
||||
|
||||
桌面端左侧新增「黑名单管理」,微信消息库页也提供快捷入口。管理页直接读取本机全部账号的黑名单,支持按账号筛选、搜索会话名称/ID、全选筛选结果、取消选择和批量移除。新增记录保留会话名、账号名和加入时间;旧记录没有保存名称或时间时显示会话 ID 或「历史记录」。切换账号或搜索条件会清空勾选,批量移除按账号和会话精确匹配,并通过事务确保失败时整批回滚。移除后会话恢复按系统发送规则处理。
|
||||
|
||||
数据库升级兼容已有数据。管理端启动时自动补充 archive_message.message_origin,旧记录默认 unknown。客户端通过归档检查点接口确认服务端支持来源补齐后才发送补齐请求;补齐只修改来源,不覆盖聊天正文、附件和内容同步检查点。
|
||||
|
||||
新增本地持久化文件 conversation_blacklist.sqlite3、message_origins.sqlite3 位于现有应用数据目录,均不加入 Git。消息来源留痕保存内容摘要和回执,不另存聊天正文。
|
||||
|
||||
验证:新增的来源、黑名单、界面交互测试通过;既有视觉发送与助理回归 449 项通过;最终来源、协议发送与归档回归 64 项通过。管理端 Vue 组件 script/template 编译、桌面 JavaScript 语法、Python 编译检查通过。管理端归档 API 和桌面桥接回归也已验证。
|
||||
|
||||
黑名单独立管理更新已通过 62 项相关回归(test_blacklist_management、test_reply_controls、test_reply_controls_ui、test_qt_console_bridge),包括旧表兼容、账号隔离、事务回滚和真实桌面页面交互。
|
||||
|
||||
独立运行新增测试:python -m unittest test_blacklist_management test_reply_controls test_reply_controls_ui。批量隔离运行可使用 tests/run_reply_control_regressions.py,参数为测试模块名;该脚本将测试中的本地设置、队列日志和视觉运行目录重定向到临时目录。
|
||||
|
||||
服务端已于 2026-09-23 部署至 192.168.110.111,管理端生产构建、线上健康检查和生产数据库副本升级验证均已通过。详见 deploy/im-admin/RELEASE_REPLY_CONTROLS_20260923.md。桌面端安装包尚未重新生成或发布;审核原因、会话黑名单和消息来源上报需要新版桌面客户端。
|
||||
@@ -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')));
|
||||
+28
-6
@@ -220,6 +220,7 @@ class ConfigBody(BaseModel):
|
||||
|
||||
|
||||
class ReleaseBody(BaseModel):
|
||||
package_media_id: str = ""
|
||||
latest_version: str
|
||||
download_url: str = ""
|
||||
release_notes: str = ""
|
||||
@@ -443,13 +444,13 @@ def create_app(
|
||||
).strip().rstrip("/")
|
||||
return (configured or zyt_auth.api_base_url(), bool(configured))
|
||||
|
||||
def release_payload(row: Any) -> dict[str, Any]:
|
||||
def release_payload(row: Any, *, direct_download: bool = False) -> dict[str, Any]:
|
||||
keys = set(row.keys()) if hasattr(row, "keys") else set()
|
||||
|
||||
def value(name: str, default: Any = "") -> Any:
|
||||
return row[name] if name in keys else default
|
||||
|
||||
return {
|
||||
result = {
|
||||
"latest_version": str(value("latest_version")),
|
||||
"download_url": str(value("download_url")),
|
||||
"release_notes": str(value("release_notes")),
|
||||
@@ -468,6 +469,17 @@ def create_app(
|
||||
),
|
||||
}
|
||||
|
||||
identity = app.state.archive_store.release_package_identity(result['download_url'])
|
||||
result['package_media_id'] = identity[0] if identity else ''
|
||||
if direct_download and identity:
|
||||
try:
|
||||
result['download_url'] = app.state.archive_store.release_package_download_url(*identity)
|
||||
except (KeyError, ValueError, RuntimeError) as exc:
|
||||
raise HTTPException(status_code=409, detail=f"COS 安装包暂不可用:{exc}") from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail="COS 下载地址生成失败,请重试") from exc
|
||||
return result
|
||||
|
||||
# ── 桌面账号认证 ─────────────────────────────────────────────────────
|
||||
@app.get("/api/v2/desktop/auth/config")
|
||||
async def desktop_auth_config() -> dict:
|
||||
@@ -1009,7 +1021,7 @@ def create_app(
|
||||
# ── 桌面端版本升级 ───────────────────────────────────────────────────
|
||||
@app.get("/api/v2/release")
|
||||
async def get_release(_: Principal = Depends(require("config:read"))) -> dict:
|
||||
return release_payload(database.release())
|
||||
return release_payload(database.release(), direct_download=True)
|
||||
|
||||
@app.post("/api/v2/release")
|
||||
async def save_release(
|
||||
@@ -1018,10 +1030,13 @@ def create_app(
|
||||
principal: Principal = Depends(require("release:write")),
|
||||
) -> dict:
|
||||
try:
|
||||
download_url = app.state.archive_store.normalize_release_download(
|
||||
body.download_url, body.package_sha256, body.package_size, body.package_media_id
|
||||
)
|
||||
release = backend.validate_release_form(
|
||||
{
|
||||
"latest_version": body.latest_version,
|
||||
"download_url": body.download_url,
|
||||
"download_url": download_url,
|
||||
"release_notes": body.release_notes,
|
||||
"force_upgrade": "1" if body.force_upgrade else "",
|
||||
"auto_install": "1" if body.auto_install else "",
|
||||
@@ -1035,6 +1050,8 @@ def create_app(
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
database.save_release(
|
||||
release["latest_version"],
|
||||
release["download_url"],
|
||||
@@ -1050,7 +1067,7 @@ def create_app(
|
||||
rollout_percent=release["rollout_percent"],
|
||||
status=release["status"],
|
||||
)
|
||||
return {"ok": True, **release}
|
||||
return {"ok": True, **release_payload(database.release(), direct_download=True)}
|
||||
|
||||
@app.post("/api/v2/release/package/prepare")
|
||||
async def prepare_release_package(
|
||||
@@ -1195,7 +1212,11 @@ def create_app(
|
||||
eligible and app_version.is_newer_version(latest, current_version)
|
||||
)
|
||||
download_url = release["download_url"]
|
||||
if download_url.startswith("/"):
|
||||
identity = app.state.archive_store.release_package_identity(download_url)
|
||||
if identity:
|
||||
# Each check gets a fresh COS HTTPS URL, including old release rows.
|
||||
download_url = release_payload(release, direct_download=True)["download_url"] if update_available else ""
|
||||
elif download_url.startswith("/"):
|
||||
forwarded_scheme = str(
|
||||
request.headers.get("x-forwarded-proto") or request.url.scheme
|
||||
).split(",", 1)[0].strip()
|
||||
@@ -1215,6 +1236,7 @@ def create_app(
|
||||
return {
|
||||
**release,
|
||||
"download_url": download_url,
|
||||
"download_url_expires_in": 900 if identity and update_available else 0,
|
||||
"update_available": update_available,
|
||||
"eligible": eligible,
|
||||
}
|
||||
|
||||
@@ -140,6 +140,19 @@ def pbkdf2_sha256(
|
||||
return derived.to_bytes(32, "big")
|
||||
|
||||
|
||||
def _sql_like_escape(value: str) -> str:
|
||||
return (
|
||||
str(value or "")
|
||||
.replace("\\", "\\\\")
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_")
|
||||
)
|
||||
|
||||
|
||||
def _sql_like_prefix(value: str) -> str:
|
||||
return f"{_sql_like_escape(value)}%"
|
||||
|
||||
|
||||
def now_text() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
@@ -1446,6 +1459,27 @@ class Database:
|
||||
).fetchall()
|
||||
return [{key: row[key] for key in row.keys()} for row in rows]
|
||||
|
||||
def audit_entries_for_user(
|
||||
self, user_id: int, action_prefix: str, *, detail_contains: str = "", limit: int = 20
|
||||
) -> list[dict[str, Any]]:
|
||||
"""某个账号在某类动作上的审计记录,用于桌面端展示订单查询留痕。"""
|
||||
limit = max(1, min(int(limit or 20), 200))
|
||||
prefix = str(action_prefix or "").strip()
|
||||
needle = str(detail_contains or "").strip()
|
||||
with self.connect() as db:
|
||||
rows = db.execute(
|
||||
"""SELECT id, action, detail, ip_address, created_at FROM audit_log
|
||||
WHERE user_id=? AND action LIKE ? ESCAPE '\\' AND detail LIKE ? ESCAPE '\\'
|
||||
ORDER BY id DESC LIMIT ?""",
|
||||
(
|
||||
int(user_id),
|
||||
_sql_like_prefix(prefix),
|
||||
f"%{_sql_like_escape(needle)}%" if needle else "%",
|
||||
limit,
|
||||
),
|
||||
).fetchall()
|
||||
return [{key: row[key] for key in row.keys()} for row in rows]
|
||||
|
||||
def model_call_stats(
|
||||
self, days: int = 7, tenant_id: Any = "default"
|
||||
) -> dict[str, Any]:
|
||||
|
||||
+73
-11
@@ -1135,10 +1135,19 @@ def _user_turn(chat_text: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _system_prompt_for_turn(chat_text: str, turn_hint: str = "") -> str:
|
||||
"""系统提示词 + 本轮临时提示(例如客户正在收尾,只需一句话)。"""
|
||||
prompt = _system_prompt(chat_text)
|
||||
hint = str(turn_hint or "").strip()
|
||||
return f"{prompt}\n\n{hint}" if hint else prompt
|
||||
|
||||
|
||||
def call_ai_text(
|
||||
chat_text: str,
|
||||
history: list = None,
|
||||
provider: "Provider | None" = None,
|
||||
mcp_context: dict | None = None,
|
||||
turn_hint: str = "",
|
||||
) -> str:
|
||||
"""
|
||||
文本模式:将聊天记录文字发给文本 AI,返回回复。
|
||||
@@ -1158,14 +1167,17 @@ def call_ai_text(
|
||||
try:
|
||||
from mcp_bridge import run_coro
|
||||
return _finalize_reply(
|
||||
run_coro(_call_ai_text_with_mcp(chat_text, history, provider=provider)),
|
||||
run_coro(_call_ai_text_with_mcp(
|
||||
chat_text, history, provider=provider, mcp_context=mcp_context,
|
||||
turn_hint=turn_hint,
|
||||
)),
|
||||
chat_text,
|
||||
history,
|
||||
)
|
||||
except Exception as e:
|
||||
print(f" [MCP] [!] 工具增强失败,回退普通回复: {e}")
|
||||
|
||||
messages = [{"role": "system", "content": _system_prompt(chat_text)}]
|
||||
messages = [{"role": "system", "content": _system_prompt_for_turn(chat_text, turn_hint)}]
|
||||
messages += _history_messages(history)
|
||||
messages.append(_user_turn(chat_text))
|
||||
msg = _chat_completion(messages, provider=provider)
|
||||
@@ -1173,29 +1185,53 @@ def call_ai_text(
|
||||
|
||||
|
||||
async def _call_ai_text_with_mcp(
|
||||
chat_text: str, history: list = None, provider: "Provider | None" = None
|
||||
chat_text: str, history: list = None, provider: "Provider | None" = None,
|
||||
mcp_context: dict | None = None, turn_hint: str = "",
|
||||
) -> str:
|
||||
"""带 MCP 工具调用的多轮回复。"""
|
||||
"""带 MCP 工具调用的多轮回复。
|
||||
|
||||
订单 MCP 只在客户这轮确实在问订单 / 快递时挂载(见 ``order_intent``),
|
||||
并且带工具作答的回复要过 ``order_facts`` 的事实校验:单号和状态必须来自
|
||||
工具返回,否则整条换成“正在核实”的安全话术。
|
||||
"""
|
||||
from mcp_bridge import McpHub
|
||||
import order_facts
|
||||
import order_intent
|
||||
|
||||
provider = _resolve(provider)
|
||||
async with McpHub() as hub:
|
||||
customer_text = _customer_text_for_rules(chat_text)
|
||||
order_context = order_intent.filter_context(mcp_context, customer_text, history)
|
||||
if mcp_context and not order_context:
|
||||
print(" [MCP] 本轮不是订单/快递问题,不挂载订单查询服务")
|
||||
elif order_context:
|
||||
print(" [MCP] 识别为订单/快递问题,挂载当前会话的订单查询服务")
|
||||
elif order_intent.is_order_intent(customer_text, history):
|
||||
print(" [MCP] 本轮是订单/快递问题,但未提供会话上下文,订单查询服务未挂载")
|
||||
try:
|
||||
hub = McpHub(context=order_context)
|
||||
except TypeError:
|
||||
# Keep compatibility with isolated test/embedding hubs that predate the
|
||||
# optional request-context argument.
|
||||
hub = McpHub()
|
||||
async with hub:
|
||||
tools = hub.openai_tools()
|
||||
if not tools:
|
||||
print(" [MCP] 未加载到任何工具,使用普通文本回复")
|
||||
messages = [{"role": "system", "content": _system_prompt(chat_text)}]
|
||||
messages = [{"role": "system", "content": _system_prompt_for_turn(chat_text, turn_hint)}]
|
||||
messages += _history_messages(history)
|
||||
messages.append(_user_turn(chat_text))
|
||||
msg = _chat_completion(messages, provider=provider)
|
||||
return _strip_thinking(msg.get("content") or "")
|
||||
content = _strip_thinking(msg.get("content") or "")
|
||||
return _guard_order_reply(content, [], order_context, customer_text)
|
||||
|
||||
print(f" [MCP] 已加载 {hub.tool_count} 个工具"
|
||||
f"(服务器: {', '.join(hub.server_names) or '-'})")
|
||||
|
||||
messages = [{"role": "system", "content": _system_prompt(chat_text)}]
|
||||
messages = [{"role": "system", "content": _system_prompt_for_turn(chat_text, turn_hint)}]
|
||||
messages += _history_messages(history)
|
||||
messages.append(_user_turn(chat_text))
|
||||
|
||||
tool_results: list[str] = []
|
||||
max_rounds = int(getattr(ai_config, "AI_MCP_MAX_ROUNDS", 5) or 5)
|
||||
for i in range(max_rounds):
|
||||
msg = _chat_completion(messages, tools=tools, provider=provider)
|
||||
@@ -1203,7 +1239,9 @@ async def _call_ai_text_with_mcp(
|
||||
content = msg.get("content")
|
||||
|
||||
if not tool_calls:
|
||||
return _strip_thinking(content or "")
|
||||
return _guard_order_reply(
|
||||
_strip_thinking(content or ""), tool_results, order_context, customer_text
|
||||
)
|
||||
|
||||
# 保留 assistant 消息(含 tool_calls)
|
||||
messages.append({
|
||||
@@ -1222,6 +1260,7 @@ async def _call_ai_text_with_mcp(
|
||||
args = {}
|
||||
print(f" [MCP] 调用工具 {name} args={json.dumps(args, ensure_ascii=False)[:120]}")
|
||||
result = await hub.call_tool(name, args)
|
||||
tool_results.append(result or "")
|
||||
preview = (result or "").replace("\n", " ")[:120]
|
||||
print(f" [MCP] 工具结果: {preview}{'…' if len(result or '') > 120 else ''}")
|
||||
messages.append({
|
||||
@@ -1233,7 +1272,25 @@ async def _call_ai_text_with_mcp(
|
||||
# 超过轮数:强制再要一次纯文本回复
|
||||
print(" [MCP] 已达最大工具轮数,请求最终回复")
|
||||
msg = _chat_completion(messages, provider=provider)
|
||||
return _strip_thinking(msg.get("content") or "")
|
||||
return _guard_order_reply(
|
||||
_strip_thinking(msg.get("content") or ""), tool_results, order_context, customer_text
|
||||
)
|
||||
|
||||
|
||||
def _guard_order_reply(
|
||||
content: str, tool_results: list, order_context: dict | None, customer_text: str
|
||||
) -> str:
|
||||
"""订单回合的出口事实校验;非订单回合原样放行。"""
|
||||
if not order_context:
|
||||
return content
|
||||
import order_facts
|
||||
|
||||
guarded, reasons = order_facts.enforce_order_facts(
|
||||
content, tool_results, customer_text=customer_text
|
||||
)
|
||||
if reasons:
|
||||
print(f" [MCP] 订单事实校验未通过,改用核实话术:{';'.join(reasons)}")
|
||||
return guarded
|
||||
|
||||
|
||||
_UI_GUARD_STATES = {
|
||||
@@ -2113,6 +2170,8 @@ def get_ai_reply(
|
||||
force_vision: bool = False,
|
||||
media_types=None,
|
||||
provider: "Provider | None" = None,
|
||||
mcp_context: dict | None = None,
|
||||
turn_hint: str = "",
|
||||
) -> str:
|
||||
"""Unified text/vision entry; media fallback may explicitly force vision."""
|
||||
provider = _resolve(provider)
|
||||
@@ -2138,7 +2197,10 @@ def get_ai_reply(
|
||||
print(" [AI] 文本模式 + MCP 工具增强...")
|
||||
else:
|
||||
print(" [AI] 使用文本模式分析聊天记录...")
|
||||
return call_ai_text(chat_text, history=history, provider=provider)
|
||||
return call_ai_text(
|
||||
chat_text, history=history, provider=provider, mcp_context=mcp_context,
|
||||
turn_hint=turn_hint,
|
||||
)
|
||||
else:
|
||||
return ""
|
||||
except requests.exceptions.Timeout as exc:
|
||||
|
||||
@@ -109,8 +109,17 @@ AI_MCP_PROMPT = """
|
||||
- 当客户问题需要准确事实、实时数据时,先调用合适的工具,再根据工具结果用客服口吻回复。
|
||||
- 工具结果仅供你内部参考:回复里不要出现「工具」「查询系统」「根据接口」等字眼。
|
||||
- 若工具失败或没有合适工具,就用已有知识礼貌回答,并在缺信息时向客户追问。
|
||||
- 订单/快递问题必须先调用订单工具;只使用工具返回的真实事实,不得猜测单号、轨迹、签收或审核结果。
|
||||
- 订单工具只返回当前会话绑定患者的数据;没有绑定、查到多笔订单或没有真实物流结果时,按工具返回的提示向客户说明并让客户选择/等待核实。
|
||||
- 先调用 query_bound_patient_orders:返回 selection_required=true 时只列出各笔的下单时间和状态让客户确认,不要自行挑一笔查物流;single_order_id 有值且带 latest_tracking 时直接据此回答。
|
||||
- 工具返回 ok=false(未绑定、无单号、物流查不到、订单不存在)时,只能说"正在后台核实",不得补一个状态。
|
||||
- 只要订单工具可用,就说明当前会话已绑定患者:直接用查询结果回答,不要向客户索要订单号、姓名或手机号;order_count=0 时如实说"系统里暂时没有查到您的订单记录,我这边人工核实后回复您"。
|
||||
- 工具只能查询,审核通过、驳回、修改单号、发货、退款等操作必须转人工确认。
|
||||
"""
|
||||
|
||||
# 订单意图关键词;留空使用 order_intent.DEFAULT_ORDER_KEYWORDS。
|
||||
AI_ORDER_INTENT_KEYWORDS: list = []
|
||||
|
||||
AI_COUNTER_INSULT_PROMPT = """
|
||||
【对骂模式|已开启】
|
||||
- 如果对方辱骂你、侮辱你、阴阳怪气地挑衅你,你不用忍着,直接怼回去:
|
||||
@@ -254,6 +263,8 @@ AI_SYSTEM_PROMPT_TEMPLATE = """你就是企业微信里的人工客服「{AI_AGE
|
||||
|
||||
【本轮输出硬规则|高于一般表达习惯】
|
||||
- 默认只回复 1~2 句、20~60 个汉字;只处理对方眼下最关心的一件事。
|
||||
- 对方只回"好 / 好的 / 嗯 / 谢谢 / 晚安"这类收尾语时,最多回一句自然的话(如"不客气,有事随时找我"),
|
||||
不要再叮嘱、提问、重复前面说过的话或开新话题;对方已经在收尾,就让对话自然结束。
|
||||
- 只有对方明确担心、难受、着急或抱怨时,才先用一句自然短话接住他,再给最关键的回答;
|
||||
普通闲聊和直接提问要直接接话,不要强行安慰或转到健康话题。
|
||||
- 一条消息最多问一个问题;不要标题、列表、分点、长篇科普和客套收尾。
|
||||
|
||||
+16
-7
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"AI_ENABLED": true,
|
||||
"AI_DEVELOPMENT_MODE": true,
|
||||
"AI_DEVELOPMENT_MODE": false,
|
||||
"AI_PROVIDER_TYPE": "dify",
|
||||
"AI_API_BASE": "http://ai.zhenyangtang.com.cn/v1",
|
||||
"AI_API_KEY": "app-TMCZfuo5Jj8lxgbL6shMaDCc",
|
||||
@@ -9,14 +9,14 @@
|
||||
"AI_FORCE_REMOTE_VISION_EVERY_MESSAGE": false,
|
||||
"AI_UI_GUARD_ENABLED": true,
|
||||
"AI_CONTEXT_ENABLED": true,
|
||||
"AI_CONTEXT_MAX_ROUNDS": 7,
|
||||
"AI_CONTEXT_MAX_ROUNDS": 30,
|
||||
"AI_COUNTER_INSULT_ENABLED": false,
|
||||
"AI_AGENT_NAME": "高兴亮",
|
||||
"AI_AGENT_NAME": "助理",
|
||||
"AI_HOSPITAL_NAME": "甄养堂互联网医院",
|
||||
"AI_MAX_TOKENS": 500,
|
||||
"AI_TEMPERATURE": 0.35,
|
||||
"AI_TIMEOUT": 120,
|
||||
"AI_MCP_ENABLED": false,
|
||||
"AI_MCP_ENABLED": true,
|
||||
"AI_MCP_MAX_ROUNDS": 5,
|
||||
"AI_MCP_SERVERS": [],
|
||||
"AI_JUDGE_ENABLED": true,
|
||||
@@ -59,6 +59,15 @@
|
||||
"消协"
|
||||
],
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "rule",
|
||||
"label": "挂号",
|
||||
"keywords": [
|
||||
"帮我挂号",
|
||||
"挂号"
|
||||
],
|
||||
"enabled": true
|
||||
}
|
||||
],
|
||||
"AI_AGENTS": [
|
||||
@@ -131,7 +140,7 @@
|
||||
"name": "客户经理",
|
||||
"role": "客户经理",
|
||||
"description": "挂号预约、面诊链接、订单物流、投诉退款",
|
||||
"persona": "你负责流程类事情:挂号预约、面诊安排、订单物流、投诉退款。客户只是咨询时不要抢着挂号;只有明确要约才登记。任何单号、物流状态、预约时间都必须是真实查到的,查不到就说去核实,绝不编。",
|
||||
"persona": "你负责流程类事情:挂号预约、面诊安排、订单物流、投诉退款。客户只是咨询时不要抢着挂号;回答的时候最好加上一个表情;只有明确要约才登记。任何单号、物流状态、预约时间都必须是真实查到的,查不到就说去核实,绝不编。",
|
||||
"keywords": [
|
||||
"挂号",
|
||||
"预约",
|
||||
@@ -168,7 +177,7 @@
|
||||
"label": "纯数字按数值理解",
|
||||
"type": "guide",
|
||||
"keywords": [],
|
||||
"instruction": "客户只发数字(13、6.8、130)时,那是在回答你上一句问的东西:按上下文当成血糖值、时间点、年龄或病程,接着这个数往下说,并把缺的关键信息问清(空腹还是餐后、什么时候测的)。严禁说它是编码、乱码或无法识别。",
|
||||
"instruction": "客户只发数字(13、6.8、130)时,那是在回答你上一句问的东西:按上下文当成血糖值、时间点、年龄或病程,接着这个数往下说,并把缺的关键信息问清(空腹还是餐后、什么时候测的)。严禁说它是编码、乱码或无法识别。挂号是免费的无需要费用",
|
||||
"reply": "",
|
||||
"enabled": true
|
||||
},
|
||||
@@ -189,7 +198,7 @@
|
||||
],
|
||||
"enabled": true,
|
||||
"priority": 20,
|
||||
"updated_at": "2026-09-15T02:58:00+00:00"
|
||||
"updated_at": "2026-09-23T07:32:03+00:00"
|
||||
}
|
||||
],
|
||||
"AI_AGENT_PLAN": {
|
||||
|
||||
+11
@@ -11,6 +11,17 @@ import sys
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# The packaged desktop executable also hosts the built-in order MCP server.
|
||||
# PyInstaller does not provide a Python interpreter to launch a .py file;
|
||||
# mcp_bridge therefore starts this executable again with this flag when
|
||||
# running from a frozen build. Keep this branch before any GUI imports so
|
||||
# the child process remains a stdio-only MCP server.
|
||||
if "--zyt-order-mcp" in sys.argv:
|
||||
from zyt_order_mcp import mcp
|
||||
|
||||
mcp.run(transport="stdio")
|
||||
return
|
||||
|
||||
if "--wechat-db-key-worker" in sys.argv:
|
||||
from wxwork_local_setup import key_worker_main
|
||||
|
||||
|
||||
@@ -26,5 +26,15 @@
|
||||
"notify_send_failed": true,
|
||||
"notify_timeout": true,
|
||||
"notify_manual": true,
|
||||
"review_assistant_accounts": {
|
||||
"1688856770803435": {
|
||||
"recipient_conv_id": "S:1688856770803435_7881301579925075",
|
||||
"recipient_name": "高瑞",
|
||||
"recipient_name_known": true,
|
||||
"recipient_kind": "企业微信客户",
|
||||
"recipient_peer_id": "7881301579925075",
|
||||
"enabled": true
|
||||
}
|
||||
},
|
||||
"notify_disconnect": true
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
APP_VERSION = "1.4.29"
|
||||
APP_VERSION = "1.5.0"
|
||||
_VERSION_PATTERN = re.compile(
|
||||
r"^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
|
||||
r"(?:[-+][0-9A-Za-z.-]+)?$"
|
||||
|
||||
+610
-1
@@ -8,6 +8,8 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
@@ -19,9 +21,33 @@ from archive_store import ALL_TENANTS, ArchiveStore
|
||||
from zyt_patient_client import (
|
||||
ZytPatientClient, ZytPatientError, ZytPatientSessionExpired, ZytPatientPermissionDenied,
|
||||
)
|
||||
from zyt_order_client import (
|
||||
ZytOrderClient, ZytOrderError, ZytOrderSessionExpired,
|
||||
ZytOrderPermissionDenied, ZytOrderNotFound, ZytOrderTrackingUnavailable,
|
||||
sanitize_order, sanitize_tracking,
|
||||
)
|
||||
|
||||
|
||||
ZYT_PATIENT_LIST_PERMISSION = "tcm.diagnosis/lists"
|
||||
# 每个订单动作在 ZYT 侧真正校验的权限。桌面代理按动作要求同样的权限,避免本地
|
||||
# 放行之后再被上游拒绝,也避免只有列表权限的账号看到物流轨迹。
|
||||
ZYT_ORDER_LIST_PERMISSIONS = frozenset({"firstvisit.mypatient/orders"})
|
||||
ZYT_ORDER_DETAIL_PERMISSIONS = frozenset({
|
||||
"firstvisit.mypatient/orderdetail",
|
||||
"tcm.prescriptionorder/detail",
|
||||
})
|
||||
ZYT_ORDER_TRACKING_PERMISSIONS = frozenset({"tcm.prescriptionorder/logisticstrace"})
|
||||
ZYT_ORDER_PERMISSIONS = (
|
||||
ZYT_ORDER_LIST_PERMISSIONS | ZYT_ORDER_DETAIL_PERMISSIONS | ZYT_ORDER_TRACKING_PERMISSIONS
|
||||
)
|
||||
ORDER_AUDIT_ACTION_PREFIX = "archive.order."
|
||||
ORDER_AUDIT_LABELS = {
|
||||
"archive.order.list": "查询订单列表",
|
||||
"archive.order.detail": "查询订单详情",
|
||||
"archive.order.tracking": "查询物流轨迹",
|
||||
"archive.order.audit_status": "查询审核状态",
|
||||
"archive.order.summary": "刷新订单概览",
|
||||
}
|
||||
|
||||
|
||||
class StorageBody(BaseModel):
|
||||
@@ -117,6 +143,27 @@ def _http_error(exc: Exception) -> HTTPException:
|
||||
})
|
||||
if isinstance(exc, ZytPatientPermissionDenied):
|
||||
return HTTPException(status_code=403, detail=str(exc))
|
||||
if isinstance(exc, ZytOrderSessionExpired):
|
||||
return HTTPException(status_code=409, detail={
|
||||
"code": "zyt_session_expired",
|
||||
"message": "ZYT 订单查询登录已过期,请重新验证账号。",
|
||||
})
|
||||
if isinstance(exc, ZytOrderPermissionDenied):
|
||||
return HTTPException(status_code=403, detail=str(exc))
|
||||
if isinstance(exc, ZytOrderNotFound):
|
||||
return HTTPException(status_code=404, detail={
|
||||
"code": "order_not_found",
|
||||
"message": str(exc) or "订单不存在或不属于当前绑定患者",
|
||||
})
|
||||
if isinstance(exc, ZytOrderTrackingUnavailable):
|
||||
# 没有单号或物流服务失败都不是权限问题;用明确的 code 让 MCP 和界面
|
||||
# 告诉客服“正在核实”,而不是把它当成通用 502。
|
||||
return HTTPException(
|
||||
status_code=409 if exc.code == "tracking_number_missing" else 502,
|
||||
detail={"code": exc.code, "message": str(exc)},
|
||||
)
|
||||
if isinstance(exc, ZytOrderError):
|
||||
return HTTPException(status_code=502, detail=str(exc))
|
||||
if isinstance(exc, ZytPatientError):
|
||||
return HTTPException(status_code=502, detail=str(exc))
|
||||
if isinstance(exc, RuntimeError):
|
||||
@@ -274,6 +321,276 @@ def register_archive_routes(
|
||||
client = ZytPatientClient(zyt_api_url(), token)
|
||||
return await asyncio.to_thread(client.get_patient, int(patient_id))
|
||||
|
||||
async def _diagnosis_visible_to_patient(
|
||||
tenant: str, patient_id: int, diagnosis_id: int
|
||||
) -> dict[str, Any] | None:
|
||||
"""Verify the selected diagnosis belongs to the selected patient.
|
||||
|
||||
``archive_patient_shadow`` stores only the latest diagnosis, while a
|
||||
patient can have several historical diagnoses. Read raw rows with an
|
||||
exact patient filter through the authenticated ZYT list endpoint; the
|
||||
normal keyword search only matches name/phone and deduplicates patients.
|
||||
"""
|
||||
try:
|
||||
patient_id = int(patient_id)
|
||||
diagnosis_id = int(diagnosis_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if patient_id <= 0 or diagnosis_id <= 0:
|
||||
return None
|
||||
token = await asyncio.to_thread(store.zyt_token, tenant)
|
||||
if zyt_patient_searcher is not None:
|
||||
result = await asyncio.to_thread(
|
||||
zyt_patient_searcher, token, str(diagnosis_id), 1, 50
|
||||
)
|
||||
else:
|
||||
if zyt_api_url is None:
|
||||
raise RuntimeError("ZYT 患者接口地址未配置")
|
||||
client = ZytPatientClient(zyt_api_url(), token)
|
||||
return await asyncio.to_thread(
|
||||
client.get_patient_diagnosis, patient_id, diagnosis_id
|
||||
)
|
||||
if not isinstance(result, dict):
|
||||
raise ZytPatientError("ZYT 患者查询结果格式不正确")
|
||||
for item in list(result.get("items") or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
item_patient_id = int(item.get("patient_id") or 0)
|
||||
item_diagnosis_id = int(item.get("diagnosis_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if item_patient_id == patient_id and item_diagnosis_id == diagnosis_id:
|
||||
return dict(item)
|
||||
return None
|
||||
|
||||
def _desktop_order_access(
|
||||
account: Any, required: frozenset[str] = ZYT_ORDER_LIST_PERMISSIONS
|
||||
) -> dict[str, Any]:
|
||||
"""订单查询权限只允许只读业务权限,不能由模型自行提升。
|
||||
|
||||
``required`` 是该动作在 ZYT 侧会检查的全部权限;缺任何一个都在本地拒绝。
|
||||
"""
|
||||
try:
|
||||
raw_permissions = account["zyt_permissions_json"]
|
||||
except (KeyError, IndexError):
|
||||
raw_permissions = "[]"
|
||||
try:
|
||||
parsed_permissions = json.loads(str(raw_permissions or "[]"))
|
||||
except (TypeError, ValueError):
|
||||
parsed_permissions = []
|
||||
permissions = {
|
||||
str(item).strip().lower()
|
||||
for item in parsed_permissions
|
||||
if str(item).strip()
|
||||
} if isinstance(parsed_permissions, list) else set()
|
||||
try:
|
||||
is_root = bool(int(account["zyt_root"] or 0))
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
is_root = False
|
||||
try:
|
||||
known = bool(int(account["zyt_permissions_known"] or 0))
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
known = False
|
||||
full_access = is_root or "*" in permissions
|
||||
allowed = full_access or required <= permissions
|
||||
reason = "" if allowed else (
|
||||
"当前登录的 ZYT 账号没有患者订单查看权限"
|
||||
if known else "暂未取得当前 ZYT 账号的权限信息,请退出软件后重新登录"
|
||||
)
|
||||
return {
|
||||
"can_query": allowed,
|
||||
"can_list": full_access or ZYT_ORDER_LIST_PERMISSIONS <= permissions,
|
||||
"can_detail": full_access or ZYT_ORDER_DETAIL_PERMISSIONS <= permissions,
|
||||
"can_track": full_access or ZYT_ORDER_TRACKING_PERMISSIONS <= permissions,
|
||||
"is_root": is_root,
|
||||
"known": known,
|
||||
"required_permissions": sorted(required),
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
def _require_desktop_order_access(
|
||||
account: Any, required: frozenset[str] = ZYT_ORDER_LIST_PERMISSIONS
|
||||
) -> dict[str, Any]:
|
||||
access = _desktop_order_access(account, required)
|
||||
if not access["can_query"]:
|
||||
raise HTTPException(status_code=403, detail=str(access["reason"]))
|
||||
return access
|
||||
|
||||
async def _bound_patient_for_order(
|
||||
account: Any, external_account_id: str, conversation_external_id: str, person_id: str = ""
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""Resolve the current conversation and return its active primary binding."""
|
||||
context = await asyncio.to_thread(
|
||||
store.conversation_patient_context,
|
||||
str(external_account_id or "").strip(),
|
||||
str(conversation_external_id or "").strip(),
|
||||
str(account["tenant_id"]),
|
||||
person_id=str(person_id or "").strip(),
|
||||
)
|
||||
person = context.get("person") if isinstance(context, dict) else None
|
||||
bindings = list((person or {}).get("patient_bindings") or []) if isinstance(person, dict) else []
|
||||
if not bindings and isinstance(context, dict):
|
||||
bindings = list(context.get("patient_bindings") or [])
|
||||
if not isinstance(person, dict) or not person.get("id"):
|
||||
if isinstance(context, dict) and context.get("requires_person_selection"):
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "person_selection_required",
|
||||
"message": "当前会话有多个联系人,请先在桌面端选择联系人并绑定患者",
|
||||
})
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "patient_binding_required",
|
||||
"message": str((context or {}).get("reason") or "当前会话没有可绑定的联系人"),
|
||||
})
|
||||
if not bindings:
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "patient_binding_required",
|
||||
"message": "当前会话尚未绑定患者,请先绑定患者",
|
||||
})
|
||||
binding = dict(bindings[0])
|
||||
try:
|
||||
patient_id = int(binding.get("patient_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
patient_id = 0
|
||||
if patient_id <= 0:
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "patient_binding_invalid",
|
||||
"message": "当前患者绑定已失效,请重新绑定",
|
||||
})
|
||||
# Older bindings may not have persisted diagnosis_id. Resolve it through
|
||||
# the authenticated ZYT patient list before any order query, otherwise a
|
||||
# broad order list could expose another patient's data.
|
||||
try:
|
||||
diagnosis_id = int(binding.get("diagnosis_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnosis_id = 0
|
||||
if diagnosis_id <= 0:
|
||||
visible = await _patient_visible_to_tenant(str(account["tenant_id"]), patient_id)
|
||||
try:
|
||||
diagnosis_id = int((visible or {}).get("diagnosis_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnosis_id = 0
|
||||
if diagnosis_id <= 0:
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "patient_binding_invalid",
|
||||
"message": "当前患者绑定缺少有效诊单,请重新绑定",
|
||||
})
|
||||
binding["diagnosis_id"] = diagnosis_id
|
||||
# Do not trust a diagnosis ID persisted by an older client or supplied
|
||||
# by a caller. It must still resolve to this patient in the current
|
||||
# authenticated ZYT data scope before any order request is made.
|
||||
verified = await _diagnosis_visible_to_patient(
|
||||
str(account["tenant_id"]), patient_id, diagnosis_id
|
||||
)
|
||||
if verified is None:
|
||||
raise HTTPException(status_code=409, detail={
|
||||
"code": "patient_binding_invalid",
|
||||
"message": "当前患者绑定的诊单不属于该患者,请重新绑定",
|
||||
})
|
||||
return context, binding
|
||||
|
||||
def _order_client(tenant: str) -> ZytOrderClient:
|
||||
if zyt_api_url is None:
|
||||
raise RuntimeError("ZYT 订单接口地址未配置")
|
||||
token = store.zyt_token(str(tenant))
|
||||
return ZytOrderClient(zyt_api_url(), token)
|
||||
|
||||
@staticmethod
|
||||
def _query_time() -> str:
|
||||
return datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
def _desktop_order_diagnosis_id(row: dict[str, Any]) -> int:
|
||||
try:
|
||||
return int(row.get("diagnosis_id") or row.get("diagnosisId") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
async def _order_for_binding(
|
||||
client: ZytOrderClient, binding: dict[str, Any], order_id: int
|
||||
) -> dict[str, Any]:
|
||||
order = await asyncio.to_thread(client.get_order_detail, int(order_id))
|
||||
diagnosis_id = _desktop_order_diagnosis_id(order)
|
||||
bound_diagnosis = int(binding.get("diagnosis_id") or 0)
|
||||
if diagnosis_id <= 0 or (bound_diagnosis > 0 and diagnosis_id != bound_diagnosis):
|
||||
raise ZytOrderNotFound("订单不存在或不属于当前绑定患者")
|
||||
return order
|
||||
|
||||
def _audit_order_query(
|
||||
account: Any, request: Request, action: str, binding: dict[str, Any],
|
||||
order_id: int = 0, *, conversation_external_id: str = "", outcome: str = "ok",
|
||||
) -> None:
|
||||
try:
|
||||
database.audit(
|
||||
int(account["id"]),
|
||||
action,
|
||||
f"patient={int(binding.get('patient_id') or 0)} order={int(order_id or 0)} "
|
||||
f"outcome={str(outcome or 'ok')[:40]} conv={str(conversation_external_id or '')[:200]}",
|
||||
client_ip(request),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _order_query_logs(account: Any, conversation_external_id: str, limit: int = 8) -> list[dict[str, Any]]:
|
||||
"""当前会话最近的订单查询留痕,给桌面端展示“MCP 查询日志”。"""
|
||||
conversation = str(conversation_external_id or "").strip()
|
||||
if not conversation:
|
||||
return []
|
||||
try:
|
||||
rows = database.audit_entries_for_user(
|
||||
int(account["id"]), ORDER_AUDIT_ACTION_PREFIX,
|
||||
detail_contains=f"conv={conversation}", limit=limit,
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
logs = []
|
||||
for row in rows:
|
||||
detail = str(row.get("detail") or "")
|
||||
order_match = re.search(r"\border=(\d+)", detail)
|
||||
outcome_match = re.search(r"\boutcome=(\S+)", detail)
|
||||
action = str(row.get("action") or "")
|
||||
logs.append({
|
||||
"time": str(row.get("created_at") or ""),
|
||||
"action": action,
|
||||
"label": ORDER_AUDIT_LABELS.get(action, action),
|
||||
"order_id": int(order_match.group(1)) if order_match else 0,
|
||||
"outcome": outcome_match.group(1) if outcome_match else "ok",
|
||||
})
|
||||
return logs
|
||||
|
||||
async def _tracking_for_order(
|
||||
client: ZytOrderClient, order: dict[str, Any], order_id: int, queried_at: str
|
||||
) -> tuple[dict[str, Any] | None, dict[str, str]]:
|
||||
"""Return (latest_tracking, error). Never invents a status when upstream fails."""
|
||||
phone = str(order.get("recipient_phone") or order.get("patient_phone") or "")
|
||||
try:
|
||||
tracking = await asyncio.to_thread(
|
||||
client.get_tracking, int(order_id), phone_tail=re.sub(r"\D", "", phone)[-4:]
|
||||
)
|
||||
except ZytOrderTrackingUnavailable as exc:
|
||||
return None, {"code": exc.code, "message": str(exc)}
|
||||
except ZytOrderError as exc:
|
||||
return None, {"code": "tracking_unavailable", "message": str(exc)}
|
||||
return sanitize_tracking(tracking, queried_at=queried_at), {}
|
||||
|
||||
def _order_list_hint(items: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""把“单笔直接查、多笔让客户选”的规则做成数据,不靠模型自觉。"""
|
||||
count = len(items)
|
||||
if count == 0:
|
||||
return {
|
||||
"order_count": 0, "selection_required": False, "single_order_id": 0,
|
||||
"hint": "该患者名下没有查到订单记录:如实告诉客户系统里暂时没有查到,说明会人工核实后回复;不要向客户索要订单号。",
|
||||
}
|
||||
if count == 1:
|
||||
return {
|
||||
"order_count": 1, "selection_required": False,
|
||||
"single_order_id": int(items[0].get("order_id") or 0),
|
||||
"hint": "只有一笔订单,可以直接告知该订单的状态和物流。",
|
||||
}
|
||||
return {
|
||||
"order_count": count, "selection_required": True, "single_order_id": 0,
|
||||
"hint": "查到多笔订单,只能向客户说明各笔的下单时间和状态,让客户确认是哪一笔后再查物流。",
|
||||
}
|
||||
|
||||
@app.get("/api/v2/archive/stats")
|
||||
def archive_stats(
|
||||
account_id: int | None = None,
|
||||
@@ -350,7 +667,8 @@ def register_archive_routes(
|
||||
return {
|
||||
"checkpoint": store.source_checkpoint(
|
||||
external_account_id, source_table, str(account["tenant_id"])
|
||||
)
|
||||
),
|
||||
"capabilities": {"message_origin_updates": True}
|
||||
}
|
||||
|
||||
@app.post("/api/v2/archive/desktop/checkpoint")
|
||||
@@ -501,6 +819,288 @@ def register_archive_routes(
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patient-orders")
|
||||
async def desktop_patient_orders(
|
||||
request: Request,
|
||||
external_account_id: str,
|
||||
conversation_external_id: str,
|
||||
person_id: str = "",
|
||||
keyword: str = "",
|
||||
page_no: int = 1,
|
||||
page_size: int = 20,
|
||||
start_date: str = "",
|
||||
end_date: str = "",
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict[str, Any]:
|
||||
access = _require_desktop_order_access(account, ZYT_ORDER_LIST_PERMISSIONS)
|
||||
try:
|
||||
context, binding = await _bound_patient_for_order(
|
||||
account, external_account_id, conversation_external_id, person_id
|
||||
)
|
||||
page_no = max(1, int(page_no))
|
||||
page_size = max(1, min(int(page_size), 50))
|
||||
keyword = str(keyword or "").strip()[:80]
|
||||
client = _order_client(str(account["tenant_id"]))
|
||||
result = await asyncio.to_thread(
|
||||
client.list_orders,
|
||||
diagnosis_id=int(binding.get("diagnosis_id") or 0),
|
||||
keyword=keyword, page_no=page_no, page_size=page_size,
|
||||
start_date=str(start_date or "").strip(), end_date=str(end_date or "").strip(),
|
||||
)
|
||||
bound_diagnosis = int(binding.get("diagnosis_id") or 0)
|
||||
rows = [
|
||||
row for row in list(result.get("items") or [])
|
||||
if isinstance(row, dict)
|
||||
and (bound_diagnosis <= 0 or _desktop_order_diagnosis_id(row) == bound_diagnosis)
|
||||
]
|
||||
queried_at = _query_time()
|
||||
items = [sanitize_order(row, queried_at=queried_at) for row in rows]
|
||||
hint = _order_list_hint(items)
|
||||
latest_tracking = None
|
||||
tracking_error: dict[str, str] = {}
|
||||
# 只有一笔订单时直接把物流带回去,模型不需要再猜要不要查、查哪一笔。
|
||||
if hint["single_order_id"] and access["can_track"]:
|
||||
only = items[0]
|
||||
if only.get("has_tracking_number"):
|
||||
latest_tracking, tracking_error = await _tracking_for_order(
|
||||
client, rows[0], hint["single_order_id"], queried_at
|
||||
)
|
||||
else:
|
||||
tracking_error = {
|
||||
"code": "tracking_number_missing",
|
||||
"message": "该订单还没有快递单号,请告知客户正在核实发货情况",
|
||||
}
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.list", binding,
|
||||
conversation_external_id=conversation_external_id,
|
||||
outcome=f"count={len(items)}",
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"patient": {
|
||||
"patient_id": int(binding.get("patient_id") or 0),
|
||||
"diagnosis_id": bound_diagnosis,
|
||||
},
|
||||
"items": items,
|
||||
# Never expose the upstream unfiltered count.
|
||||
"total": len(items),
|
||||
"page_no": page_no,
|
||||
"page_size": page_size,
|
||||
"queried_at": queried_at,
|
||||
"binding_id": str(binding.get("id") or ""),
|
||||
"context_available": bool(context.get("available")),
|
||||
**hint,
|
||||
"latest_tracking": latest_tracking,
|
||||
"tracking_error": tracking_error,
|
||||
}
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patient-orders/summary")
|
||||
async def desktop_patient_order_summary(
|
||||
request: Request,
|
||||
external_account_id: str,
|
||||
conversation_external_id: str,
|
||||
person_id: str = "",
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict[str, Any]:
|
||||
"""桌面端会话面板用的概览:能力状态、最近订单、最新物流和查询留痕。
|
||||
|
||||
与其它订单接口不同,这里对“未绑定 / 无权限”不抛错,而是把原因返回给界面
|
||||
展示;真正的订单数据仍然只在绑定有效且有权限时才会查询。
|
||||
"""
|
||||
access = _desktop_order_access(account, ZYT_ORDER_LIST_PERMISSIONS)
|
||||
base: dict[str, Any] = {
|
||||
"ok": True,
|
||||
"capability": {
|
||||
"enabled": False,
|
||||
"bound": False,
|
||||
"reason": str(access["reason"] or ""),
|
||||
"can_track": bool(access["can_track"]),
|
||||
"can_detail": bool(access["can_detail"]),
|
||||
},
|
||||
"recent_orders": [],
|
||||
"latest_tracking": None,
|
||||
"tracking_error": {},
|
||||
"logs": _order_query_logs(account, conversation_external_id),
|
||||
"queried_at": _query_time(),
|
||||
}
|
||||
if not access["can_query"]:
|
||||
return base
|
||||
try:
|
||||
_context, binding = await _bound_patient_for_order(
|
||||
account, external_account_id, conversation_external_id, person_id
|
||||
)
|
||||
except HTTPException as exc:
|
||||
detail = exc.detail if isinstance(exc.detail, dict) else {"message": str(exc.detail)}
|
||||
base["capability"]["reason"] = str(detail.get("message") or "当前会话尚未绑定患者")
|
||||
base["capability"]["code"] = str(detail.get("code") or "")
|
||||
return base
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
base["capability"].update({"enabled": True, "bound": True, "reason": ""})
|
||||
try:
|
||||
client = _order_client(str(account["tenant_id"]))
|
||||
result = await asyncio.to_thread(
|
||||
client.list_orders,
|
||||
diagnosis_id=int(binding.get("diagnosis_id") or 0), page_no=1, page_size=5,
|
||||
)
|
||||
bound_diagnosis = int(binding.get("diagnosis_id") or 0)
|
||||
rows = [
|
||||
row for row in list(result.get("items") or [])
|
||||
if isinstance(row, dict)
|
||||
and (bound_diagnosis <= 0 or _desktop_order_diagnosis_id(row) == bound_diagnosis)
|
||||
][:3]
|
||||
queried_at = _query_time()
|
||||
items = [sanitize_order(row, queried_at=queried_at) for row in rows]
|
||||
base["recent_orders"] = items
|
||||
base["queried_at"] = queried_at
|
||||
shipped = next(
|
||||
(index for index, item in enumerate(items) if item.get("has_tracking_number")),
|
||||
None,
|
||||
)
|
||||
if shipped is not None and access["can_track"]:
|
||||
base["latest_tracking"], base["tracking_error"] = await _tracking_for_order(
|
||||
client, rows[shipped], int(items[shipped]["order_id"]), queried_at
|
||||
)
|
||||
if base["latest_tracking"] is not None:
|
||||
base["latest_tracking"]["order_id"] = int(items[shipped]["order_id"])
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.summary", binding,
|
||||
conversation_external_id=conversation_external_id,
|
||||
outcome=f"count={len(items)}",
|
||||
)
|
||||
base["logs"] = _order_query_logs(account, conversation_external_id)
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
return base
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patient-orders/{order_id}")
|
||||
async def desktop_patient_order_detail(
|
||||
order_id: int,
|
||||
request: Request,
|
||||
external_account_id: str,
|
||||
conversation_external_id: str,
|
||||
person_id: str = "",
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict[str, Any]:
|
||||
_require_desktop_order_access(account, ZYT_ORDER_DETAIL_PERMISSIONS)
|
||||
try:
|
||||
_context, binding = await _bound_patient_for_order(
|
||||
account, external_account_id, conversation_external_id, person_id
|
||||
)
|
||||
client = _order_client(str(account["tenant_id"]))
|
||||
try:
|
||||
order = await _order_for_binding(client, binding, order_id)
|
||||
except ZytOrderNotFound:
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.detail", binding, order_id,
|
||||
conversation_external_id=conversation_external_id, outcome="rejected",
|
||||
)
|
||||
raise
|
||||
queried_at = _query_time()
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.detail", binding, order_id,
|
||||
conversation_external_id=conversation_external_id,
|
||||
)
|
||||
return {"ok": True, "order": sanitize_order(order, queried_at=queried_at)}
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patient-orders/{order_id}/tracking")
|
||||
async def desktop_patient_order_tracking(
|
||||
order_id: int,
|
||||
request: Request,
|
||||
external_account_id: str,
|
||||
conversation_external_id: str,
|
||||
person_id: str = "",
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict[str, Any]:
|
||||
_require_desktop_order_access(
|
||||
account, ZYT_ORDER_DETAIL_PERMISSIONS | ZYT_ORDER_TRACKING_PERMISSIONS
|
||||
)
|
||||
try:
|
||||
_context, binding = await _bound_patient_for_order(
|
||||
account, external_account_id, conversation_external_id, person_id
|
||||
)
|
||||
client = _order_client(str(account["tenant_id"]))
|
||||
order = await _order_for_binding(client, binding, order_id)
|
||||
queried_at = _query_time()
|
||||
safe = sanitize_order(order, queried_at=queried_at)
|
||||
if not safe.get("has_tracking_number"):
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.tracking", binding, order_id,
|
||||
conversation_external_id=conversation_external_id,
|
||||
outcome="tracking_number_missing",
|
||||
)
|
||||
raise ZytOrderTrackingUnavailable(
|
||||
"该订单还没有快递单号,请告知客户正在核实发货情况",
|
||||
code="tracking_number_missing",
|
||||
)
|
||||
latest_tracking, tracking_error = await _tracking_for_order(
|
||||
client, order, order_id, queried_at
|
||||
)
|
||||
if latest_tracking is None:
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.tracking", binding, order_id,
|
||||
conversation_external_id=conversation_external_id,
|
||||
outcome=str(tracking_error.get("code") or "tracking_unavailable"),
|
||||
)
|
||||
raise ZytOrderTrackingUnavailable(
|
||||
str(tracking_error.get("message") or "物流服务暂时查不到轨迹"),
|
||||
code=str(tracking_error.get("code") or "tracking_unavailable"),
|
||||
)
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.tracking", binding, order_id,
|
||||
conversation_external_id=conversation_external_id,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"order_id": int(order_id),
|
||||
"order_no": safe.get("order_no", ""),
|
||||
"express_company": safe.get("express_company", ""),
|
||||
"tracking_number_masked": safe.get("tracking_number_masked", ""),
|
||||
"fulfillment_status": safe.get("fulfillment_status", ""),
|
||||
"latest_tracking": latest_tracking,
|
||||
"queried_at": queried_at,
|
||||
}
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patient-orders/{order_id}/audit-status")
|
||||
async def desktop_patient_order_audit_status(
|
||||
order_id: int,
|
||||
request: Request,
|
||||
external_account_id: str,
|
||||
conversation_external_id: str,
|
||||
person_id: str = "",
|
||||
account: Any = Depends(current_desktop),
|
||||
) -> dict[str, Any]:
|
||||
_require_desktop_order_access(account, ZYT_ORDER_DETAIL_PERMISSIONS)
|
||||
try:
|
||||
_context, binding = await _bound_patient_for_order(
|
||||
account, external_account_id, conversation_external_id, person_id
|
||||
)
|
||||
client = _order_client(str(account["tenant_id"]))
|
||||
order = await _order_for_binding(client, binding, order_id)
|
||||
queried_at = _query_time()
|
||||
safe = sanitize_order(order, queried_at=queried_at)
|
||||
_audit_order_query(
|
||||
account, request, "archive.order.audit_status", binding, order_id,
|
||||
conversation_external_id=conversation_external_id,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"order_id": int(order_id),
|
||||
"order_no": safe.get("order_no", ""),
|
||||
"prescription_audit": safe["prescription_audit"],
|
||||
"payment_audit": safe["payment_audit"],
|
||||
"fulfillment_status": safe["fulfillment_status"],
|
||||
"queried_at": queried_at,
|
||||
}
|
||||
except Exception as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
@app.get("/api/v2/archive/desktop/patients/search")
|
||||
async def desktop_search_zyt_patients(
|
||||
keyword: str,
|
||||
@@ -531,6 +1131,15 @@ def register_archive_routes(
|
||||
status_code=403,
|
||||
detail="当前 ZYT 账号无权访问该患者,不能建立绑定",
|
||||
)
|
||||
if body.diagnosis_id:
|
||||
verified_diagnosis = await _diagnosis_visible_to_patient(
|
||||
tenant, body.patient_id, body.diagnosis_id
|
||||
)
|
||||
if verified_diagnosis is None:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="所选诊单不属于该患者,不能建立绑定",
|
||||
)
|
||||
context = await asyncio.to_thread(store.conversation_patient_context,
|
||||
body.external_account_id,
|
||||
body.conversation_external_id,
|
||||
|
||||
@@ -31,6 +31,7 @@ from urllib.parse import urlparse, urlunparse
|
||||
import requests
|
||||
|
||||
import backend_client
|
||||
from message_origin import classify as classify_message_origin
|
||||
from archive_content_parser import (
|
||||
parse_message_content,
|
||||
decode_hex_protobuf_text,
|
||||
@@ -419,6 +420,7 @@ class ArchiveApiClient:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.archive_scope = ""
|
||||
self.supports_origin_updates = False
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
@@ -518,6 +520,7 @@ class ArchiveApiClient:
|
||||
"/api/v2/archive/desktop/checkpoint",
|
||||
params={"external_account_id": account, "source_table": SOURCE_TABLE},
|
||||
)
|
||||
self.supports_origin_updates = (result.get('capabilities') or {}).get('message_origin_updates') is True
|
||||
checkpoint = result.get("checkpoint")
|
||||
return checkpoint if isinstance(checkpoint, dict) else {}
|
||||
|
||||
@@ -1180,6 +1183,8 @@ class IncrementalArchiveImporter:
|
||||
"sent_at_epoch": row.get("send_time"),
|
||||
"message_type": message_type,
|
||||
"direction": "outbound" if sender_id and sender_id == account else "inbound",
|
||||
"message_origin": classify_message_origin(
|
||||
account, conversation_id, sender_id, row.get('server_id'), content, row.get('send_time'), root=self.config.work_root.parent),
|
||||
"status": _message_status(row),
|
||||
"content": str(content or ""),
|
||||
"content_parser": CONTENT_PARSER_VERSION,
|
||||
@@ -1321,6 +1326,51 @@ class IncrementalArchiveImporter:
|
||||
_atomic_json(path, state)
|
||||
return path, state
|
||||
|
||||
def _repair_origins(self, connection, account, columns, checkpoint):
|
||||
if getattr(self.api, 'supports_origin_updates', False) is not True:
|
||||
return 0
|
||||
if not {'sender_id', 'conversation_id', 'send_time'}.issubset(columns):
|
||||
return 0
|
||||
endpoint = str(getattr(self.api, 'base_url', '') or self.config.api_urls[0])
|
||||
identity = hashlib.sha256(json.dumps([endpoint, str(getattr(self.api, 'archive_scope', '')), self.config.corp_scope_id, account,
|
||||
str(self.config.source_root.resolve())]).encode()).hexdigest()
|
||||
path = self.config.work_root / 'origin_repair' / (identity + '.json')
|
||||
try:
|
||||
cursor = json.loads(path.read_text(encoding='utf-8'))
|
||||
except (OSError, ValueError):
|
||||
cursor = {'send_time': 0, 'rowid': 0}
|
||||
upper = float(checkpoint.get('send_time') or 0)
|
||||
if float(cursor.get('send_time') or 0) > upper:
|
||||
cursor = {'send_time': 0, 'rowid': 0}
|
||||
query = connection.execute("""SELECT rowid AS __archive_rowid,* FROM message_table
|
||||
WHERE CAST(sender_id AS TEXT)=? AND (send_time>? OR (send_time=? AND rowid>?))
|
||||
AND send_time<=? AND send_time<? ORDER BY send_time,rowid LIMIT ?""",
|
||||
(account, cursor['send_time'], cursor['send_time'], cursor['rowid'], upper,
|
||||
time.time() - 120, min(5000, max(1, self.config.batch_size))))
|
||||
names = [str(item[0]) for item in query.description]
|
||||
rows = [dict(zip(names, values)) for values in query.fetchall()]
|
||||
query.close()
|
||||
if not rows:
|
||||
return 0
|
||||
updates = []
|
||||
for row in rows:
|
||||
parsed = parse_message_content(row.get('content'), row.get('content_type'), extra_content=row.get('extra_content'))
|
||||
origin = classify_message_origin(account, row.get('conversation_id'), row.get('sender_id'),
|
||||
row.get('server_id'), parsed.get('text'), row.get('send_time'), root=self.config.work_root.parent)
|
||||
if origin not in {'ai', 'human', 'system'}:
|
||||
continue
|
||||
source_id = next((value for value in (_valid_source_id(row.get(key)) for key in ('server_id','client_id','message_id')) if value),
|
||||
f"rowid:{row['__archive_rowid']}")
|
||||
updates.append({'origin_only': True, 'message_origin': origin, 'source_table': SOURCE_TABLE,
|
||||
'source_message_id': source_id, 'server_id': str(row.get('server_id') or ''),
|
||||
'conversation': {'external_id': str(row.get('conversation_id') or '')}})
|
||||
if updates:
|
||||
self.api.import_messages({'batch_id': uuid.uuid4().hex,
|
||||
'source_account': {'external_account_id': account, 'corp_scope_id': self.config.corp_scope_id},
|
||||
'messages': updates})
|
||||
_atomic_json(path, {'send_time': float(rows[-1]['send_time']), 'rowid': int(rows[-1]['__archive_rowid'])})
|
||||
return len(updates)
|
||||
|
||||
def _repair_content(
|
||||
self, connection: Any, account: str, state_path: Path, state: dict[str, Any],
|
||||
users: dict[tuple[str, str], str], conversations: dict[tuple[str, str], str],
|
||||
@@ -1490,6 +1540,8 @@ class IncrementalArchiveImporter:
|
||||
if SOURCE_TABLE not in _tables(connection):
|
||||
continue
|
||||
columns = _table_columns(connection, SOURCE_TABLE)
|
||||
from message_origin import reconcile_visual_receipts
|
||||
reconcile_visual_receipts(connection, account, root=self.config.work_root.parent)
|
||||
if "send_time" not in columns:
|
||||
continue
|
||||
checkpoint = self.api.checkpoint(account)
|
||||
@@ -1575,6 +1627,7 @@ class IncrementalArchiveImporter:
|
||||
)
|
||||
sent_at = next_checkpoint["send_time"]
|
||||
rowid = next_checkpoint["rowid"]
|
||||
self._repair_origins(connection, account, columns, {'send_time': sent_at, 'rowid': rowid})
|
||||
summary["attachments_repaired"] += self._repair_cached_attachments(
|
||||
connection,
|
||||
account,
|
||||
|
||||
+75
-6
@@ -25,7 +25,7 @@ import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Iterator
|
||||
from urllib.parse import quote, urlparse
|
||||
from urllib.parse import quote, unquote, urlparse
|
||||
|
||||
from archive_content_parser import (
|
||||
decode_hex_protobuf_text,
|
||||
@@ -44,6 +44,7 @@ RELEASE_TENANT = "system-release"
|
||||
ALL_TENANTS = "*"
|
||||
MAX_DIRECT_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024
|
||||
MAX_RELEASE_PACKAGE_BYTES = 1024 * 1024 * 1024
|
||||
RELEASE_DOWNLOAD_PREFIX = "/api/v2/desktop/update/cos-packages/"
|
||||
MULTIPART_THRESHOLD_BYTES = 8 * 1024 * 1024
|
||||
MULTIPART_PART_BYTES = 2 * 1024 * 1024
|
||||
EXCEL_SHEET_DATA_ROWS = 900_000
|
||||
@@ -182,6 +183,7 @@ CREATE TABLE IF NOT EXISTS archive_message (
|
||||
message_type TEXT NOT NULL DEFAULT 'unknown',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
direction TEXT NOT NULL DEFAULT 'unknown',
|
||||
message_origin TEXT NOT NULL DEFAULT 'unknown',
|
||||
status TEXT NOT NULL DEFAULT 'normal',
|
||||
sent_at TEXT NOT NULL,
|
||||
sent_at_epoch INTEGER,
|
||||
@@ -730,6 +732,9 @@ class ArchiveStore:
|
||||
now = utc_now()
|
||||
with self.database.connect() as db:
|
||||
db.executescript(SCHEMA)
|
||||
message_columns = {row[1] for row in db.execute('PRAGMA table_info(archive_message)')}
|
||||
if 'message_origin' not in message_columns:
|
||||
db.execute("ALTER TABLE archive_message ADD COLUMN message_origin TEXT NOT NULL DEFAULT 'unknown'")
|
||||
storage_columns = {
|
||||
row[1] for row in db.execute("PRAGMA table_info(archive_storage_config)")
|
||||
}
|
||||
@@ -1187,17 +1192,17 @@ class ArchiveStore:
|
||||
"required_headers": headers,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _release_package_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def _release_package_payload(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
media = payload.get("media") if isinstance(payload.get("media"), dict) else {}
|
||||
media_id = str(media.get("id") or "")
|
||||
filename = Path(str(media.get("original_filename") or "update.exe")).name
|
||||
return {
|
||||
**payload,
|
||||
"file_name": filename,
|
||||
"download_url": (
|
||||
f"/api/v2/desktop/update/cos-packages/{media_id}/{quote(filename)}"
|
||||
),
|
||||
"package_media_id": media_id,
|
||||
"download_url": self.release_package_download_url(media_id, filename)
|
||||
if media.get("status") == "ready" else "",
|
||||
"download_url_expires_in": 900 if media.get("status") == "ready" else 0,
|
||||
"package_sha256": str(media.get("sha256") or ""),
|
||||
"package_size": int(media.get("size_bytes") or 0),
|
||||
}
|
||||
@@ -1249,6 +1254,50 @@ class ArchiveStore:
|
||||
raise KeyError("升级包不存在或尚未上传完成")
|
||||
return self.media_download_url(media_id, expires, RELEASE_TENANT)
|
||||
|
||||
@staticmethod
|
||||
def release_package_identity(download_url: str) -> tuple[str, str] | None:
|
||||
"""Recognize the durable reference used by old release records."""
|
||||
value = str(download_url or "").strip()
|
||||
if not value.startswith(RELEASE_DOWNLOAD_PREFIX):
|
||||
return None
|
||||
parts = value[len(RELEASE_DOWNLOAD_PREFIX):].split("/", 1)
|
||||
if len(parts) != 2 or not parts[0] or not parts[1]:
|
||||
raise ValueError("COS 安装包标识无效")
|
||||
return parts[0], unquote(parts[1])
|
||||
|
||||
def release_package_reference(self, media_id: str, digest: str, size: int) -> str:
|
||||
with self.database.connect() as db:
|
||||
row = db.execute("""SELECT * FROM archive_media_object
|
||||
WHERE id=? AND tenant_id=? AND status='ready'""", (media_id, RELEASE_TENANT)).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("COS 安装包不存在或尚未上传完成,请重新上传")
|
||||
if str(digest or '').lower() != row['sha256'] or int(size or 0) != row['size_bytes']:
|
||||
raise ValueError("安装包 SHA256 或大小与已上传 COS 文件不一致")
|
||||
return RELEASE_DOWNLOAD_PREFIX + str(row['id']) + '/' + quote(row['original_filename'])
|
||||
|
||||
def normalize_release_download(self, download_url: str, digest: str, size: int, media_id: str = "") -> str:
|
||||
"""Persist an artifact reference, never the expiring COS signature."""
|
||||
value = str(download_url or "").strip()
|
||||
identity = self.release_package_identity(value)
|
||||
if media_id or identity:
|
||||
reference = self.release_package_reference(media_id or identity[0], digest, size)
|
||||
if identity and reference != value:
|
||||
raise ValueError("COS 安装包地址与所选文件不一致")
|
||||
return reference
|
||||
# A page opened before this API upgrade does not send package_media_id.
|
||||
# Match its signed URL by verified hash AND exact COS host/object path.
|
||||
if value and digest:
|
||||
with self.database.connect() as db:
|
||||
row = db.execute("""SELECT * FROM archive_media_object
|
||||
WHERE tenant_id=? AND sha256=? AND status='ready'""", (RELEASE_TENANT, digest.lower())).fetchone()
|
||||
if row is not None:
|
||||
parsed = urlparse(value)
|
||||
if unquote(parsed.path).lstrip('/') == row['object_key']:
|
||||
current = urlparse(self.release_package_download_url(row['id'], row['original_filename']))
|
||||
if parsed.scheme == current.scheme and parsed.netloc == current.netloc:
|
||||
return self.release_package_reference(row['id'], digest, size)
|
||||
return value
|
||||
|
||||
def _prepare_multipart_media(
|
||||
self,
|
||||
config: dict[str, Any],
|
||||
@@ -2048,6 +2097,20 @@ class ArchiveStore:
|
||||
for message in rows:
|
||||
try:
|
||||
raw = dict(message)
|
||||
if raw.get('origin_only') is True:
|
||||
origin = str(raw.get('message_origin') or 'unknown')
|
||||
conv_id = str((raw.get('conversation') or {}).get('external_id') or '')
|
||||
if origin not in {'ai', 'human', 'system'} or not conv_id:
|
||||
raise ValueError('消息来源或会话身份无效')
|
||||
dedup = sha256_text(f"{tenant}\x1f{account['id']}\x1f{self._source_message_key(raw)}")
|
||||
changed = db.execute("""UPDATE archive_message SET message_origin=?,updated_at=?
|
||||
WHERE tenant_id=? AND source_account_id=? AND dedup_key=? AND direction='outbound'
|
||||
AND conversation_id IN (SELECT id FROM archive_conversation WHERE tenant_id=? AND source_account_id=? AND external_id=?)
|
||||
AND (message_origin='unknown' OR ? IN ('ai','system'))""",
|
||||
(origin, now, tenant, account['id'], dedup, tenant, account['id'], conv_id, origin)).rowcount
|
||||
duplicates += changed
|
||||
skipped += int(not changed)
|
||||
continue
|
||||
conv_values = dict(raw.get("conversation") or {})
|
||||
if not conv_values:
|
||||
conv_values = {
|
||||
@@ -2183,6 +2246,11 @@ class ArchiveStore:
|
||||
(new_id(), message_id, status, content, raw_id, now),
|
||||
)
|
||||
inserted += 1
|
||||
origin = str(raw.get('message_origin') or 'unknown')
|
||||
if origin in {'ai', 'human', 'system'} and raw.get('direction') == 'outbound':
|
||||
# Never let a legacy/unknown re-import erase a known source.
|
||||
db.execute("UPDATE archive_message SET message_origin=?,updated_at=? WHERE id=? AND (message_origin='unknown' OR ? IN ('ai','system'))",
|
||||
(origin, now, message_id, origin))
|
||||
parent = str(
|
||||
raw.get("parent_source_message_id")
|
||||
or raw.get("parent_message_id") or ""
|
||||
@@ -3150,6 +3218,7 @@ class ArchiveStore:
|
||||
has_attachment=bool(attachments_by_message[str(row["id"])]),
|
||||
),
|
||||
"direction": row["direction"],
|
||||
"message_origin": 'customer' if row['direction'] == 'inbound' else row['message_origin'],
|
||||
"status": row["status"],
|
||||
"sent_at": row["sent_at"],
|
||||
"sequence_no": row["sequence_no"],
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import Any
|
||||
|
||||
import admin_backend
|
||||
from archive_store import ArchiveStore
|
||||
from message_origin import classify as classify_message_origin
|
||||
from archive_content_parser import parse_message_content
|
||||
from wxwork_db import (
|
||||
connect_sqlite,
|
||||
@@ -186,6 +187,8 @@ class WxworkArchiveAdapter:
|
||||
"sent_at": row.get("send_time"),
|
||||
"message_type": get_msg_type_name(content_type),
|
||||
"direction": "outbound" if sender_id and sender_id == account else "inbound",
|
||||
"message_origin": classify_message_origin(
|
||||
account, conversation_id, sender_id, row.get('server_id'), str(parsed.get('text') or ''), row.get('send_time')),
|
||||
"status": status,
|
||||
"content": str(parsed.get("text") or ""),
|
||||
"content_parser": "desktop-plaintext-v1",
|
||||
|
||||
+138
-9
File diff suppressed because one or more lines are too long
@@ -72,3 +72,22 @@
|
||||
#stage .assistant-recipient-card { grid-template-columns:32px minmax(0,1fr); gap:10px; padding:12px; }
|
||||
#stage .assistant-recipient-icon { width:32px; height:32px; }
|
||||
}
|
||||
|
||||
/* Independent blacklist management shares the console panel and button styles. */
|
||||
#stage .blacklist-panel > .tiny { margin: 8px 0 18px; }
|
||||
#stage .blacklist-filters { margin: 16px 0; gap: 12px; }
|
||||
#stage .blacklist-filters .search { flex: 1 1 260px; height: 40px; }
|
||||
#stage .blacklist-filters .select { flex: 0 1 320px; height: 40px; }
|
||||
#stage .blacklist-actions { margin: 16px 0; gap: 12px; }
|
||||
#stage .blacklist-actions > span { margin-right: auto; color: var(--muted); }
|
||||
#stage .blacklist-table-wrap { overflow: auto; max-height: 620px; }
|
||||
#stage .blacklist-table { width: 100%; border-collapse: collapse; text-align: left; }
|
||||
#stage .blacklist-table :is(th, td) { padding: 14px 12px; border-bottom: 1px solid #e5eaf2; vertical-align: middle; }
|
||||
#stage .blacklist-table th { position: sticky; top: 0; background: #f5f7fc; color: #536582; white-space: nowrap; z-index: 1; }
|
||||
#stage .blacklist-table th:first-child { width: 48px; }
|
||||
#stage .blacklist-table td { overflow-wrap: anywhere; min-width: 160px; }
|
||||
#stage .blacklist-table td:first-child { min-width: 48px; }
|
||||
#stage .blacklist-table small { display: block; color: var(--muted); margin-top: 6px; }
|
||||
#stage .blacklist-table input[type="checkbox"] { width: 18px; height: 18px; accent-color: #3772ff; cursor: pointer; }
|
||||
#stage .blacklist-table tr:has(input:checked) { background: #edf3ff; }
|
||||
#stage .blacklist-error { padding: 12px; border-radius: 10px; background: #fff1df; color: #86500d; overflow-wrap: anywhere; }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user