feat: element plus UI组件库

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
sophieandCursor committed 2026-10-14 20:25:35 +08:00
1 parent 041bb73b9a
commit 5f6fbcd76f
30 files changed
+3621 -1327

No files matched your search

@@ -2,28 +2,33 @@
/**
* features/kb/components/KbAdminPanel.vue
* 知识库配置面板(治理面:分组、Dify)。
* 依赖:kb.api、DifySettingsDialog、DifyHealthDialog、DeleteConfirmDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组;分组列表在主表格过滤排序,新增/编辑通过右侧抽屉提交。
* 依赖:kb.api、Element Plus、DifySettingsDialog、DifyHealthDialog、Vue I18n。
* 逻辑:管理控制台加载知识库分组;列表、表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { CircleCheck, Plus, Search, Setting, Tools } from '@element-plus/icons-vue';
import {
Activity,
Pencil,
Plus,
RefreshCw,
Search,
Settings,
Trash2,
Wrench,
} from 'lucide-vue-next';
ElAlert,
ElButton,
ElConfigProvider,
ElInput,
ElLoading,
ElMessageBox,
ElPagination,
ElSpace,
ElTable,
ElTableColumn,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import KbGroupDrawer, { type KbGroupFormValue } from './KbGroupDrawer.vue';
import DifyHealthDialog from './DifyHealthDialog.vue';
import DifySettingsDialog from './DifySettingsDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
createKbGroup,
@@ -35,35 +40,42 @@ import {
import { formatDateTime } from '../utils/kb-display.utils';
type GroupFilterMode = 'all' | 'withDocs' | 'empty';
type GroupSortMode = 'updatedDesc' | 'updatedAsc' | 'docsDesc' | 'docsAsc' | 'nameAsc';
type GroupSortKey = 'name' | 'document_count' | 'updated_at';
const router = useRouter();
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const vLoading = ElLoading.directive;
const groups = ref<KbGroup[]>([]);
const isSubmitting = ref(false);
const isDeleting = ref(false);
const isRefreshing = ref(false);
const isRefreshing = ref(true);
const editingGroupId = ref<number | null>(null);
const form = ref<KbGroupFormValue>({ name: '', description: '' });
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const settingsDialogOpen = ref(false);
const healthDialogOpen = ref(false);
const deleteDialogOpen = ref(false);
const drawerOpen = ref(false);
const deletingGroup = ref<KbGroup | null>(null);
const searchKeyword = ref('');
const filterMode = ref<GroupFilterMode>('all');
const sortMode = ref<GroupSortMode>('updatedDesc');
const sortKey = ref<GroupSortKey | ''>('updated_at');
const sortDir = ref<'asc' | 'desc' | ''>('desc');
const currentPage = ref(1);
const pageSize = ref(20);
const filterOptions: GroupFilterMode[] = ['all', 'withDocs', 'empty'];
const sortOptions: GroupSortMode[] = ['updatedDesc', 'updatedAsc', 'docsDesc', 'docsAsc', 'nameAsc'];
const pageSizeOptions = [10, 20, 50, 100];
const totalDocuments = computed(() => groups.value.reduce((total, group) => total + (group.document_count ?? 0), 0));
/**
* 文档数表头筛选项。
* 核心逻辑:不放「全部」;Element 筛选面板的重置会清空条件,等同于全部。
*/
const documentFilters = computed(() => [
{ text: t('kbAdmin.filters.withDocs'), value: 'withDocs' },
{ text: t('kbAdmin.filters.empty'), value: 'empty' },
]);
const filteredGroups = computed(() => {
const keyword = searchKeyword.value.trim().toLowerCase();
const matched = groups.value.filter((group) => {
@@ -77,16 +89,17 @@ const filteredGroups = computed(() => {
return matchesKeyword && matchesFilter;
});
if (!sortKey.value || !sortDir.value) return matched;
return [...matched].sort((a, b) => {
const docsA = a.document_count ?? 0;
const docsB = b.document_count ?? 0;
const updatedA = Date.parse(a.updated_at || '') || 0;
const updatedB = Date.parse(b.updated_at || '') || 0;
if (sortMode.value === 'updatedAsc') return updatedA - updatedB;
if (sortMode.value === 'docsDesc') return docsB - docsA;
if (sortMode.value === 'docsAsc') return docsA - docsB;
if (sortMode.value === 'nameAsc') return a.name.localeCompare(b.name, undefined, { numeric: true });
return updatedB - updatedA;
let result = 0;
if (sortKey.value === 'name') {
result = a.name.localeCompare(b.name, undefined, { numeric: true });
} else if (sortKey.value === 'document_count') {
result = (a.document_count ?? 0) - (b.document_count ?? 0);
} else {
result = (Date.parse(a.updated_at || '') || 0) - (Date.parse(b.updated_at || '') || 0);
}
return sortDir.value === 'asc' ? result : -result;
});
});
const pagedGroups = computed(() => {
@@ -94,19 +107,33 @@ const pagedGroups = computed(() => {
return filteredGroups.value.slice(start, start + pageSize.value);
});
/**
* 表格空状态文案。
* 核心逻辑:一个分组都没有时提示去创建;有分组但筛选后为空时提示调整条件。
*/
const tableEmptyText = computed(() => (
groups.value.length === 0 ? t('kbAdmin.groupsEmpty') : t('kbAdmin.filters.emptyResult')
));
/** 格式化分组更新时间,避免管理台表格直接暴露后端 ISO 时间字符串。 */
const formatGroupUpdatedAt = (value?: string | null) => formatDateTime(value);
/** 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 */
/**
* 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。
* 核心逻辑:只等分组列表;失败写入页面提示,并用 finally 关掉表格加载态。
*/
const loadData = async () => {
isRefreshing.value = true;
const groupsResult = await getKbGroupsSafe();
if (groupsResult.ok) groups.value = groupsResult.data;
else {
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
feedbackType.value = 'error';
try {
const groupsResult = await getKbGroupsSafe();
if (groupsResult.ok) groups.value = groupsResult.data;
else {
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
feedbackType.value = 'error';
}
} finally {
isRefreshing.value = false;
}
isRefreshing.value = false;
};
/** 重置分组表单到新建状态,关闭抽屉或切换新建时清空当前编辑对象。 */
@@ -162,17 +189,27 @@ const handleSubmitGroup = async () => {
await loadData();
};
/** 打开分组删除确认弹窗,确认前不直接调用删除接口。 */
const handleDeleteGroup = (group: KbGroup) => {
deletingGroup.value = group;
deleteDialogOpen.value = true;
};
/** 确认删除当前选中的分组,并在成功后同步刷新列表与编辑表单状态。 */
const handleDeleteGroupConfirm = async () => {
if (!deletingGroup.value) return;
/**
* 确认后删除分组,并刷新列表。
* 核心逻辑:Element 确认框取消会 reject,这里直接返回,不调用删除接口。
* @param group - 待删除的分组
*/
const handleDeleteGroup = async (group: KbGroup) => {
try {
await ElMessageBox.confirm(
t('kbAdmin.deleteDialog.message', { name: group.name }),
t('kbAdmin.deleteDialog.title'),
{
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
},
);
} catch {
return;
}
isDeleting.value = true;
const result = await deleteKbGroup(deletingGroup.value.id);
const result = await deleteKbGroup(group.id);
isDeleting.value = false;
if (!result.ok) {
feedback.value = result.error || t('kbAdmin.msg.deleteFailed');
@@ -180,15 +217,46 @@ const handleDeleteGroupConfirm = async () => {
return;
}
if (editingGroupId.value === deletingGroup.value.id) closeDrawer();
if (editingGroupId.value === group.id) closeDrawer();
feedback.value = t('kbAdmin.msg.deleted');
feedbackType.value = 'success';
deleteDialogOpen.value = false;
deletingGroup.value = null;
await loadData();
};
watch([searchKeyword, filterMode, sortMode, pageSize], () => {
/**
* 按文档数表头筛选全部分组,并回到第一页。
* 核心逻辑:筛选发生在分页之前。未选或重置时显示全部;单选时只留有文档或空分组。
* @param filters - Element 按 column-key 给出的已选值
*/
function onFilterChange(filters: Record<string, string[]>): void {
const selected = filters.document_count ?? [];
if (selected.length === 1 && (selected[0] === 'withDocs' || selected[0] === 'empty')) {
filterMode.value = selected[0];
} else {
filterMode.value = 'all';
}
currentPage.value = 1;
}
/**
* 按表头把筛选后的全部分组重排,并回到第一页。
* 核心逻辑:排序发生在分页之前,所以翻页后顺序不变。第三次点击表头时 Element 清空排序,列表回到接口原顺序。
* @param payload.prop - 列字段
* @param payload.order - ascending、descending 或空
*/
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const field = payload.prop;
if ((field === 'name' || field === 'document_count' || field === 'updated_at') && payload.order) {
sortKey.value = field;
sortDir.value = payload.order === 'ascending' ? 'asc' : 'desc';
} else {
sortKey.value = '';
sortDir.value = '';
}
currentPage.value = 1;
}
watch([searchKeyword, pageSize], () => {
currentPage.value = 1;
});
@@ -200,142 +268,98 @@ defineExpose({ loadData });
</script>
<template>
<div class="animate-fade-in-up">
<div class="kb-admin-header">
<ElConfigProvider :locale="elementLocale">
<section class="admin-table-section">
<div class="admin-table-header admin-table-header--stacked">
<div class="min-w-0 flex-1">
<h2 class="text-xl font-bold text-primary">{{ t('kbAdmin.groupsTitle') }}</h2>
<h2 class="section-title">{{ t('kbAdmin.groupsTitle') }}</h2>
<p class="section-desc mt-1">{{ t('kbAdmin.groupManageSubtitle') }}</p>
</div>
<div class="flex w-full shrink-0 flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:justify-end">
<div class="kb-admin-toolbar" role="toolbar" :aria-label="t('kbAdmin.toolbar')">
<button type="button" class="kb-admin-toolbar-btn" @click="settingsDialogOpen = true" :title="t('kbAdmin.difySettings')">
<Settings class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.difySettings') }}</span>
</button>
<button type="button" class="kb-admin-toolbar-btn" @click="healthDialogOpen = true" :title="t('kbAdmin.healthCheck')">
<Activity class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.healthCheck') }}</span>
</button>
<button type="button" class="kb-admin-toolbar-btn" @click="loadData" :title="t('common.refresh')">
<RefreshCw class="h-4 w-4 shrink-0" :class="{ 'animate-spin': isRefreshing }" />
<span class="whitespace-nowrap">{{ t('common.refresh') }}</span>
</button>
</div>
<button type="button" class="btn-secondary inline-flex w-full items-center justify-center gap-2 px-4 py-2.5 text-sm sm:w-auto" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">
<Wrench class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.goWorkspace') }}</span>
</button>
<button type="button" class="btn-primary inline-flex w-full items-center justify-center gap-2 px-4 py-2.5 text-sm sm:w-auto" @click="openCreateDrawer">
<Plus class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap">{{ t('kbAdmin.form.create') }}</span>
</button>
</div>
<ElSpace wrap>
<ElButton :icon="Setting" @click="settingsDialogOpen = true">{{ t('kbAdmin.difySettings') }}</ElButton>
<ElButton :icon="CircleCheck" @click="healthDialogOpen = true">{{ t('kbAdmin.healthCheck') }}</ElButton>
<ElButton :icon="Tools" @click="router.push(WORKSPACE_PATHS.knowledgeBase)">{{ t('kbAdmin.goWorkspace') }}</ElButton>
<ElButton type="primary" :icon="Plus" @click="openCreateDrawer">{{ t('kbAdmin.form.create') }}</ElButton>
</ElSpace>
</div>
<div class="kb-admin-body">
<section class="admin-table-section">
<div class="admin-table-filters flex flex-col gap-4">
<div class="grid grid-cols-1 gap-3 lg:grid-cols-[minmax(16rem,1fr)_auto_minmax(11rem,14rem)] lg:items-center">
<label class="relative min-w-0">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input v-model="searchKeyword" class="input-field w-full pl-9" :placeholder="t('kbAdmin.filters.searchPlaceholder')" />
</label>
<div class="inline-flex w-full overflow-hidden rounded-xl border border-default bg-surface lg:w-auto">
<button
v-for="option in filterOptions"
:key="option"
type="button"
class="min-w-0 flex-1 whitespace-nowrap px-4 py-2.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover:text-primary lg:flex-none"
:class="{ 'bg-brand-50 text-brand-700': filterMode === option }"
@click="filterMode = option"
>
{{ t(`kbAdmin.filters.${option}`) }}
</button>
</div>
<select v-model="sortMode" class="select-field w-full">
<option v-for="option in sortOptions" :key="option" :value="option">
{{ t(`kbAdmin.sort.${option}`) }}
</option>
</select>
</div>
<div class="flex flex-wrap items-center gap-3 text-xs text-muted">
<span>{{ t('kbAdmin.stats.groups', { count: groups.length }) }}</span>
<span>{{ t('kbAdmin.stats.documents', { count: totalDocuments }) }}</span>
<span>{{ t('kbAdmin.stats.visible', { count: filteredGroups.length }) }}</span>
</div>
</div>
<p v-if="feedback" class="mx-6 mt-4 rounded-xl border px-4 py-3 text-sm" :class="feedbackType === 'error' ? 'border-rose-200 bg-rose-50 text-rose-600' : 'border-emerald-200 bg-emerald-50 text-emerald-700'">
{{ feedback }}
</p>
<div v-if="groups.length === 0" class="admin-table-empty">{{ t('kbAdmin.groupsEmpty') }}</div>
<div v-else-if="filteredGroups.length === 0" class="admin-table-empty">{{ t('kbAdmin.filters.emptyResult') }}</div>
<div v-else>
<div class="admin-table-wrap hidden md:block">
<table class="admin-table table-fixed">
<thead>
<tr>
<th class="w-[20%] px-6 py-3 text-xs">{{ t('kbAdmin.table.name') }}</th>
<th class="w-[30%] px-6 py-3 text-xs">{{ t('kbAdmin.table.description') }}</th>
<th class="w-[12%] px-6 py-3 text-xs">{{ t('kbAdmin.table.documents') }}</th>
<th class="w-[26%] px-6 py-3 text-xs">{{ t('kbAdmin.table.updatedAt') }}</th>
<th class="w-[12%] px-6 py-3 text-right text-xs">{{ t('kbAdmin.table.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="group in pagedGroups" :key="group.id">
<td class="px-6 py-4 align-middle"><div class="truncate font-semibold text-primary" :title="group.name">{{ group.name }}</div></td>
<td class="px-6 py-4 align-middle text-sm text-muted">
<div class="truncate" :title="group.description || t('kbAdmin.noDescription')">
{{ group.description || t('kbAdmin.noDescription') }}
</div>
</td>
<td class="px-6 py-4 align-middle"><span class="kb-admin-badge whitespace-nowrap">{{ group.document_count ?? 0 }}</span></td>
<td class="px-6 py-4 align-middle text-sm text-muted"><div class="truncate" :title="formatGroupUpdatedAt(group.updated_at)">{{ formatGroupUpdatedAt(group.updated_at) }}</div></td>
<td class="px-6 py-4 align-middle">
<div class="flex justify-end gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
<button type="button" class="btn-icon-ds border border-rose-200 text-rose-600 hover:bg-rose-50" @click="handleDeleteGroup(group)" :disabled="isDeleting" :title="t('common.delete')"><Trash2 class="h-4 w-4" /></button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="space-y-3 p-4 md:hidden">
<article v-for="group in pagedGroups" :key="group.id" class="kb-admin-card">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h3 class="font-semibold text-primary">{{ group.name }}</h3>
<p class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || t('kbAdmin.noDescription')">{{ group.description || t('kbAdmin.noDescription') }}</p>
</div>
<span class="kb-admin-badge">{{ group.document_count ?? 0 }}</span>
</div>
<div class="mt-3 flex items-center justify-between gap-3">
<span class="text-xs text-muted">{{ formatGroupUpdatedAt(group.updated_at) }}</span>
<div class="flex gap-1.5">
<button type="button" class="btn-icon-ds border border-default" @click="openEditDrawer(group)" :title="t('common.edit')"><Pencil class="h-4 w-4" /></button>
<button type="button" class="btn-icon-ds border border-rose-200 text-rose-600" @click="handleDeleteGroup(group)" :title="t('common.delete')"><Trash2 class="h-4 w-4" /></button>
</div>
</div>
</article>
</div>
<div class="border-t border-default px-6 py-4">
<PaginationBar
v-model:page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-size-options="pageSizeOptions"
<div class="kb-admin-filters">
<div class="kb-element-filters">
<ElInput
v-model="searchKeyword"
clearable
:prefix-icon="Search"
:placeholder="t('kbAdmin.filters.searchPlaceholder')"
/>
</div>
</div>
</section>
</div>
</div>
<ElAlert
v-if="feedback"
class="kb-admin-alert"
:title="feedback"
:type="feedbackType === 'error' ? 'error' : 'success'"
show-icon
closable
@close="feedback = ''"
/>
<ElTable
v-loading="isRefreshing"
class="hx-admin-table"
:data="pagedGroups"
row-key="id"
:default-sort="{ prop: 'updated_at', order: 'descending' }"
:empty-text="tableEmptyText"
@sort-change="onSortChange"
@filter-change="onFilterChange"
>
<ElTableColumn prop="name" :label="t('kbAdmin.table.name')" min-width="160" sortable="custom">
<template #default="{ row }">
<div class="truncate" :title="(row as KbGroup).name">{{ (row as KbGroup).name }}</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('kbAdmin.table.description')" min-width="220">
<template #default="{ row }">
<div class="truncate hx-element-hint" :title="(row as KbGroup).description || t('kbAdmin.noDescription')">
{{ (row as KbGroup).description || t('kbAdmin.noDescription') }}
</div>
</template>
</ElTableColumn>
<ElTableColumn
prop="document_count"
column-key="document_count"
:label="t('kbAdmin.table.documents')"
width="160"
sortable="custom"
:filters="documentFilters"
:filter-multiple="false"
>
<template #default="{ row }">{{ (row as KbGroup).document_count ?? 0 }}</template>
</ElTableColumn>
<ElTableColumn prop="updated_at" :label="t('kbAdmin.table.updatedAt')" min-width="180" sortable="custom">
<template #default="{ row }">{{ formatGroupUpdatedAt((row as KbGroup).updated_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('kbAdmin.table.actions')" width="160" align="right">
<template #default="{ row }">
<ElButton link type="primary" @click="openEditDrawer(row as KbGroup)">{{ t('common.edit') }}</ElButton>
<ElButton link type="danger" :disabled="isDeleting" @click="handleDeleteGroup(row as KbGroup)">
{{ t('common.delete') }}
</ElButton>
</template>
</ElTableColumn>
</ElTable>
<div v-if="filteredGroups.length > 0" class="hx-admin-pager">
<ElPagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:total="filteredGroups.length"
:page-sizes="pageSizeOptions"
layout="total, sizes, prev, pager, next"
background
/>
</div>
</section>
<KbGroupDrawer
v-model:form="form"
@@ -348,5 +372,32 @@ defineExpose({ loadData });
<DifySettingsDialog :open="settingsDialogOpen" @close="settingsDialogOpen = false" @saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }" @error="(message) => { feedback = message; feedbackType = 'error'; }" />
<DifyHealthDialog :open="healthDialogOpen" @close="healthDialogOpen = false" @error="(message) => { feedback = message; feedbackType = 'error'; }" />
<DeleteConfirmDialog v-model="deleteDialogOpen" :title="t('kbAdmin.deleteDialog.title')" :message="t('kbAdmin.deleteDialog.message', { name: deletingGroup?.name || '' })" :confirm-loading="isDeleting" @confirm="handleDeleteGroupConfirm" @cancel="() => { deleteDialogOpen = false; deletingGroup = null; }" />
</ElConfigProvider>
</template>
<style scoped>
.kb-admin-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px 24px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.kb-admin-alert {
margin: 16px 32px 0;
}
.kb-element-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.kb-element-filters :deep(.el-input) {
width: 16rem;
flex: none;
}
</style>