OperationsKit.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { useEffect, useRef, useState, type ReactNode } from "react";
  2. import { createPortal } from "react-dom";
  3. import { Check, ChevronDown, ChevronUp, X } from "lucide-react";
  4. import { Button } from "./ui/button";
  5. import { FieldHint } from "./ui/field-hint";
  6. import type { StatusTone } from "../domain/statuses";
  7. export type OpsTone = StatusTone | "brand";
  8. /** 管理页通用右侧抽屉;视觉与工单/每日任务页保持一致。wide=66% 宽(册10 执行记录抽屉契约)。 */
  9. export function OpsDrawer({ title, subtitle, onClose, wide = false, children }: { title: string; subtitle: string; onClose: () => void; wide?: boolean; children: ReactNode }) {
  10. const ref = useRef<HTMLDialogElement>(null);
  11. useEffect(() => {
  12. const dialog = ref.current;
  13. if (!dialog) return;
  14. const previous = document.activeElement as HTMLElement | null;
  15. const overflow = document.body.style.overflow;
  16. document.body.style.overflow = "hidden";
  17. dialog.showModal();
  18. return () => { dialog.close(); document.body.style.overflow = overflow; previous?.focus(); };
  19. }, []);
  20. return <dialog ref={ref} className={`ops-drawer${wide ? " ops-drawer--wide" : ""}`} aria-labelledby="ops-drawer-title" onCancel={onClose} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}>
  21. <header><div><p>{subtitle}</p><h2 id="ops-drawer-title">{title}</h2></div><Button variant="ghost" size="icon" aria-label="关闭抽屉" onClick={onClose}><X size={19} /></Button></header>
  22. {children}
  23. </dialog>;
  24. }
  25. /** 状态徽章:颜色只表达状态,文字始终保留。 */
  26. export function OpsStatus({ tone, children }: { tone: OpsTone; children: ReactNode }) {
  27. return <span className={`ops-status status-${tone}`}><i />{children}</span>;
  28. }
  29. /** 分类小标签。 */
  30. export function OpsTag({ tone, children }: { tone: OpsTone; children: ReactNode }) {
  31. return <span className={`ops-tag tone-${tone}`}>{children}</span>;
  32. }
  33. export function OpsTableEmpty({ colSpan, children }: { colSpan: number; children: ReactNode }) {
  34. return <tr><td className="ops-table-empty-cell" colSpan={colSpan}>
  35. <div className="ops-table-empty-message">{children}</div>
  36. </td></tr>;
  37. }
  38. /** 保留分配比例,由浏览器按表格的实际宽度处理小数像素。 */
  39. export function OpsTableColumns({ widths }: { widths: readonly number[] }) {
  40. const total = widths.reduce((sum, width) => sum + width, 0);
  41. return <colgroup>{widths.map((width, index) => <col key={index} style={{ width: `${width / total * 100}%` }} />)}</colgroup>;
  42. }
  43. /**
  44. * 字段口径问号:与编辑项标题后的问号同一套交互({@link FieldHint})——
  45. * 鼠标移入或点击显示、移出/失焦/Esc 收起;浮层走 body 传送门+fixed,弹窗与台账的 overflow 容器不会裁掉它。
  46. * ⚠️ 放进 `<label>` 里点图标会连带切换勾选态 ⇒ 由调用方把图标摆在 label 之外(`.ops-form-check-row`)。
  47. */
  48. export function OpsHint({ label, title, children }: { label: string; title: string; children: ReactNode }) {
  49. return <FieldHint label={label} title={title}>{children}</FieldHint>;
  50. }
  51. /**
  52. * 成功提示条的停留时长:与原型 `.toast` 一致(约 2.6s 自动消失),测试手册 §1.4 按此口径取证。
  53. * ⛔ 挂着不走等用户点「关闭」——保存后注意力已经转向结果,条子会一直压在页面底部。
  54. */
  55. export const NOTICE_DISMISS_MS = 2600;
  56. /** 页面底部轻提示,用于保存成功等操作的反馈:到时自动消失,也可手动关闭。 */
  57. export function OpsNotice({ message, onClose, duration = NOTICE_DISMISS_MS }: { message: string; onClose: () => void; duration?: number }) {
  58. const [visible, setVisible] = useState(true);
  59. // 父级每次渲染都传新的箭头函数 ⇒ 关回调放 ref,⛔ 让它进依赖把计时器反复重置。
  60. const closeRef = useRef(onClose);
  61. closeRef.current = onClose;
  62. useEffect(() => {
  63. // 同一实例换了下一条提示(连续保存)⇒ 重新出现并重新计时。
  64. setVisible(true);
  65. const timer = window.setTimeout(() => { setVisible(false); closeRef.current(); }, duration);
  66. return () => window.clearTimeout(timer);
  67. }, [message, duration]);
  68. if (!visible) return null;
  69. return <div className="ops-notice" role="status"><Check size={17} />{message}<button type="button" aria-label="关闭提示" onClick={() => { setVisible(false); closeRef.current(); }}><X size={15} /></button></div>;
  70. }
  71. export type OpsMoreItem = { label: string; icon: ReactNode; onSelect: () => void; disabled?: boolean; title?: string };
  72. /** 主操作之外只有一项时直接展示;多项才按可用空间收纳。 */
  73. export function OpsResponsiveActions({ expanded, items }: { expanded: boolean; items: (OpsMoreItem & { shortLabel?: string; danger?: boolean })[] }) {
  74. if (!expanded && items.length > 1) return <OpsMore items={items} />;
  75. return <>{items.map((item) => <button key={item.label} type="button" className={item.danger ? "is-danger" : undefined} disabled={item.disabled} title={item.title} onClick={(event) => { event.stopPropagation(); item.onSelect(); }}>{item.icon}{item.shortLabel ?? item.label}</button>)}</>;
  76. }
  77. /**
  78. * 全页「更多」菜单的登记册:同一时刻只留一个打开。
  79. *
  80. * 平时靠 `pointerdown` 的 outside 判据关旧的即可,但脚本点击、辅助技术、部分触摸环境
  81. * 只派发 `click` 不派发 `pointerdown` ⇒ 旧菜单会留在 DOM 里叠成一摞。
  82. * 这里改成「打开新的先关旧的」,与事件来源无关。
  83. */
  84. const menuClosers = new Set<(open: boolean) => void>();
  85. /**
  86. * 操作列的「更多」悬停菜单:鼠标移入按钮弹出溢出动作项,portal 渲染避免被表格滚动容器裁剪。
  87. *
  88. * `placeholder`:本行暂时没有溢出动作(如订阅已到期只剩「详情」)时,占一个和「更多」等宽的
  89. * 不可见空位——操作列按行自适应宽度,缺了它同一列里「详情」就会左右错位(业主 2026-11-16)。
  90. */
  91. export function OpsMore({ items, label = "更多", placeholder = false }: { items: OpsMoreItem[]; label?: string; placeholder?: boolean }) {
  92. const [open, setOpen] = useState(false);
  93. const [pos, setPos] = useState({ top: 0, right: 0 });
  94. const btnRef = useRef<HTMLButtonElement>(null);
  95. const menuRef = useRef<HTMLDivElement>(null);
  96. const timer = useRef<number | undefined>(undefined);
  97. /** `setOpen` 的引用在实例生命周期内稳定 ⇒ 用它当本实例在登记册里的身份。 */
  98. const identity = useRef(setOpen);
  99. useEffect(() => {
  100. const mine = identity.current;
  101. menuClosers.add(mine);
  102. return () => { menuClosers.delete(mine); };
  103. }, []);
  104. function openMenu() {
  105. window.clearTimeout(timer.current);
  106. menuClosers.forEach((closer) => { if (closer !== identity.current) closer(false); });
  107. const rect = btnRef.current?.getBoundingClientRect();
  108. if (rect) setPos({ top: rect.bottom + 4, right: Math.max(8, window.innerWidth - rect.right) });
  109. setOpen(true);
  110. }
  111. function scheduleClose() { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(false), 120); }
  112. function cancelClose() { window.clearTimeout(timer.current); }
  113. useEffect(() => {
  114. if (!open) return;
  115. const close = () => setOpen(false);
  116. const outside = (event: PointerEvent) => { if (!btnRef.current?.contains(event.target as Node) && !menuRef.current?.contains(event.target as Node)) close(); };
  117. const escape = (event: KeyboardEvent) => { if (event.key === "Escape") { close(); btnRef.current?.focus(); } };
  118. document.addEventListener("pointerdown", outside);
  119. document.addEventListener("keydown", escape);
  120. window.addEventListener("scroll", close, true);
  121. window.addEventListener("resize", close);
  122. return () => { window.removeEventListener("scroll", close, true); window.removeEventListener("resize", close); document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", escape); };
  123. }, [open]);
  124. useEffect(() => () => window.clearTimeout(timer.current), []);
  125. if (!items.length) {
  126. // 等宽空位:把「更多」的按钮原样画出来再隐藏,宽度自然与有菜单的行一致(⛔ 写死 px)。
  127. return placeholder
  128. ? <span className="ops-more ops-more-slot" aria-hidden="true"><button type="button" tabIndex={-1} disabled>{label}<ChevronDown size={15} /></button></span>
  129. : null;
  130. }
  131. return <>
  132. <span className="ops-more" onMouseEnter={openMenu} onMouseLeave={scheduleClose}>
  133. <button ref={btnRef} type="button" aria-haspopup="menu" aria-expanded={open} onClick={(event) => { event.stopPropagation(); openMenu(); }} onFocus={cancelClose} onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault(); openMenu(); requestAnimationFrame(() => menuRef.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus()); } }}>{label}{open ? <ChevronUp size={15} /> : <ChevronDown size={15} />}</button>
  134. </span>
  135. {open && createPortal(
  136. <div ref={menuRef} className="ops-more-menu" role="menu" style={{ top: pos.top, right: pos.right }} onMouseEnter={cancelClose} onMouseLeave={scheduleClose} onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node)) setOpen(false); }}>
  137. {items.map((item) => <button key={item.label} type="button" role="menuitem" disabled={item.disabled} title={item.title} onClick={(event) => { event.stopPropagation(); setOpen(false); item.onSelect(); }}>{item.icon}{item.label}</button>)}
  138. </div>, document.body)}
  139. </>;
  140. }