Elffuss BraidHub

kikocis/utopia public

dev · 10.0 KiBRawPermalink
1// 顶栏告警(0005):铃铛 + 未读角标 + 弹出面板。
2//
3// **弹窗不是页面**:告警是"顺手瞄一眼"的东西,不是一个要专门去逛的地方。
4// 做成页面会逼人离开手头的事,而离开的代价就是没人去看。
5//
6// 一条告警 = 一次故障,写完不再变,没有"已解决"。
7// 「已读」逐人——一个人读过不代表别人也该从未读里消失。
8import { type Ref, useEffect, useState } from "react";
9import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
10import { Bell, Search, X } from "lucide-react";
11
12import { api, type AlertGroup } from "../api";
13import { S } from "../i18n";
14import { Chip, Pager, cn } from "../ui";
15import { usePopoverFlip } from "../ui/popoverFlip";
16
17const PAGE = 8;
18
19/** 明细里给人看的那一行:对象名 — 报错原文 */
20function line(d: AlertGroup["lines"][number]): string | null {
21 const parts = [d.name ?? d.job, d.error].filter(Boolean);
22 return parts.length ? parts.join(" — ") : null;
23}
24
25function AlertRow({
26 g,
27 onRead,
28}: {
29 g: AlertGroup;
30 onRead: (g: AlertGroup) => void;
31}) {
32 // 没见过的 kind 也得显示得出来:新告警源上线时前端可能还没跟上,
33 // 而"有条告警但我不认识它"远好过"什么都不显示"
34 const worded = S.alerts.kinds[g.kind];
35 const lines = g.lines.map(line).filter((l): l is string => !!l);
36 // count 数的是整组,lines 只带回前几条——差额是"还有 N 条"
37 const rest = g.count - lines.length;
38 return (
39 <button
40 type="button"
41 // **点击才算读过**,不是划过。鼠标经过一列告警不代表看过它们,
42 // 而已读一旦落下就再也不会自己回来。点一下把这一组整个标掉
43 onClick={() => {
44 if (g.unread > 0) onRead(g);
45 }}
46 className="w-full text-left flex gap-2.5 px-3.5 py-3 border-b border-white/[0.06] last:border-b-0 hover:bg-white/[0.03] transition-colors"
47 >
48 {/* 未读就是一个红点。整行描边或底色会让面板在告警多时变成一片红,
49 而红点只占它该占的那一点地方,读过就没了 */}
50 <span
51 className={cn(
52 "mt-[7px] h-1.5 w-1.5 rounded-full shrink-0",
53 g.unread > 0 ? "bg-rose-500" : "bg-transparent",
54 )}
55 />
56 <div className="min-w-0 flex-1">
57 <div className="flex items-center gap-1.5 flex-wrap">
58 <span
59 className={cn(
60 "text-[13px]",
61 g.unread > 0 ? "font-medium text-white" : "text-neutral-400",
62 )}
63 >
64 {worded?.title ?? S.alerts.unknownKind(g.kind)}
65 </span>
66 {g.count > 1 && <Chip tone="neutral">{g.count}</Chip>}
67 <Chip tone={g.kb_name ? "neutral" : "violet"}>
68 {g.kb_name ?? S.alerts.system}
69 </Chip>
70 </div>
71 {worded && (
72 <p className="mt-0.5 text-[11.5px] text-neutral-500">{worded.hint}</p>
73 )}
74 {lines.length > 0 && (
75 <ul className="mt-1 space-y-0.5">
76 {lines.map((l, i) => (
77 <li key={i} className="text-[11px] text-neutral-400 break-words">
78 {l}
79 </li>
80 ))}
81 {rest > 0 && (
82 <li className="text-[11px] text-neutral-600">
83 {S.alerts.andMore(rest)}
84 </li>
85 )}
86 </ul>
87 )}
88 {/* 时间取组里最新的那一次 */}
89 <p className="u-num mt-1.5 text-[10.5px] text-neutral-600">
90 {new Date(g.latest_at).toLocaleString()}
91 </p>
92 </div>
93 </button>
94 );
95}
96
97function Panel({ panelRef }: { panelRef: Ref<HTMLDivElement> }) {
98 const [q, setQ] = useState("");
99 const [page, setPage] = useState(0);
100 const qc = useQueryClient();
101
102 // 搜索后回第一页:停在第 4 页看一个只有 2 页的结果,
103 // 面板会显示空白,而人会读成"没有告警"
104 useEffect(() => {
105 setPage(0);
106 }, [q]);
107
108 const list = useQuery({
109 queryKey: ["alerts", "list", q, page],
110 queryFn: () => api.alerts({ q, limit: PAGE, offset: page * PAGE }),
111 // 翻页时留着上一页,免得面板高度塌一下再弹回来
112 placeholderData: (prev) => prev,
113 });
114
115 const read = useMutation({
116 mutationFn: (g: AlertGroup) =>
117 api.alertReadGroup({
118 kb_id: g.kb_id,
119 kind: g.kind,
120 from: g.earliest_at,
121 to: g.latest_at,
122 }),
123 onSuccess: () => qc.invalidateQueries({ queryKey: ["alerts"] }),
124 });
125 const readAll = useMutation({
126 mutationFn: () => api.alertsReadAll(),
127 onSuccess: () => qc.invalidateQueries({ queryKey: ["alerts"] }),
128 });
129
130 const groups = list.data?.items ?? [];
131 const total = list.data?.total ?? 0;
132
133 return (
134 // top-0 而不是 top-9:面板要从铃铛**原位**长出来,右上角对齐
135 <div
136 ref={panelRef}
137 className="u-menu-glass absolute right-0 top-0 w-[420px] rounded-xl shadow-2xl z-50 overflow-hidden"
138 >
139 <div className="flex items-center gap-2 pl-3.5 pr-10 py-2.5 border-b border-white/10">
140 <span className="text-[13px] font-medium text-neutral-100">
141 {S.alerts.title}
142 </span>
143 </div>
144
145 {/* 跟文库的过滤框同一套:input-dark + 左侧图标 + 有值时右侧清除、Esc 清空 */}
146 <div className="px-3.5 py-2.5 border-b border-white/[0.06]">
147 <div className="relative">
148 <Search
149 size={13}
150 className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
151 />
152 <input
153 className="input-dark w-full pl-8 pr-7 py-1.5 text-[13px]"
154 placeholder={S.alerts.searchPlaceholder}
155 value={q}
156 onChange={(e) => setQ(e.target.value)}
157 onKeyDown={(e) => e.key === "Escape" && setQ("")}
158 />
159 {q && (
160 <button
161 onClick={() => setQ("")}
162 className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-neutral-200"
163 >
164 <X size={12} />
165 </button>
166 )}
167 </div>
168 </div>
169
170 <div className="max-h-[420px] overflow-y-auto">
171 {groups.length === 0 ? (
172 <div className="px-3.5 py-8 text-center">
173 <p className="text-[13px] text-neutral-300">
174 {q ? S.alerts.noMatch : S.alerts.empty}
175 </p>
176 {!q && (
177 <p className="mt-1 text-[11.5px] text-neutral-500">
178 {S.alerts.emptyHint}
179 </p>
180 )}
181 </div>
182 ) : (
183 groups.map((g) => (
184 <AlertRow
185 key={`${g.kb_id ?? "system"}|${g.kind}|${g.latest_at}`}
186 g={g}
187 onRead={(x) => read.mutate(x)}
188 />
189 ))
190 )}
191 </div>
192
193 {/* 底栏:整张列表级的动作跟翻页放一起,离光标最远 */}
194 {groups.length > 0 && (
195 <div className="flex items-center gap-3 px-3.5 py-2 border-t border-white/[0.06]">
196 {groups.some((g) => g.unread > 0) && (
197 <button
198 className="text-[11.5px] text-neutral-500 hover:text-neutral-200 transition-colors"
199 onClick={() => readAll.mutate()}
200 >
201 {S.alerts.markAllRead}
202 </button>
203 )}
204 <Pager
205 className="ml-auto"
206 total={total}
207 pageSize={PAGE}
208 page={page}
209 onPage={setPage}
210 />
211 </div>
212 )}
213 </div>
214 );
215}
216
217export function AlertBell() {
218 // 跟用户菜单同一份原地变形:两个面板紧挨着,动画差一点点来回点两下就看得出来
219 const { open, setOpen, close, rootRef, anchorRef, panelRef } =
220 usePopoverFlip<HTMLButtonElement, HTMLDivElement>();
221 const unread = useQuery({
222 queryKey: ["alerts", "unread"],
223 queryFn: () => api.alertsUnread(),
224 // 推送是主路,这个只是断流时的兜底
225 refetchInterval: 120_000,
226 });
227 const n = unread.data?.unread ?? 0;
228
229 return (
230 <div ref={rootRef} className="relative">
231 <button
232 ref={anchorRef}
233 onClick={() => (open ? close() : setOpen(true))}
234 title={S.alerts.badgeLabel}
235 aria-label={S.alerts.badgeLabel}
236 aria-expanded={open}
237 // h-7 w-7 正方形:只装一个图标的按钮不该是长方形。
238 // 关闭按钮用同一组尺寸绝对定位在面板的 right-0 top-0,两者严丝合缝
239 className={cn(
240 "relative grid h-7 w-7 place-items-center rounded-lg transition-colors",
241 open
242 ? "text-neutral-200 bg-white/[0.06]"
243 : "text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05]",
244 )}
245 >
246 <Bell size={15} />
247 {/* 角标也是个点,不是数字。"有事没看"是二元的,具体几条打开就知道;
248 数字还会随重试一路往上跳,跳到三位数就把铃铛撑变形了 */}
249 {n > 0 && (
250 <span className="absolute top-1 right-1 h-1.5 w-1.5 rounded-full bg-rose-500" />
251 )}
252 </button>
253 {open && (
254 <>
255 <Panel panelRef={panelRef} />
256 {/* 关闭按钮是面板的**兄弟**,不是它的孩子:放里面的话 `right-0 top-0`
257 相对的是面板的内边距盒,而 u-menu-glass 有一条 0.667px 的发丝边框
258 (DPR 1.5 上的一个物理像素),永远差那么一点。放在这里,定位祖先
259 就是裹着铃铛的这个 div,跟铃铛同一个盒子——重合是构造出来的。
260
261 光标点开面板之后正停在这个位置,所以这儿必须是"再点一下关掉"。
262 放"全部标为已读"等于把误触做成默认动作,而它一下清掉的是
263 所有库的所有告警 */}
264 <button
265 onClick={close}
266 title={S.alerts.close}
267 aria-label={S.alerts.close}
268 className="absolute right-0 top-0 z-[60] grid h-7 w-7 place-items-center rounded-lg text-neutral-500 hover:text-neutral-200 transition-colors"
269 >
270 <X size={15} />
271 </button>
272 </>
273 )}
274 </div>
275 );
276}