三个 settings 面板各手写同一套 flash-message 状态机(msg state + setTimeout 自动
消失 + 卸载清 timer)。global-config / notifications 是完整版(逐字相同);
system-panel 是退化版(无 timer ref、无 cleanup、rapid flash 累积 timer、卸载后可能
stale setMsg)。抽 useFlashMessage(durationMs=2400) → { msg, flash, setMsg }。
- global-config / notifications:迁移后行为不变(2400ms;flash 瞬时 + setMsg 持久
错误保留)。
- system-panel:保留 4000ms(useFlashMessage(4000)),顺带补上 prior-timer 取消 +
卸载 cleanup(修 timer 泄漏,现代 React 里无害的小改善)。
webui typecheck(tsc -b) + vite build 干净;对抗性 Agent 逐行核对确认 hook 等价、
两面板行为不变、无依赖/import 回归。
38 lines
1.4 KiB
TypeScript
38 lines
1.4 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
|
|
export type FlashKind = 'ok' | 'err';
|
|
export interface FlashMessage {
|
|
kind: FlashKind;
|
|
text: string;
|
|
}
|
|
|
|
/**
|
|
* Transient status-banner state for a settings panel.
|
|
*
|
|
* - `flash(kind, text)` shows a message that auto-clears after `durationMs`,
|
|
* cancelling any prior auto-clear timer first.
|
|
* - `setMsg` sets/clears the message directly (a persistent one that stays
|
|
* until the next action — e.g. a load-failure banner).
|
|
* - The pending timer is cleared on unmount.
|
|
*
|
|
* Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` +
|
|
* unmount cleanup, which had drifted (one panel omitted the ref, the
|
|
* prior-timer cancel, and the unmount cleanup entirely — leaking a timer that
|
|
* could fire a stale `setMsg` after unmount).
|
|
*/
|
|
export function useFlashMessage(durationMs = 2400): {
|
|
msg: FlashMessage | null;
|
|
flash: (kind: FlashKind, text: string) => void;
|
|
setMsg: (msg: FlashMessage | null) => void;
|
|
} {
|
|
const [msg, setMsg] = useState<FlashMessage | null>(null);
|
|
const timer = useRef<number | null>(null);
|
|
useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
|
|
const flash = (kind: FlashKind, text: string) => {
|
|
setMsg({ kind, text });
|
|
if (timer.current) clearTimeout(timer.current);
|
|
timer.current = window.setTimeout(() => setMsg(null), durationMs);
|
|
};
|
|
return { msg, flash, setMsg };
|
|
}
|