Files
SupplierSystem/src/components/ui/Modal.tsx
T
Ubuntu c3484789b1
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(Modal): 拆分焦点 effect —— 修「输入框敲一个字就失焦」(真机缺陷,影响所有弹窗)
## 根因(截图 + 代码定位,非浏览器默认行为)
`Modal` 的焦点 effect 依赖里有 `onClose`,而调用方几乎都传**内联箭头函数**
(如库存入库:`onClose={() => { if (!creatingProduct) setNewProductDraft(null); }}`)
⇒ 每次渲染都是新函数 ⇒ **effect 每次渲染都重跑**
⇒ `requestAnimationFrame(() => (firstFocusable || dialog)?.focus())` 把焦点**抢回弹窗**
⇒ 表现为「**在输入框里敲一个字就失去焦点**」,弹窗内每个输入框(商品名/规格/单位/分类)都一样。

## 修法(共享组件 Modal,一处修全受益)
把原来的单个 effect 拆成两个:
- **"打开时聚焦一次"**:只依赖 `[open]`(记住来源焦点 → 聚焦第一个可聚焦元素;cleanup 时归还焦点);
- **"键盘监听"**(Escape 关闭 / Tab 焦点环):仍依赖 `[open, onClose]`。

## 影响面与回归
- 影响**所有使用 `Modal` 的弹窗**:它们此前都有"敲字失焦"这个缺陷(只是没人报),修好之后统一受益;
  焦点管理本身(首次聚焦、Tab 环路、Escape、关闭后归还焦点)语义未变。
- 验证:前端 `tsc --noEmit` **0 错**;`stockInboundPanelShelfLife.contract.test.ts` + `PagePrimitives.test.tsx` 共 **8 条通过**。
- ⚠️ 未做浏览器目视验证(本机无 playwright/puppeteer)。**请刷新页面**后确认:
  ① 新建商品弹窗各输入框能连续打字不再失焦;② Tab 仍在弹窗内循环、Esc 仍能关闭;
  ③ 关闭弹窗后焦点回到原来那个按钮。

## 同批
本提交前的 `b1ca4e6` 已按开发者要求把库存入库新建商品弹窗的「分类」移到规格行**下方**、
并换成原生 input + datalist(无浮层、可输入)。
2026-10-17 08:35:28 +08:00

123 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useEffect, useId, useRef } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';
import { useBodyScrollLock } from '../../hooks/useBodyScrollLock';
export interface ModalProps {
open: boolean;
title: string;
onClose: () => void;
children: React.ReactNode;
footer?: React.ReactNode;
className?: string;
closeLabel?: string;
}
const FOCUSABLE_SELECTOR =
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
/** 全站标准弹窗:焦点锁、Escape 关闭、关闭后恢复焦点。 */
export const Modal: React.FC<ModalProps> = ({
open,
title,
onClose,
children,
footer,
className = 'max-w-2xl',
closeLabel = '关闭弹窗',
}) => {
const titleId = useId();
const dialogRef = useRef<HTMLDivElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
useBodyScrollLock(open);
/**
* ⚠️ **"打开时聚焦一次"必须只依赖 `open`**(2026-10-16 真机缺陷)。
*
* 原先这个 effect 的依赖里有 `onClose`,而调用方几乎都传**内联箭头函数**
* (`onClose={() => setX(null)}`)⇒ 每次渲染都是新函数 ⇒ effect 每次渲染都重跑
* ⇒ `requestAnimationFrame(() => firstFocusable.focus())` 把焦点**抢回弹窗**,
* 症状就是「**输入框敲一个字就失焦**」(弹窗里每个输入框都这样)。
* 所以拆成两个 effect:本 effect 只负责"打开时记住来源 + 聚焦第一个可聚焦元素"。
*/
useEffect(() => {
if (!open) return;
previousFocusRef.current = document.activeElement as HTMLElement | null;
const dialog = dialogRef.current;
const firstFocusable = dialog?.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
window.requestAnimationFrame(() => (firstFocusable || dialog)?.focus());
return () => {
previousFocusRef.current?.focus();
};
}, [open]);
// 键盘监听(Escape 关闭 / Tab 焦点环)仍然跟随 open 与 onClose
useEffect(() => {
if (!open) return;
const dialog = dialogRef.current;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
onClose();
return;
}
if (event.key !== 'Tab' || !dialog) return;
const focusable = Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
if (!focusable.length) {
event.preventDefault();
dialog.focus();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [open, onClose]);
if (!open) return null;
return createPortal(
<div
className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/50 p-4"
onMouseDown={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
tabIndex={-1}
className={`app-surface app-foreground flex max-h-[90vh] w-full flex-col overflow-hidden rounded-xl border ${className}`}
>
<div className="app-border flex items-center justify-between border-b px-5 py-4">
<h2 id={titleId} className="text-lg font-semibold">{title}</h2>
<button
type="button"
onClick={onClose}
aria-label={closeLabel}
className="app-focus-ring app-foreground-muted app-nav-idle rounded-lg p-2 focus:outline-none focus:ring-2"
>
<X className="h-5 w-5" />
</button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-5">{children}</div>
{footer ? (
<div className="app-border border-t px-5 py-4">{footer}</div>
) : null}
</div>
</div>,
document.body
);
};