| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153 |
- import { useEffect, useRef, useState, type ReactNode } from "react";
- import { createPortal } from "react-dom";
- import { Check, ChevronDown, ChevronUp, X } from "lucide-react";
- import { Button } from "./ui/button";
- import { FieldHint } from "./ui/field-hint";
- import type { StatusTone } from "../domain/statuses";
- export type OpsTone = StatusTone | "brand";
- /** 管理页通用右侧抽屉;视觉与工单/每日任务页保持一致。wide=66% 宽(册10 执行记录抽屉契约)。 */
- export function OpsDrawer({ title, subtitle, onClose, wide = false, children }: { title: string; subtitle: string; onClose: () => void; wide?: boolean; children: ReactNode }) {
- const ref = useRef<HTMLDialogElement>(null);
- useEffect(() => {
- const dialog = ref.current;
- if (!dialog) return;
- const previous = document.activeElement as HTMLElement | null;
- const overflow = document.body.style.overflow;
- document.body.style.overflow = "hidden";
- dialog.showModal();
- return () => { dialog.close(); document.body.style.overflow = overflow; previous?.focus(); };
- }, []);
- 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(); }}>
- <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>
- {children}
- </dialog>;
- }
- /** 状态徽章:颜色只表达状态,文字始终保留。 */
- export function OpsStatus({ tone, children }: { tone: OpsTone; children: ReactNode }) {
- return <span className={`ops-status status-${tone}`}><i />{children}</span>;
- }
- /** 分类小标签。 */
- export function OpsTag({ tone, children }: { tone: OpsTone; children: ReactNode }) {
- return <span className={`ops-tag tone-${tone}`}>{children}</span>;
- }
- export function OpsTableEmpty({ colSpan, children }: { colSpan: number; children: ReactNode }) {
- return <tr><td className="ops-table-empty-cell" colSpan={colSpan}>
- <div className="ops-table-empty-message">{children}</div>
- </td></tr>;
- }
- /** 保留分配比例,由浏览器按表格的实际宽度处理小数像素。 */
- export function OpsTableColumns({ widths }: { widths: readonly number[] }) {
- const total = widths.reduce((sum, width) => sum + width, 0);
- return <colgroup>{widths.map((width, index) => <col key={index} style={{ width: `${width / total * 100}%` }} />)}</colgroup>;
- }
- /**
- * 字段口径问号:与编辑项标题后的问号同一套交互({@link FieldHint})——
- * 鼠标移入或点击显示、移出/失焦/Esc 收起;浮层走 body 传送门+fixed,弹窗与台账的 overflow 容器不会裁掉它。
- * ⚠️ 放进 `<label>` 里点图标会连带切换勾选态 ⇒ 由调用方把图标摆在 label 之外(`.ops-form-check-row`)。
- */
- export function OpsHint({ label, title, children }: { label: string; title: string; children: ReactNode }) {
- return <FieldHint label={label} title={title}>{children}</FieldHint>;
- }
- /**
- * 成功提示条的停留时长:与原型 `.toast` 一致(约 2.6s 自动消失),测试手册 §1.4 按此口径取证。
- * ⛔ 挂着不走等用户点「关闭」——保存后注意力已经转向结果,条子会一直压在页面底部。
- */
- export const NOTICE_DISMISS_MS = 2600;
- /** 页面底部轻提示,用于保存成功等操作的反馈:到时自动消失,也可手动关闭。 */
- export function OpsNotice({ message, onClose, duration = NOTICE_DISMISS_MS }: { message: string; onClose: () => void; duration?: number }) {
- const [visible, setVisible] = useState(true);
- // 父级每次渲染都传新的箭头函数 ⇒ 关回调放 ref,⛔ 让它进依赖把计时器反复重置。
- const closeRef = useRef(onClose);
- closeRef.current = onClose;
- useEffect(() => {
- // 同一实例换了下一条提示(连续保存)⇒ 重新出现并重新计时。
- setVisible(true);
- const timer = window.setTimeout(() => { setVisible(false); closeRef.current(); }, duration);
- return () => window.clearTimeout(timer);
- }, [message, duration]);
- if (!visible) return null;
- 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>;
- }
- export type OpsMoreItem = { label: string; icon: ReactNode; onSelect: () => void; disabled?: boolean; title?: string };
- /** 主操作之外只有一项时直接展示;多项才按可用空间收纳。 */
- export function OpsResponsiveActions({ expanded, items }: { expanded: boolean; items: (OpsMoreItem & { shortLabel?: string; danger?: boolean })[] }) {
- if (!expanded && items.length > 1) return <OpsMore items={items} />;
- 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>)}</>;
- }
- /**
- * 全页「更多」菜单的登记册:同一时刻只留一个打开。
- *
- * 平时靠 `pointerdown` 的 outside 判据关旧的即可,但脚本点击、辅助技术、部分触摸环境
- * 只派发 `click` 不派发 `pointerdown` ⇒ 旧菜单会留在 DOM 里叠成一摞。
- * 这里改成「打开新的先关旧的」,与事件来源无关。
- */
- const menuClosers = new Set<(open: boolean) => void>();
- /**
- * 操作列的「更多」悬停菜单:鼠标移入按钮弹出溢出动作项,portal 渲染避免被表格滚动容器裁剪。
- *
- * `placeholder`:本行暂时没有溢出动作(如订阅已到期只剩「详情」)时,占一个和「更多」等宽的
- * 不可见空位——操作列按行自适应宽度,缺了它同一列里「详情」就会左右错位(业主 2026-11-16)。
- */
- export function OpsMore({ items, label = "更多", placeholder = false }: { items: OpsMoreItem[]; label?: string; placeholder?: boolean }) {
- const [open, setOpen] = useState(false);
- const [pos, setPos] = useState({ top: 0, right: 0 });
- const btnRef = useRef<HTMLButtonElement>(null);
- const menuRef = useRef<HTMLDivElement>(null);
- const timer = useRef<number | undefined>(undefined);
- /** `setOpen` 的引用在实例生命周期内稳定 ⇒ 用它当本实例在登记册里的身份。 */
- const identity = useRef(setOpen);
- useEffect(() => {
- const mine = identity.current;
- menuClosers.add(mine);
- return () => { menuClosers.delete(mine); };
- }, []);
- function openMenu() {
- window.clearTimeout(timer.current);
- menuClosers.forEach((closer) => { if (closer !== identity.current) closer(false); });
- const rect = btnRef.current?.getBoundingClientRect();
- if (rect) setPos({ top: rect.bottom + 4, right: Math.max(8, window.innerWidth - rect.right) });
- setOpen(true);
- }
- function scheduleClose() { window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setOpen(false), 120); }
- function cancelClose() { window.clearTimeout(timer.current); }
- useEffect(() => {
- if (!open) return;
- const close = () => setOpen(false);
- const outside = (event: PointerEvent) => { if (!btnRef.current?.contains(event.target as Node) && !menuRef.current?.contains(event.target as Node)) close(); };
- const escape = (event: KeyboardEvent) => { if (event.key === "Escape") { close(); btnRef.current?.focus(); } };
- document.addEventListener("pointerdown", outside);
- document.addEventListener("keydown", escape);
- window.addEventListener("scroll", close, true);
- window.addEventListener("resize", close);
- return () => { window.removeEventListener("scroll", close, true); window.removeEventListener("resize", close); document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", escape); };
- }, [open]);
- useEffect(() => () => window.clearTimeout(timer.current), []);
- if (!items.length) {
- // 等宽空位:把「更多」的按钮原样画出来再隐藏,宽度自然与有菜单的行一致(⛔ 写死 px)。
- return placeholder
- ? <span className="ops-more ops-more-slot" aria-hidden="true"><button type="button" tabIndex={-1} disabled>{label}<ChevronDown size={15} /></button></span>
- : null;
- }
- return <>
- <span className="ops-more" onMouseEnter={openMenu} onMouseLeave={scheduleClose}>
- <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>
- </span>
- {open && createPortal(
- <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); }}>
- {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>)}
- </div>, document.body)}
- </>;
- }
|