Files
halo-ops-audit/plugin-operation-audit/ui/src/views/AuditLogList.vue
T
836061373 34764c7641 fix: 操作审计移动端改为题头+横向滚动,修复 :deep 作用域失配
上一轮「隐藏题头 + 数据行纵向堆叠」在真机上整批失效:VEntity 是
多根 Fragment 组件(tr + 可选 footer tr),其 <tr> 拿不到本组件的
scoped 作用域 ID,所有锚定 .audit-row 的 :deep 规则永远无法匹配
(Vue 仅在元素为组件 subTree 根时附加父作用域 ID),窄屏下字段仍按
固定列宽横排并被视口截断,且横向滑动也被控制台裁剪。

改为窄屏保持「题头 + 固定列宽」的表格形态:
- 题头与数据行置于同一横向滚动容器 .audit-list(overflow-x: auto,
  同官方 EntityList 的 w-full overflow-x-auto 模式),整体左右
  滑动看全六列,列对齐关系与桌面一致;容器够宽时无滚动条
- .audit-header 增加 min-width: max-content(下划线随内容延伸,
  滑动后不断裂)、.header-col 增加 flex-shrink: 0(列不被压缩)
- 行悬停手型改为锚定自身元素 .audit-list 经 :deep 穿透到
  entity-wrapper,并移除永远失配的 .audit-row 选择器
- 筛选栏窄屏 2 列(≤480px 单列)、分页条换行等此前已生效的
  适配保持不变

重写 AuditLogList.mobile.spec.ts:新增滚动容器/题头可见/列不收缩/
无失效堆叠规则等断言,防止失效方案回归;并在浏览器中于 390×844、
1280×800 与 1024px+侧栏三种宽度下验证横向滑动与列对齐。
2026-11-22 16:27:43 +08:00

