OperationsKit.tsx 10 KB

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