HeaderMenus.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { useEffect, useRef, useState } from "react";
  2. import { Bell, ChevronDown, LogOut, UserRound } from "lucide-react";
  3. import { useLocation } from "react-router";
  4. import { clearSessionQueries } from "../../lib/api/query-client";
  5. import { getToken } from "../../lib/api/http";
  6. import { logout as platformLogout } from "../../lib/api/platform";
  7. import { Button } from "../ui/button";
  8. import { cn } from "../../lib/utils";
  9. import { useDemoAccount, useDemoIdentity } from "../../lib/demo-session";
  10. import { useSession } from "../../auth/session";
  11. import { useProfileOverlay } from "./ProfileOverlay";
  12. import { InboxPanel } from "./InboxPanel";
  13. import { inboxUnreadCount } from "../../lib/api/inbox";
  14. type OpenMenu = "messages" | "user" | null;
  15. export function HeaderMenus() {
  16. const accountName = useDemoAccount() ?? "未登录";
  17. const identity = useDemoIdentity();
  18. const { signOut } = useSession();
  19. const [openMenu, setOpenMenu] = useState<OpenMenu>(null);
  20. const [unread, setUnread] = useState(0);
  21. const [confirmingExit, setConfirmingExit] = useState(false);
  22. const [exiting, setExiting] = useState(false);
  23. const rootRef = useRef<HTMLDivElement>(null);
  24. const messageButtonRef = useRef<HTMLButtonElement>(null);
  25. const userButtonRef = useRef<HTMLButtonElement>(null);
  26. const location = useLocation();
  27. const { openProfile } = useProfileOverlay();
  28. useEffect(() => setOpenMenu(null), [location.pathname]);
  29. /**
  30. * 提醒箱可用角色=后端 `bos.inbox.*` 的授出面:总运营/运营主账号/运营子账号/运维团队长。
  31. * 客户(主/分账号)、合伙人、运营商、运维成员**没有**这把键 ⇒ 请求必回 `11001`。
  32. * 2026-11-18 巡检:无键角色每页仍发 1–6 次 `inbox/list`(101 页共 114 次 11001)。
  33. * ⛔ 靠「失败就吞掉」兜底——那是把授权缺失当网络抖动;这里直接**不请求、不渲染**入口。
  34. */
  35. const canUseInbox = identity?.role === "admin" || identity?.role === "regAdmin" || identity?.role === "teamLead";
  36. /**
  37. * 未读徽标:SPA 壳常驻,⛔ 绑路由切页。
  38. * 取数节奏=登录/身份就绪后一次 + 页签回到前台 + 低频定时;开面板时 InboxPanel 再拉列表并回写。
  39. * 无权角色不发请求(⛔ 顶栏报错)。
  40. */
  41. useEffect(() => {
  42. if (!canUseInbox) {
  43. setUnread(0);
  44. return;
  45. }
  46. let cancelled = false;
  47. const refresh = () => {
  48. void inboxUnreadCount().then((n) => {
  49. if (!cancelled) setUnread(n);
  50. });
  51. };
  52. refresh();
  53. const onVisible = () => {
  54. if (document.visibilityState === "visible") refresh();
  55. };
  56. document.addEventListener("visibilitychange", onVisible);
  57. window.addEventListener("focus", refresh);
  58. const timer = window.setInterval(refresh, 120_000);
  59. return () => {
  60. cancelled = true;
  61. document.removeEventListener("visibilitychange", onVisible);
  62. window.removeEventListener("focus", refresh);
  63. window.clearInterval(timer);
  64. };
  65. }, [identity?.id, canUseInbox]);
  66. useEffect(() => {
  67. if (!openMenu) return;
  68. const handleOutsideClick = (event: PointerEvent) => {
  69. if (!rootRef.current?.contains(event.target as Node)) setOpenMenu(null);
  70. };
  71. const handleEscape = (event: KeyboardEvent) => {
  72. if (event.key !== "Escape") return;
  73. setOpenMenu(null);
  74. (openMenu === "messages" ? messageButtonRef : userButtonRef).current?.focus();
  75. };
  76. document.addEventListener("pointerdown", handleOutsideClick);
  77. document.addEventListener("keydown", handleEscape);
  78. return () => {
  79. document.removeEventListener("pointerdown", handleOutsideClick);
  80. document.removeEventListener("keydown", handleEscape);
  81. };
  82. }, [openMenu]);
  83. /** AC-17:先二次确认,再调平台 `POST /auth/logout@v1`,最后清本地凭证回登录页。 */
  84. const confirmExit = async () => {
  85. if (exiting) return;
  86. setExiting(true);
  87. const token = getToken();
  88. if (token) await platformLogout(token);
  89. setConfirmingExit(false);
  90. setExiting(false);
  91. clearSessionQueries();
  92. signOut();
  93. };
  94. const menuItemClass = "flex w-full cursor-pointer items-center gap-3 rounded-md px-3 py-2.5 text-left text-sm text-foreground transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
  95. return (
  96. <div ref={rootRef} className="ml-auto flex shrink-0 items-center gap-2 sm:gap-3">
  97. <div className="hidden items-center gap-2 border-r border-border pr-4 text-xs text-muted-foreground sm:flex">
  98. <span aria-hidden="true" className="size-1.5 rounded-full bg-primary" />
  99. <span>开发环境</span>
  100. </div>
  101. {canUseInbox && <div className="relative">
  102. <button
  103. ref={messageButtonRef}
  104. aria-controls="header-message-panel"
  105. aria-expanded={openMenu === "messages"}
  106. aria-haspopup="dialog"
  107. aria-label="消息"
  108. className={cn("grid size-9 cursor-pointer place-items-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", openMenu === "messages" && "bg-accent text-foreground")}
  109. onClick={() => setOpenMenu((current) => current === "messages" ? null : "messages")}
  110. title="消息"
  111. type="button"
  112. >
  113. <Bell aria-hidden="true" size={18} strokeWidth={1.8} />
  114. {unread > 0 && (
  115. <span aria-hidden="true" className="absolute right-1 top-1 grid min-w-[15px] place-items-center rounded-full bg-destructive px-1 text-[10px] font-semibold leading-[15px] text-destructive-foreground">
  116. {unread > 99 ? "99+" : unread}
  117. </span>
  118. )}
  119. {unread > 0 && <span className="sr-only">,{unread} 条未读</span>}
  120. </button>
  121. {openMenu === "messages" && (
  122. <div
  123. id="header-message-panel"
  124. aria-label="消息菜单"
  125. className="absolute right-0 top-[calc(100%+12px)] z-50 w-[min(360px,calc(100vw-32px))] rounded-lg border border-border bg-card p-4 text-card-foreground shadow-[var(--shadow-panel)]"
  126. role="dialog"
  127. >
  128. <InboxPanel onUnreadChange={setUnread} />
  129. </div>
  130. )}
  131. </div>}
  132. <div className="relative">
  133. <button
  134. ref={userButtonRef}
  135. aria-controls="header-user-panel"
  136. aria-expanded={openMenu === "user"}
  137. aria-haspopup="menu"
  138. aria-label={`用户菜单:${accountName}`}
  139. className={cn("flex h-9 cursor-pointer items-center gap-2 rounded-md px-1.5 text-sm text-foreground transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:px-2", openMenu === "user" && "bg-accent")}
  140. onClick={() => setOpenMenu((current) => current === "user" ? null : "user")}
  141. type="button"
  142. >
  143. <span className="grid size-7 shrink-0 place-items-center rounded-full bg-primary-soft text-primary"><UserRound aria-hidden="true" size={16} strokeWidth={1.8} /></span>
  144. <span className="hidden max-w-28 truncate font-medium sm:inline">{accountName}</span>
  145. <ChevronDown aria-hidden="true" className={cn("hidden text-muted-foreground transition-transform sm:block", openMenu === "user" && "rotate-180")} size={15} />
  146. </button>
  147. {openMenu === "user" && (
  148. <div
  149. id="header-user-panel"
  150. aria-label="用户菜单"
  151. className="absolute right-0 top-[calc(100%+12px)] z-50 w-56 rounded-lg border border-border bg-card p-1.5 text-card-foreground shadow-[var(--shadow-panel)]"
  152. role="menu"
  153. >
  154. <div className="border-b border-border px-3 py-2.5">
  155. <p className="truncate text-sm font-semibold">{accountName}</p>
  156. <p className="mt-0.5 text-xs leading-5 text-muted-foreground">{identity?.title ?? "未登录"}</p>
  157. </div>
  158. <div className="py-1">
  159. <button className={menuItemClass} onClick={() => { setOpenMenu(null); openProfile(); }} role="menuitem" type="button"><UserRound aria-hidden="true" size={16} />个人资料</button>
  160. </div>
  161. <div className="border-t border-border pt-1">
  162. <button className={cn(menuItemClass, "text-destructive hover:bg-destructive/10")} onClick={() => { setOpenMenu(null); setConfirmingExit(true); }} role="menuitem" type="button"><LogOut aria-hidden="true" size={16} />退出登录</button>
  163. </div>
  164. </div>
  165. )}
  166. </div>
  167. {confirmingExit && (
  168. <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" role="alertdialog" aria-modal="true" aria-labelledby="logout-confirm-title">
  169. <div className="w-[min(420px,100%)] rounded-lg border border-border bg-card p-5 shadow-[var(--shadow-panel)]">
  170. <h2 className="text-base font-semibold" id="logout-confirm-title">退出登录?</h2>
  171. <p className="mt-2 text-sm leading-6 text-muted-foreground">退出后需重新输入账号密码登录,未保存的编辑内容将丢失。</p>
  172. <div className="mt-5 flex justify-end gap-2">
  173. <Button disabled={exiting} onClick={() => setConfirmingExit(false)} variant="outline">取消</Button>
  174. <Button disabled={exiting} onClick={confirmExit} variant="destructive">{exiting ? "退出中…" : "确认退出"}</Button>
  175. </div>
  176. </div>
  177. </div>
  178. )}
  179. </div>
  180. );
  181. }