Files
crawler-plugin/frontend-vue/src/shared/components/NotificationBell.vue
T
huangzd1997 6096e85d32 refactor(代理): 用户余量巡检与长样式出件,压回可读性棘轮
推送闸门抓到 UserApiSecretService 1278→1408、两枚 Vue 超过 800 行:
把用户级余量查询/缓存/巡检拆到 UserProxyBalanceService,两端组件的大段
样式移到同名 .css 由 scoped src 挂载。行为与选择器不变,只为让长文件棘轮
回到基线以内(不调基线、不整份回写)。
2026-10-21 14:26:03 +08:00

468 lines
16 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.
<template>
<div ref="rootRef" class="notification-bell" :class="`notification-bell--${theme}`">
<button
type="button"
class="bell-trigger"
:class="{ 'bell-trigger--active': panelOpen }"
:title="unreadCount > 0 ? `通知(${unreadCount} 条未读)` : '通知'"
aria-label="通知"
@click="togglePanel"
>
<svg
class="bell-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>
<span v-if="badgeText" class="bell-badge">{{ badgeText }}</span>
</button>
<!-- 面板挂到 body 上(fixed 定位):顶栏内绝对定位时会被页面内容压住(如 el-select),提 z-index 无效 -->
<Teleport to="body">
<div
v-if="panelOpen"
ref="panelRef"
class="bell-panel"
:class="`bell-panel--${theme}`"
:style="panelStyle"
role="dialog"
aria-label="通知列表"
>
<header class="bell-head">
<div class="bell-head-title">
<span class="bell-title-text">通知</span>
<span v-if="unreadCount > 0" class="bell-unread-chip">{{ unreadChipText }}</span>
</div>
<button
v-if="unreadCount > 0"
type="button"
class="bell-read-all"
:disabled="markingAll"
@click="readAll"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.4"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m5 12 5 5L20 7" />
</svg>
{{ markingAll ? '处理中' : '全部已读' }}
</button>
</header>
<div class="bell-filters">
<div class="bell-search-box">
<svg
class="bell-search-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="11" cy="11" r="7" />
<path d="m21 21-4.35-4.35" />
</svg>
<input
v-model="keyword"
type="text"
class="bell-search-input"
placeholder="搜索标题或内容"
aria-label="搜索通知"
@input="onKeywordInput"
/>
<button
v-if="keyword"
type="button"
class="bell-search-clear"
aria-label="清空搜索"
@click="clearKeyword"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.2"
stroke-linecap="round"
aria-hidden="true"
>
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</div>
<div class="bell-category-chips" role="group" aria-label="按类型筛选">
<button
type="button"
class="bell-chip"
:class="{ 'is-active': !category }"
@click="selectCategory('')"
>
全部
</button>
<button
v-for="option in NOTIFICATION_CATEGORY_OPTIONS"
:key="option.value"
type="button"
class="bell-chip"
:class="{ 'is-active': category === option.value }"
@click="selectCategory(option.value)"
>
{{ option.label }}
</button>
</div>
<div class="bell-sort-chips" role="group" aria-label="通知排序">
<span class="bell-sort-label">排序</span>
<button
type="button"
class="bell-chip"
:class="{ 'is-active': sortMode === 'severity' }"
@click="setSortMode('severity')"
>
严重度
</button>
<button
type="button"
class="bell-chip"
:class="{ 'is-active': sortMode === 'time' }"
@click="setSortMode('time')"
>
时间
</button>
</div>
<div class="bell-search-days">
<el-date-picker
:model-value="dateRange"
type="daterange"
value-format="YYYY-MM-DD"
start-placeholder="开始日期"
end-placeholder="结束日期"
range-separator="至"
class="bell-date-picker"
popper-class="bell-date-popper"
:clearable="true"
@update:model-value="onDateRangeChange"
@change="reload"
/>
<button v-if="hasFilter" type="button" class="bell-search-reset" @click="resetFilters">
重置
</button>
</div>
</div>
<div v-if="loading && !groups.length" class="bell-skeleton" aria-label="正在加载">
<div v-for="row in 3" :key="row" class="bell-skeleton-row">
<span class="bell-skeleton-icon"></span>
<span class="bell-skeleton-lines">
<span class="bell-skeleton-bar bell-skeleton-bar--title"></span>
<span class="bell-skeleton-bar bell-skeleton-bar--text"></span>
</span>
</div>
</div>
<div v-else-if="loadError && !groups.length" class="bell-state">
<span class="bell-state-icon bell-state-icon--error" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</svg>
</span>
<p class="bell-state-text">{{ loadError }}</p>
<button type="button" class="bell-state-action" @click="reload">重新加载</button>
</div>
<div v-else-if="!groups.length" class="bell-state">
<span class="bell-state-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>
</span>
<p class="bell-state-text">{{ hasFilter ? '没有符合条件的通知' : '暂无通知' }}</p>
<p v-if="hasFilter" class="bell-state-sub">试试调整类型、搜索词或时间范围</p>
</div>
<ul v-else class="bell-list">
<template v-for="(group, index) in groups" :key="notificationGroupKey(group)">
<!-- 严重度排序会跨天交错,日期头只在时间排序下有意义 -->
<li v-if="sortMode === 'time' && startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
<li
class="bell-item bell-group"
:class="[`bell-item--${itemLevel(group)}`, { 'bell-group--open': isExpanded(group) }]"
@click="toggleGroup(group)"
>
<NotificationLevelIcon :level="itemLevel(group)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(group)}`">
{{ severityLabel(group) }}
</span>
<span class="bell-item-title" :title="group.title">{{ group.title }}</span>
<span
class="bell-item-dot"
:class="{ 'bell-item-dot--on': group.unreadCount > 0 }"
aria-hidden="true"
></span>
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
</div>
<p class="bell-item-content" :title="group.content">{{ group.content }}</p>
<div class="bell-group-foot">
<span class="bell-group-count">{{ formatGroupCounts(group.rowCount, group.unreadCount) }}</span>
<span class="bell-group-toggle">{{ isExpanded(group) ? '收起明细' : '展开明细' }}</span>
</div>
</div>
</li>
<!-- 已读只能进明细逐条点:聚合行上的点击只做展开,避免"看一眼顺手把没看过的全标成已读" -->
<template v-if="isExpanded(group)">
<li v-if="detailLoading" class="bell-detail-state">正在加载明细...</li>
<li v-else-if="!details.length" class="bell-detail-state">这一组里没有通知</li>
<li
v-for="item in details"
:key="item.id"
class="bell-item bell-item--detail"
:class="[`bell-item--${itemLevel(item)}`, { 'bell-item--unread': !item.read }]"
@click="onItemClick(item)"
>
<NotificationLevelIcon :level="itemLevel(item)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(item)}`">
{{ severityLabel(item) }}
</span>
<span class="bell-item-title" :title="item.title">{{ item.title }}</span>
<span class="bell-item-dot" :class="{ 'bell-item-dot--on': !item.read }" aria-hidden="true"></span>
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
</div>
<p class="bell-item-content" :title="item.content">{{ item.content }}</p>
</div>
</li>
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-state">
另有 {{ detailTotal - details.length }} 条未列出,可缩小时间范围后查看
</li>
</template>
</template>
</ul>
<footer class="bell-foot">
<div class="bell-foot-meta">
<span class="bell-foot-total">共 {{ total }} 组 · 明细 {{ rowCount }} 条</span>
<select
v-model="pageSize"
class="bell-size-select"
aria-label="每页条数"
@change="onPageSizeChange"
>
<option v-for="size in PAGE_SIZES" :key="size" :value="size">{{ size }}条/页</option>
</select>
</div>
<div class="bell-pager">
<button
type="button"
class="bell-page-btn"
:disabled="page <= 1 || loading"
@click="goPage(page - 1)"
>
上一页
</button>
<span class="bell-page-info">第 {{ page }} / {{ totalPages }} 页</span>
<button
type="button"
class="bell-page-btn"
:disabled="page >= totalPages || loading"
@click="goPage(page + 1)"
>
下一页
</button>
</div>
</footer>
</div>
</Teleport>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { NOTIFICATION_CATEGORY_OPTIONS } from '@/shared/api/types/modules/notification'
import {
PANEL_PAGE_SIZES as PAGE_SIZES,
itemLevel,
itemSeverity,
severityLabel,
startsNewDay as groupStartsNewDay,
useNotificationBellPanel,
} from '@/shared/composables/useNotificationBellPanel'
import {
NOTIFICATION_POLL_INTERVAL_MS,
currentNotificationUid,
formatDayLabel,
formatGroupCounts,
formatNotificationTime,
formatUnreadBadge,
notificationGroupKey,
} from '@/shared/utils/notification-bell'
/** 顶栏主题:工具页/配置页深色(dark),桌面入口首页浅色(light)。 */
const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
theme: 'dark',
})
const theme = computed(() => props.theme)
const uid = currentNotificationUid()
/**
* 面板的数据流(聚合组、明细、两个计数、筛选与防抖)整块在 useNotificationBellPanel.ts。
* 那一层是真函数,`npm test` 能直接跑判据;组件只留 DOM 相关的一半:
* 面板开合、fixed 定位与窄窗回让、外部点击关闭、60s 轮询定时器。
*/
const {
badgeCount,
category,
clearKeyword,
dateRange,
detailLoading,
detailTotal,
details,
goPage,
groups,
hasFilter,
isExpanded,
keyword,
loadError,
loading,
markingAll,
onDateRangeChange,
onItemClick,
onKeywordInput,
onPageSizeChange,
page,
pageSize,
readAll,
refreshSummary,
reload,
resetFilters,
rowCount,
selectCategory,
setSortMode,
sortMode,
toggleGroup,
total,
totalPages,
unreadCount,
unreadGroupCount,
} = useNotificationBellPanel({ uid: () => uid })
const rootRef = ref<HTMLElement | null>(null)
const panelRef = ref<HTMLElement | null>(null)
const panelStyle = ref<Record<string, string>>({})
const panelOpen = ref(false)
const badgeText = computed(() => formatUnreadBadge(badgeCount.value))
const unreadChipText = computed(() => {
const count = unreadGroupCount.value
return count > 99 ? '99+ 组未读' : `${count} 组未读`
})
/** 模板里仍是 startsNewDay(index):组序列在面板层,这里只补一次取值。 */
function startsNewDay(index: number): boolean {
return groupStartsNewDay(groups.value, index)
}
function formatTime(value: string | null) {
return formatNotificationTime(value)
}
/** 面板挂到 body 后用 fixed 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
const PANEL_WIDTH = 376
function syncPanelPosition() {
const trigger = rootRef.value
if (!trigger) return
const rect = trigger.getBoundingClientRect()
// 窗口过窄时右对齐会把面板顶出左边界,这里把 right 收回来保证整块可见
const panelWidth = Math.min(PANEL_WIDTH, window.innerWidth - 24)
const maxRight = Math.max(8, window.innerWidth - panelWidth - 8)
const right = Math.min(Math.max(8, Math.round(window.innerWidth - rect.right)), maxRight)
panelStyle.value = {
top: `${Math.round(rect.bottom + 10)}px`,
right: `${right}px`,
}
}
function togglePanel() {
panelOpen.value = !panelOpen.value
if (panelOpen.value) {
syncPanelPosition()
reload()
}
}
/** 点击组件外部关闭面板(面板已 Teleport 到 body,需连同面板自身一起判断)。 */
function onDocumentMouseDown(event: MouseEvent) {
if (!panelOpen.value) return
const target = event.target
if (!(target instanceof Node)) return
if (rootRef.value?.contains(target) || panelRef.value?.contains(target)) return
// 日期选择面板同样挂在 body 上(el-popper),点它不应关闭通知面板
if (target instanceof Element && target.closest('.el-popper')) return
panelOpen.value = false
}
/** 窗口尺寸变化时重新对齐面板。 */
function onWindowResize() {
if (panelOpen.value) {
syncPanelPosition()
}
}
/** 页面回到前台时立即刷新一次未读数。 */
function onVisibilityChange() {
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
refreshSummary()
}
}
let pollTimer: number | null = null
onMounted(() => {
document.addEventListener('mousedown', onDocumentMouseDown)
document.addEventListener('visibilitychange', onVisibilityChange)
window.addEventListener('resize', onWindowResize)
refreshSummary()
pollTimer = window.setInterval(() => {
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
return
}
refreshSummary()
}, NOTIFICATION_POLL_INTERVAL_MS)
})
onUnmounted(() => {
document.removeEventListener('mousedown', onDocumentMouseDown)
document.removeEventListener('visibilitychange', onVisibilityChange)
window.removeEventListener('resize', onWindowResize)
if (pollTimer != null) {
window.clearInterval(pollTimer)
pollTimer = null
}
})
</script>
<style scoped src="./notification-bell.css"></style>
<style src="./notification-bell-popover.css"></style>