feat: 引入antdesignxvue

This commit is contained in:
2026-09-19 00:54:06 +08:00
parent bc73668737
commit ffb9f2ca90
10 changed files with 358 additions and 103 deletions
+1
View File
@@ -42,6 +42,7 @@
"@vben/utils": "workspace:*",
"@vueuse/core": "catalog:",
"ant-design-vue": "catalog:",
"ant-design-x-vue": "^1.6.0",
"dayjs": "catalog:",
"dompurify": "^3.4.15",
"marked": "^18.0.13",
+48 -1
View File
@@ -1,6 +1,7 @@
import type {
ComponentRecordType,
GenerateMenuAndRoutesOptions,
RouteRecordStringComponent,
} from '@vben/types';
import { generateAccessible } from '@vben/access';
@@ -14,6 +15,52 @@ import { $t } from '#/locales';
const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');
/** 将 glob key 规范成与后端 component 一致的 /xxx/index.vue */
function normalizePageKey(path: string): string {
const normalized = path.replace(/^(\.\/|\.\.\/)+/, '');
const withSlash = normalized.startsWith('/') ? normalized : `/${normalized}`;
const viewPath = withSlash.replace(/^\/views/, '');
return viewPath.endsWith('.vue') ? viewPath : `${viewPath}.vue`;
}
/**
* 过滤掉本地不存在的页面组件(已下线菜单仍下发时避免 console.error)。
* layout / iframe 名称保留。
*/
function filterMissingPageRoutes(
routes: RouteRecordStringComponent[],
pageMap: ComponentRecordType,
layoutMap: ComponentRecordType,
): RouteRecordStringComponent[] {
const knownPages = new Set(
Object.keys(pageMap).map((k) => normalizePageKey(k)),
);
const walk = (
nodes: RouteRecordStringComponent[],
): RouteRecordStringComponent[] => {
const result: RouteRecordStringComponent[] = [];
for (const node of nodes) {
const children = node.children?.length
? walk(node.children as RouteRecordStringComponent[])
: undefined;
const component = node.component;
if (!component || layoutMap[component]) {
result.push(children ? { ...node, children } : node);
continue;
}
const pageKey = normalizePageKey(component);
if (!knownPages.has(pageKey)) {
continue;
}
result.push(children ? { ...node, children } : node);
}
return result;
};
return walk(routes);
}
async function generateAccess(options: GenerateMenuAndRoutesOptions) {
const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');
@@ -31,7 +78,7 @@ async function generateAccess(options: GenerateMenuAndRoutesOptions) {
});
try {
const routes = await getUserMenuApi();
return routes;
return filterMissingPageRoutes(routes || [], pageMap, layoutMap);
} catch (error) {
console.error('❌ 获取用户菜单路由失败:', error);
throw error;
@@ -1,7 +1,19 @@
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import type {
BubbleListProps,
BubbleProps,
Conversation,
} from 'ant-design-x-vue';
import { computed, h, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import {
PlusOutlined,
RobotOutlined,
SettingOutlined,
UserOutlined,
} from '@ant-design/icons-vue';
import {
Button,
@@ -11,9 +23,10 @@ import {
Input,
InputPassword,
Modal,
Textarea,
Spin,
message,
} from 'ant-design-vue';
import { BubbleList, Conversations, Sender } from 'ant-design-x-vue';
import {
createAgentSessionApi,
@@ -23,8 +36,8 @@ import {
listAgentMessagesApi,
listAgentSessionsApi,
streamAgentChat,
updateAgentLlmSettingsApi,
type AgentVO,
updateAgentLlmSettingsApi,
} from '#/api/agent';
import { renderAgentMarkdown } from './markdown';
@@ -37,7 +50,7 @@ const sending = ref(false);
const sessions = ref<AgentVO.Session[]>([]);
const activeThreadId = ref<string | null>(null);
const messages = ref<AgentVO.Message[]>([]);
/** 当前流式助手正文(与 messages 末条同步,避免列表被 loading 遮挡时丢更新) */
/** 当前流式助手正文(与 messages 末条同步) */
const streamingText = ref('');
const draft = ref('');
const settingsOpen = ref(false);
@@ -50,9 +63,13 @@ const llmForm = ref({
apiKeyMasked: '' as string | null,
configured: false,
});
const messagePaneRef = ref<HTMLElement | null>(null);
const bubbleListRef = ref<{
scrollTo?: (info: {
key?: string | number;
block?: ScrollLogicalPosition;
}) => void;
} | null>(null);
let abort: AbortController | null = null;
/** 丢弃过期的 loadMessages */
let messagesLoadSeq = 0;
const activeSession = computed(() =>
@@ -63,23 +80,79 @@ const showMessageLoading = computed(
() => loadingMessages.value && !sending.value && messages.value.length === 0,
);
function bubbleHtml(m: AgentVO.Message, idx: number): string {
const isStreamingAssistant =
sending.value &&
idx === messages.value.length - 1 &&
m.role === 'assistant';
const text = isStreamingAssistant ? streamingText.value : m.content || '';
if (!text) {
return isStreamingAssistant ? '…' : '';
const renderAssistantMarkdown: BubbleProps['messageRender'] = (content) => {
const html = renderAgentMarkdown(String(content ?? ''));
return h('div', { class: 'agent-md', innerHTML: html || '…' });
};
/** Bubble.List 角色预设:SSE 已流式输出,关闭组件自带 typing 动画 */
const bubbleRoles: BubbleListProps['roles'] = {
assistant: {
placement: 'start',
variant: 'filled',
avatar: {
icon: h(RobotOutlined),
style: { background: '#1677ff', color: '#fff' },
},
messageRender: renderAssistantMarkdown,
styles: { content: { maxWidth: 'min(720px, 85%)' } },
},
user: {
placement: 'end',
variant: 'filled',
avatar: {
icon: h(UserOutlined),
style: { background: '#87d068', color: '#fff' },
},
styles: { content: { maxWidth: 'min(720px, 85%)' } },
},
};
const bubbleItems = computed<BubbleListProps['items']>(() =>
messages.value.map((m, idx) => {
const isStreamingAssistant =
sending.value &&
idx === messages.value.length - 1 &&
m.role === 'assistant';
const content = isStreamingAssistant
? streamingText.value || m.content || ''
: m.content || '';
const role = m.role === 'user' ? 'user' : 'assistant';
return {
key: m.id || `${m.seq}-${idx}`,
role,
content,
loading: isStreamingAssistant && !content,
};
}),
);
/** 侧栏会话列表:映射为 Conversations items(label 用字符串,避免 Typography ellipsis+children 告警) */
const conversationItems = computed<Conversation[]>(() =>
sessions.value.map((s) => {
const ts = s.updatedAt || s.lastMessageAt || s.createdAt;
const timeMs = ts ? Date.parse(ts) : undefined;
return {
key: s.threadId,
label: s.title || '新对话',
timestamp: Number.isFinite(timeMs) ? timeMs : undefined,
};
}),
);
function onConversationActiveChange(key: string) {
if (sending.value) {
message.warning('回复生成中,请稍候再切换会话');
return;
}
if (m.role === 'user') {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\n/g, '<br>');
}
return renderAgentMarkdown(text);
activeThreadId.value = key;
}
function scrollBubblesToBottom() {
const items = bubbleItems.value || [];
const last = items[items.length - 1];
if (last?.key == null) return;
bubbleListRef.value?.scrollTo?.({ key: last.key, block: 'end' });
}
async function refreshSessions() {
@@ -102,13 +175,17 @@ async function loadMessages(threadId: string) {
loadingMessages.value = true;
try {
const res = await listAgentMessagesApi(threadId);
if (seq !== messagesLoadSeq || sending.value || threadId !== activeThreadId.value) {
if (
seq !== messagesLoadSeq ||
sending.value ||
threadId !== activeThreadId.value
) {
return;
}
messages.value = res.items || [];
streamingText.value = '';
await nextTick();
scrollToBottom();
scrollBubblesToBottom();
} catch (e: any) {
if (seq === messagesLoadSeq && !sending.value) {
message.error(e?.message || '加载消息失败');
@@ -120,11 +197,6 @@ async function loadMessages(threadId: string) {
}
}
function scrollToBottom() {
const el = messagePaneRef.value;
if (el) el.scrollTop = el.scrollHeight;
}
watch(activeThreadId, (id) => {
if (sending.value) return;
if (id) void loadMessages(id);
@@ -209,11 +281,11 @@ function appendStreamToken(t: string) {
if (last?.role === 'assistant') {
messages.value[idx] = { ...last, content: streamingText.value };
}
void nextTick().then(scrollToBottom);
void nextTick().then(scrollBubblesToBottom);
}
async function send() {
const text = draft.value.trim();
async function send(textOverride?: string) {
const text = (textOverride ?? draft.value).trim();
if (!text || sending.value) return;
if (!activeThreadId.value) {
await createSession();
@@ -237,7 +309,7 @@ async function send() {
content: '',
});
await nextTick();
scrollToBottom();
scrollBubblesToBottom();
abort?.abort();
abort = streamAgentChat({
@@ -268,6 +340,15 @@ async function send() {
});
}
function onSenderSubmit(msg: string) {
void send(msg);
}
function onSenderCancel() {
abort?.abort();
sending.value = false;
}
onBeforeUnmount(() => abort?.abort());
void refreshSessions();
@@ -279,43 +360,37 @@ void refreshSessions();
<aside
class="flex w-64 shrink-0 flex-col border-r border-border bg-card"
>
<div class="flex items-center gap-2 border-b border-border p-3">
<Button type="primary" block @click="createSession">新对话</Button>
<div class="border-b border-border p-3">
<Button type="primary" block @click="createSession">
<template #icon><PlusOutlined /></template>
新对话
</Button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-2">
<div class="relative min-h-0 flex-1">
<div
v-if="loadingSessions"
class="text-muted-foreground py-6 text-center text-sm"
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
>
加载中…
<Spin size="small" />
</div>
<template v-else>
<button
v-for="s in sessions"
:key="s.threadId"
type="button"
class="mb-1 w-full rounded-md px-3 py-2 text-left text-sm transition-colors"
:class="
s.threadId === activeThreadId
? 'bg-primary/10 text-primary'
: 'hover:bg-muted'
"
@click="activeThreadId = s.threadId"
>
<div class="truncate font-medium">{{ s.title }}</div>
<div class="text-muted-foreground mt-0.5 truncate text-xs">
{{ s.updatedAt || '' }}
</div>
</button>
<Empty
v-if="sessions.length === 0"
class="mt-8"
description="暂无会话"
/>
</template>
<Empty
v-if="!loadingSessions && conversationItems.length === 0"
class="mt-10 px-2"
description="暂无会话"
/>
<Conversations
v-else
class="agent-conversations h-full overflow-y-auto px-3 py-2"
:items="conversationItems"
:active-key="activeThreadId ?? undefined"
@active-change="onConversationActiveChange"
/>
</div>
<div class="border-t border-border p-3">
<Button block @click="openSettings">模型 API 设置</Button>
<Button block @click="openSettings">
<template #icon><SettingOutlined /></template>
模型 API 设置
</Button>
</div>
</aside>
@@ -327,51 +402,39 @@ void refreshSessions();
{{ activeSession?.title || '智能助手' }}
</span>
</header>
<div
ref="messagePaneRef"
class="relative min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4"
>
<div class="relative min-h-0 flex-1">
<div
v-if="showMessageLoading"
class="text-muted-foreground py-6 text-center text-sm"
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
>
加载消息…
</div>
<Empty
v-else-if="messages.length === 0"
v-if="!showMessageLoading && messages.length === 0"
class="absolute inset-0 flex items-center justify-center"
description="开始提问吧(需先配置公司模型 API)"
/>
<div
v-for="(m, idx) in messages"
:key="`${m.seq}-${idx}`"
class="flex"
:class="m.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="agent-md max-w-[75%] rounded-2xl px-3 py-2 text-sm leading-relaxed"
:class="
m.role === 'user'
? 'bg-primary text-primary-foreground whitespace-pre-wrap'
: 'bg-muted text-foreground'
"
v-html="bubbleHtml(m, idx)"
></div>
</div>
<BubbleList
v-show="messages.length > 0"
ref="bubbleListRef"
class="h-full px-4 py-4"
:roles="bubbleRoles"
:items="bubbleItems"
:auto-scroll="true"
/>
</div>
<footer class="shrink-0 border-t border-border p-3">
<div class="flex gap-2">
<Textarea
v-model:value="draft"
:rows="2"
:disabled="sending"
placeholder="输入问题,Enter 发送(Shift+Enter 换行)"
class="flex-1"
@keydown.enter.exact.prevent="send"
/>
<Button type="primary" :loading="sending" @click="send">
发送
</Button>
</div>
<Sender
v-model:value="draft"
:loading="sending"
placeholder="输入问题,Enter 发送(Shift+Enter 换行)"
:auto-size="{ minRows: 2, maxRows: 6 }"
submit-type="enter"
@submit="onSenderSubmit"
@cancel="onSenderCancel"
/>
</footer>
</section>
</div>
@@ -436,6 +499,9 @@ void refreshSessions();
</template>
<style scoped>
.agent-conversations :deep(.ant-conversations-list) {
padding-inline: 0;
}
.agent-md :deep(p) {
margin: 0.35em 0;
}