637 lines
22 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import {
VButton,
VCard,
VEmpty,
VEntity,
VEntityField,
VLoading,
VPageHeader,
VPagination,
VSpace,
VAlert,
IconRefreshLine,
IconSave,
} from '@halo-dev/components'
import type {
AuditLog,
AuditV1alpha1ConsoleApiExportAuditLogsRequest,
AuditV1alpha1ConsoleApiListAuditLogsRequest,
} from '@/api/generated'
import { auditApiClient } from '@/api'
import {
describeOperation,
displayUsername,
formatTime,
localDateTimeToInstant,
methodBadgeClass,
resultBadge,
SEMANTIC_ACTIONS,
} from '@/utils/audit'
import AuditLogDetail from './AuditLogDetail.vue'
// 查询/导出走生成客户端(ui/src/api/generated,generateApiClient 产物):
// 端点路径与参数由后端 Springdoc 声明生成,禁止在此手写或覆盖。
const RESOURCE_TYPES = [
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
'plugins', 'themes', 'attachments', 'menus', 'categories', 'tags',
]
const loading = ref(false)
const exporting = ref(false)
const error = ref('')
const logs = ref<AuditLog[]>([])
const total = ref(0)
const page = ref(1)
const size = ref(20)
// 筛选条件
const filterUsername = ref('')
const filterResourceType = ref('')
const filterMethod = ref('')
const filterAction = ref('')
const filterResult = ref('')
const filterKeyword = ref('')
const filterStartTime = ref('')
const filterEndTime = ref('')
const selectedLog = ref<AuditLog | null>(null)
const detailVisible = ref(false)
const hasActiveFilter = computed(
() =>
filterUsername.value ||
filterResourceType.value ||
filterMethod.value ||
filterAction.value ||
filterResult.value ||
filterKeyword.value ||
filterStartTime.value ||
filterEndTime.value,
)
/** 查询请求对象(与后端 AuditQueryEndpoint 声明一致的生成参数形态)。 */
function listRequest(): AuditV1alpha1ConsoleApiListAuditLogsRequest {
const fieldSelector: string[] = []
if (filterUsername.value.trim()) {
fieldSelector.push(`spec.username=${filterUsername.value.trim()}`)
}
if (filterResourceType.value) {
fieldSelector.push(`spec.resourceType=${filterResourceType.value}`)
}
if (filterMethod.value) {
fieldSelector.push(`spec.method=${filterMethod.value}`)
}
// 语义动作筛选(spec.action,捕获时标注落库;历史记录无标注不会被筛出)
if (filterAction.value) {
fieldSelector.push(`spec.action=${filterAction.value}`)
}
return {
page: page.value,
size: size.value,
sort: 'metadata.creationTimestamp,desc',
fieldSelector,
result: filterResult.value || undefined,
keyword: filterKeyword.value.trim() || undefined,
startTime: localDateTimeToInstant(filterStartTime.value) ?? undefined,
endTime: localDateTimeToInstant(filterEndTime.value) ?? undefined,
}
}
/** 统一错误摘要:HTTP 错误取状态码(沿用旧 fetch 行为),其余取消息原文。 */
function errorMessage(e: unknown, action: string): string {
const status = (e as { response?: { status?: number } })?.response?.status
if (status) {
return `${action}(HTTP ${status})`
}
return e instanceof Error ? e.message : String(e)
}
async function fetchLogs() {
loading.value = true
error.value = ''
try {
const { data } = await auditApiClient.audit.listAuditLogs(listRequest())
logs.value = data.items ?? []
total.value = data.total ?? 0
} catch (e) {
error.value = errorMessage(e, '查询失败')
logs.value = []
total.value = 0
} finally {
loading.value = false
}
}
/** 导出文件名:audit-logs-<本地时间 yyyyMMdd-HHmmss>.csv(冒号/空格在文件名中非法)。 */
function exportFilename(): string {
const now = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
return (
`audit-logs-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` +
`-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.csv`
)
}
/** 按当前筛选条件导出全部记录:生成客户端(responseType=blob)→ 触发下载,失败进顶部错误提示。 */
async function exportLogs() {
exporting.value = true
error.value = ''
try {
// 导出为全量接口,无需分页参数(复用查询请求,仅保留筛选条件)
const request = listRequest()
const exportRequest: AuditV1alpha1ConsoleApiExportAuditLogsRequest = {
fieldSelector: request.fieldSelector,
result: request.result,
keyword: request.keyword,
startTime: request.startTime,
endTime: request.endTime,
}
const response = await auditApiClient.audit.exportAuditLogs(exportRequest, {
responseType: 'blob',
})
const blob = response.data
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = exportFilename()
anchor.click()
URL.revokeObjectURL(url)
} catch (e) {
error.value = errorMessage(e, '导出失败')
} finally {
exporting.value = false
}
}
function resetFilter() {
filterUsername.value = ''
filterResourceType.value = ''
filterMethod.value = ''
filterAction.value = ''
filterResult.value = ''
filterKeyword.value = ''
filterStartTime.value = ''
filterEndTime.value = ''
}
/**
* 查看该资源历史(功能评审 P1-1):行内快捷动作——预填资源类型 + 资源名关键字
* (关键字匹配资源名称/路径)并刷新列表,与现有筛选/导出条件共用同一套状态,
* 不新增后端参数。仅在有资源名称的记录上提供(集合级/登录操作无可回溯的具体资源)。
*/
function viewResourceHistory(log: AuditLog) {
filterResourceType.value = log.spec.resourceType
filterKeyword.value = log.spec.resourceName ?? ''
applyFilters()
}
watch([filterUsername, filterResourceType, filterMethod, filterAction, filterResult], () => {
page.value = 1
fetchLogs()
})
function applyFilters() {
page.value = 1
fetchLogs()
}
watch([page, size], () => fetchLogs())
function openDetail(log: AuditLog) {
selectedLog.value = log
detailVisible.value = true
}
onMounted(fetchLogs)
</script>
<template>
<div class="audit-page">
<VPageHeader title="操作审计">
<template #icon>
<span class="audit-logo">监</span>
</template>
<template #actions>
<VSpace>
<VButton :loading="exporting" type="default" @click="exportLogs">
<template #icon>
<IconSave class="h-full w-full" />
</template>
导出
</VButton>
<VButton :loading="loading" type="default" @click="fetchLogs">
<template #icon>
<IconRefreshLine class="h-full w-full" />
</template>
刷新
</VButton>
</VSpace>
</template>
</VPageHeader>
<div class="audit-body">
<VAlert v-if="error" class="audit-error" type="error" :closable="true" :title="error" />
<!-- 筛选栏、数据列表、分页条合并为一张白卡:区块之间不再露出灰缝,
分页条白底随卡片铺满整行、与上方列表左右对齐(文字位置保持不变) -->
<VCard :body-class="['!p-0']">
<!-- 筛选栏(只读查询,无任何修改/删除入口) -->
<div class="audit-filter">
<div class="filter-grid">
<label class="filter-item">
<span>操作者</span>
<input
v-model="filterUsername"
type="text"
placeholder="用户名,精确匹配"
/>
</label>
<label class="filter-item">
<span>资源类型</span>
<select v-model="filterResourceType">
<option value="">全部</option>
<option v-for="t in RESOURCE_TYPES" :key="t" :value="t">{{ t }}</option>
</select>
</label>
<label class="filter-item">
<span>动作</span>
<select v-model="filterMethod">
<option value="">全部</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
</label>
<label class="filter-item">
<span>语义动作</span>
<select v-model="filterAction">
<option value="">全部</option>
<option v-for="a in SEMANTIC_ACTIONS" :key="a.value" :value="a.value">
{{ a.label }}
</option>
</select>
</label>
<label class="filter-item">
<span>结果</span>
<select v-model="filterResult">
<option value="">全部</option>
<option value="success">成功</option>
<option value="failure">失败</option>
</select>
</label>
<label class="filter-item">
<span>关键字</span>
<input
v-model="filterKeyword"
type="text"
placeholder="资源名称 / 路径模糊匹配"
@keyup.enter="applyFilters"
/>
</label>
<label class="filter-item">
<span>开始时间</span>
<input v-model="filterStartTime" type="datetime-local" @change="applyFilters" />
</label>
<label class="filter-item">
<span>结束时间</span>
<input v-model="filterEndTime" type="datetime-local" @change="applyFilters" />
</label>
<div class="filter-actions">
<VButton size="sm" @click="applyFilters">查询</VButton>
<VButton size="sm" :disabled="!hasActiveFilter" @click="resetFilter">重置</VButton>
</div>
</div>
</div>
<VLoading v-if="loading && !logs.length" />
<template v-else>
<VEmpty
v-if="!logs.length"
title="暂无审计记录"
:message="hasActiveFilter ? '没有匹配当前筛选条件的记录' : '插件启用后,后台写操作与登录事件会自动记录在这里'"
>
<template #actions>
<VButton @click="hasActiveFilter ? resetFilter() : fetchLogs()">
{{ hasActiveFilter ? '清除筛选' : '刷新' }}
</VButton>
</template>
</VEmpty>
<template v-else>
<!-- 题头与数据行置于同一横向滚动容器:固定列宽合计约 69.5rem,
容器窄于列表(手机/竖屏平板/半屏窗口)时整体左右滑动看全六列,
列对齐关系与桌面完全一致;容器够宽时无溢出、无滚动条,桌面观感不变。
:deep 规则须锚定此容器(本组件自己的元素)才能穿透到 VEntity 行内,
VEntity 是多根 Fragment 组件,其 <tr> 拿不到本组件的 scoped 作用域 ID -->
<div class="audit-list">
<!-- 列题头:分组结构与内边距镜像 entity 行的两个 td,列宽与各 VEntityField 的 width 一一对应 -->
<div class="audit-header">
<div class="header-start">
<span class="header-col col-username">操作者 / 时间</span>
<span class="header-col col-method">动作</span>
<span class="header-col col-resource">资源 / 路径</span>
<span class="header-col col-desc">描述</span>
</div>
<div class="header-end">
<span class="header-col col-status">结果</span>
<span class="header-col col-ip">IP</span>
</div>
</div>
<VEntity
v-for="log in logs"
:key="log.metadata.name"
@click="openDetail(log)"
>
<template #start>
<VEntityField :title="displayUsername(log.spec.username)" width="12rem">
<template #description>
<span class="row-sub">{{ formatTime(log.metadata.creationTimestamp) }}</span>
</template>
</VEntityField>
<!-- 动作列:彩色徽标标注请求方法 -->
<VEntityField width="6rem">
<template #title>
<span class="method-badge" :class="methodBadgeClass(log.spec.method)">
{{ log.spec.method }}
</span>
</template>
</VEntityField>
<VEntityField width="20rem">
<template #title>
<span class="resource-text">
{{ log.spec.resourceType }}
<template v-if="log.spec.resourceName">/ {{ log.spec.resourceName }}</template>
</span>
<!-- 行内快捷动作(功能评审 P1-1):查看该资源的历史操作;
stop 冒泡避免触发行点击的详情抽屉 -->
<a
v-if="log.spec.resourceName"
class="resource-history-link"
title="查看该资源的历史操作"
@click.stop="viewResourceHistory(log)"
>历史</a>
</template>
<template #description>
<span class="row-sub">{{ log.spec.path }}</span>
</template>
</VEntityField>
<!-- 描述列:该操作实际语义的中文描述(如 登录/新建用户/发布文章) -->
<VEntityField width="10rem">
<template #title>
<span class="action-desc">{{ describeOperation(log.spec) }}</span>
</template>
</VEntityField>
</template>
<template #end>
<!-- 结果列:登录失败记录(HTTP 200/302 也可能是失败,语义动作已标注)
显示红色「失败」,避免绿色 200/302 误读为登录成功;
徽标经 #title 插槽渲染(当前版本组件在无 title 时不渲染 #extra,
原先徽标实际不可见) -->
<VEntityField width="4rem">
<template #title>
<span class="status-badge" :class="resultBadge(log.spec).class">
{{ resultBadge(log.spec).text }}
</span>
</template>
</VEntityField>
<VEntityField :title="log.spec.remoteIp" width="9rem" />
</template>
</VEntity>
</div>
</template>
</template>
<!-- 分页条置于卡片内部末尾:白底铺满整行,与上方列表左右对齐 -->
<div v-if="total > 0" class="audit-pagination">
<VPagination
v-model:page="page"
v-model:size="size"
:total="total"
:size-options="[10, 20, 50]"
/>
</div>
</VCard>
</div>
<AuditLogDetail v-model:visible="detailVisible" :log="selectedLog" />
</div>
</template>
<style scoped>
.audit-page {
--audit-green: #4ccba0;
--audit-dark: #0e1731;
--audit-red: #d71d1d;
/* 保持控制台默认灰底,内容以白色卡片呈现(与控制台其他页面观感一致) */
flex: 1;
}
.audit-body {
padding: 1rem 1.25rem 2rem;
display: flex;
flex-direction: column;
/* 筛选、数据、分页合并为一张白卡,区块之间不留灰缝 */
}
.audit-logo {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 0.375rem;
background: var(--audit-dark);
color: #fff;
font-size: 0.8rem;
}
.audit-filter {
padding: 0.75rem 1rem;
}
.filter-grid {
display: grid;
/* 8 个筛选字段 + 自动宽度的操作按钮,全部排成一行 */
grid-template-columns: repeat(8, minmax(0, 1fr)) auto;
gap: 0.75rem 1rem;
align-items: end;
}
.filter-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.75rem;
color: #666;
}
.filter-item input,
.filter-item select {
height: 2rem;
padding: 0 0.5rem;
border: 1px solid #ddd;
border-radius: 0.375rem;
font-size: 0.8125rem;
background: #fff;
min-width: 0;
}
.filter-item input:focus,
.filter-item select:focus {
outline: none;
border-color: var(--audit-green);
}
.filter-actions {
display: flex;
gap: 0.5rem;
}
/* 题头与数据行共用横向滚动容器(同官方 EntityList 的 w-full overflow-x-auto):
固定列宽合计约 69.5rem,容器更窄(手机/竖屏平板/半屏窗口)时整体左右滑动;
容器够宽时不产生滚动条,桌面观感不变。
VEntity 行内样式一律经此自身元素 :deep 穿透:VEntity 是多根 Fragment 组件,
其 <tr> 拿不到本组件的 scoped 作用域 ID,锚定 .audit-row 的规则永远失配。 */
.audit-list {
overflow-x: auto;
}
/* 列题头:VEntity 数据行由两个 td(entity-start-wrapper / entity-end-wrapper)组成,
每个 td 自带 1rem 左右内边距,end 组紧跟 start 组之后(行宽由内容收缩,不铺满)。
题头按同样结构分两组、各组自带 1rem 内边距,才能与数据列一一对齐;
不可用 margin-left: auto 把 end 组推到行尾(数据行并非如此布局)。 */
.audit-header {
display: flex;
align-items: center;
/* 滚动容器内题头盒随内容延伸(否则下划线止于可视宽度,滑动后断裂);
容器更宽时仍为 100%,与桌面一致 */
min-width: max-content;
padding: 0.5rem 0;
border-bottom: 1px solid #eaecf0;
}
.header-start {
display: flex;
gap: 1rem;
padding: 0 1rem;
}
.header-end {
display: flex;
gap: 1.5rem;
padding: 0 1rem;
}
.header-col {
font-size: 0.75rem;
color: #666;
white-space: nowrap;
/* 列宽不参与 flex 收缩:窄屏下题头盒宽由内容决定,避免被压缩与数据列错位 */
flex-shrink: 0;
}
.col-username { width: 12rem; }
.col-method { width: 6rem; }
.col-resource { width: 20rem; }
.col-desc { width: 10rem; }
.col-status { width: 4rem; }
.col-ip { width: 9rem; }
.audit-error {
--tw-ring-color: transparent;
/* 错误提示位于白卡上方,与卡片留出间距 */
margin-bottom: 1rem;
}
/* 行悬停手型:VEntity 多根组件的 tr 无法携带本组件 scoped 作用域 ID,
规则须锚定自身元素 .audit-list 再 :deep 穿透到行 */
.audit-list :deep(.entity-wrapper) {
cursor: pointer;
}
.row-sub {
font-size: 0.75rem;
color: #999;
max-width: 22rem;
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.resource-text {
font-size: 0.8125rem;
}
/* 行内快捷动作:查看该资源历史(P1-1),主题绿小链接 */
.resource-history-link {
margin-left: 0.375rem;
font-size: 0.75rem;
color: var(--audit-green);
cursor: pointer;
}
.resource-history-link:hover {
text-decoration: underline;
}
.method-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
font-family: ui-monospace, monospace;
color: #fff;
background: #6b7280;
}
/* 描述列:中文操作描述,超宽时截断(列宽固定 10rem) */
.action-desc {
display: inline-block;
max-width: 9.75rem;
font-size: 0.8125rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.method-post { background: #1e7ee0; }
.method-put { background: #d97706; }
.method-delete { background: var(--audit-red); }
.method-patch { background: #7c3aed; }
.status-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
font-family: ui-monospace, monospace;
}
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.status-fail { color: var(--audit-red); background: rgba(215, 29, 29, 0.12); }
.audit-pagination {
/* 在白卡内铺满整行:白底与上方列表左右对齐;上下各留 1rem,
文字的垂直位置与原分页条一致;上边缘 1px 分隔线同控制台卡片 footer 观感 */
padding: 1rem;
border-top: 1px solid #eaecf0;
}
/* ===== 移动端适配(窄屏:手机 / 竖屏平板 / 半屏小窗口) =====
桌面布局的 9 列筛选行在窄屏下每列仅剩数十像素(标签逐字换行、
输入框被压扁),窄屏改为筛选 2 列(≤480px 手机竖屏单列)。
列表保持题头 + 固定列宽的表格形态,由 .audit-list 整体左右滑动看全六列,
列对齐与桌面一致。数据行纵向堆叠方案不可行:VEntity 是多根 Fragment
组件,其 <tr> 拿不到本组件的 scoped 作用域 ID,所有锚定 .audit-row 的
行内 :deep 规则均失配(历史方案因此整批失效),且堆叠后题头无从对齐。
≥1024px 维持桌面布局不变。
媒体查询置于文件末尾,同特异性规则按顺序覆盖桌面样式。 */
@media (max-width: 1023px) {
.audit-body {
padding: 0.75rem 0.75rem 1.5rem;
}
.filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.75rem;
}
.filter-actions {
grid-column: 1 / -1;
}
.filter-actions > :deep(*) {
flex: 1;
}
/* 分页条(总数 + 翻页/条数控制器)窄屏下换行铺开,不横向溢出 */
.audit-pagination :deep(.pagination),
.audit-pagination :deep(.pagination__controller) {
flex-wrap: wrap;
}
}
@media (max-width: 480px) {
/* 手机竖屏:单列筛选,datetime-local 等宽控件不再被压扁 */
.filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
</style>