fix(a11y): improve focus restoration with timing fixes, validation, and error handling

Core improvements:
- Fix focus restoration timing by using queueMicrotask only (removed double-layer async)
- Add comprehensive error handling with dev-mode logging for all failure scenarios
- Validate element visibility (display: none, visibility: hidden) before restoring focus
- Check disabled state and implement fallback to nearest focusable ancestor
- Add findNearestFocusableElement() helper for robust fallback strategy
- Add tabindex="-1" to focusable selectors for better focus management
- Use preventScroll option when calling focus() to prevent scroll jumps

Additional fixes:
- Remove unnecessary type conversion in Modal.tsx
- Fix TypeScript unused variable errors in main process
- Clean up unused imports in bip-users-dao.ts
- Add ARIA attributes and focus management to LoginDialog
- Add triggerRef support to UserSelectionDialog and ExecutionReportDialog
- Refactor ExecutionReportDialog to use Modal component
- Improve MaterialTypeManagementDialog with focus management

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
test
2026-03-08 18:29:39 +08:00
parent 9a640b96e6
commit bcfe0eecca
10 changed files with 493 additions and 971 deletions

View File

@@ -59,9 +59,11 @@ export function withErrorHandling<T>(
const code = getErrorCode(error)
// Serialize error with full details
const serializedError = serializeError(error)
const errorToLog =
process.env.NODE_ENV === 'production' ? sanitizeError(serializedError) : serializedError
if (process.env.NODE_ENV === 'production') {
sanitizeError(serializeError(error))
} else {
serializeError(error)
}
if (isBaseError(error)) {
logError(log, `[${context}] ${error.name}`, error, {

View File

@@ -14,7 +14,6 @@ import { ConfigManager } from '../config/config-manager'
import sql from 'mssql'
import type { UserInfo } from '../../types/user.types'
import { createLogger, logError } from '../logger'
import { serializeError } from '../logger/error-utils'
const log = createLogger('BipUsersDao')

View File

@@ -45,6 +45,9 @@ function App(): React.JSX.Element {
// Track if current session is switched by Admin
const [isSwitchedByAdmin, setIsSwitchedByAdmin] = useState(false)
// Ref for logout button (for focus restoration)
const logoutButtonRef = React.useRef<HTMLButtonElement>(null)
// Navigation state
const [currentPage, setCurrentPage] = useState<Page>('extractor') // Default to extractor for the new layout
@@ -251,6 +254,7 @@ function App(): React.JSX.Element {
currentUsername={currentUser?.username || ''}
onSelectUser={handleUserSelect}
onCancel={handleUserSelectionCancel}
triggerRef={logoutButtonRef}
/>
{errorMessage && <div className="error-toast">{errorMessage}</div>}
@@ -374,6 +378,7 @@ function App(): React.JSX.Element {
</span>
{shouldShowLogout && (
<button
ref={logoutButtonRef}
onClick={handleLogout}
className="ml-2 text-slate-400 hover:text-red-400 transition-colors"
title="退出登录"

View File

@@ -7,10 +7,9 @@
* - Error list (if any)
*/
import React, { useRef } from 'react'
import React from 'react'
import { CheckCircle, XCircle, SkipForward, Package, Loader2 } from 'lucide-react'
import FocusLock from 'react-focus-lock'
import { useDialogFocus } from '../hooks/useDialogFocus'
import { Modal } from './ui/Modal'
interface CleanerProgress {
message: string
@@ -34,6 +33,7 @@ interface ExecutionReportDialogProps {
isExecuting?: boolean
progress?: CleanerProgress | null
startTime?: number | null
triggerRef?: React.RefObject<HTMLElement | null>
}
export const ExecutionReportDialog: React.FC<ExecutionReportDialogProps> = ({
@@ -46,21 +46,14 @@ export const ExecutionReportDialog: React.FC<ExecutionReportDialogProps> = ({
dryRun = false,
isExecuting = false,
progress = null,
startTime = null
startTime = null,
triggerRef
}) => {
const dialogRef = useRef<HTMLDivElement>(null)
const [now, setNow] = React.useState(() => Date.now())
// Setup focus management with conditional escape key handling
const { focusLockProps } = useDialogFocus({
isOpen,
dialogRef,
onClose,
shouldCloseOnEscape: () => !isExecuting // Only close when NOT executing
})
const hasErrors = errors.length > 0
const showProgress = isExecuting && progress
const isProgressing = !!showProgress
React.useEffect(() => {
if (!showProgress || !startTime) return
@@ -99,633 +92,208 @@ export const ExecutionReportDialog: React.FC<ExecutionReportDialogProps> = ({
}
}, [showProgress, startTime, progress, now])
if (!isOpen) return null
return (
<FocusLock {...focusLockProps}>
<div
className="execution-report-overlay"
onClick={showProgress ? undefined : onClose}
role="dialog"
aria-modal="true"
aria-labelledby={
showProgress ? 'execution-dialog-progress-title' : 'execution-dialog-report-title'
}
>
<div
ref={dialogRef}
className="execution-report-dialog"
onClick={(e) => e.stopPropagation()}
style={{ width: showProgress ? '560px' : '480px' }}
>
{showProgress ? (
// Progress View
<div className="progress-header">
<div className="progress-icon-wrapper">
<Loader2 className="progress-icon spinning" />
</div>
<h2 id="execution-dialog-progress-title" className="progress-title">
...
</h2>
<p className="progress-subtitle" aria-live="polite" aria-atomic="true">
{progress?.message || '处理中...'}
</p>
<Modal
isOpen={isOpen}
onClose={onClose}
title={
isProgressing
? '正在执行清理...'
: dryRun
? '预览执行报告'
: hasErrors
? '执行完成 (有错误)'
: '执行完成'
}
size={isProgressing ? 'lg' : 'md'}
showCloseButton={!isExecuting}
triggerRef={triggerRef}
isAlertDialog={isProgressing}
disableEscapeKey={isProgressing}
ariaDescribedBy={isProgressing ? 'execution-dialog-progress-desc' : undefined}
initialFocusSelector={!isProgressing ? '.btn-report-close' : undefined}
>
{isProgressing ? (
// Progress View
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="relative">
<Loader2 className="w-12 h-12 text-blue-500 animate-spin" />
</div>
) : (
// Result View
<div className="report-header">
<div className="report-icon-wrapper">
{dryRun ? (
<Package className="report-icon preview" />
) : hasErrors ? (
<XCircle className="report-icon error" />
) : (
<CheckCircle className="report-icon success" />
)}
</div>
<p
id="execution-dialog-progress-desc"
className="text-sm text-gray-600 mb-4"
aria-live="polite"
aria-atomic="true"
>
{progress?.message || '处理中...'}
</p>
</div>
) : (
// Result View
<div className="text-center mb-4">
<div className="flex justify-center mb-4">
{dryRun ? (
<Package className="w-12 h-12 text-amber-500" />
) : hasErrors ? (
<XCircle className="w-12 h-12 text-red-500" />
) : (
<CheckCircle className="w-12 h-12 text-green-500" />
)}
</div>
<p className="text-sm text-gray-600">
{dryRun
? '预览模式 - 未实际删除数据'
: hasErrors
? '部分操作未能完成,请查看下方错误信息'
: '所有操作已成功完成'}
</p>
</div>
)}
{isProgressing ? (
// Progress View Content
<div className="space-y-4">
<div className="progress-bar-container w-full h-6 bg-gradient-to-r from-blue-50 to-sky-100 rounded-full overflow-hidden border border-blue-200 relative">
<div
className="progress-bar-fill h-full bg-gradient-to-r from-blue-500 to-blue-700 transition-all duration-300 relative overflow-hidden"
style={{ width: `${progress?.progress || 0}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-shimmer" />
</div>
</div>
<div className="flex justify-around py-4 bg-gray-50 rounded-lg border border-gray-200">
<div className="flex flex-col items-center">
<span className="text-xs text-gray-600"></span>
<span className="text-lg font-semibold text-blue-600">
{Math.min(progress!.currentOrderIndex, progress!.totalOrders)} /{' '}
{progress!.totalOrders}
</span>
</div>
{progress!.totalMaterialsInOrder > 0 && (
<div className="flex flex-col items-center">
<span className="text-xs text-gray-600"></span>
<span className="text-lg font-semibold text-blue-600">
{progress!.currentMaterialIndex} / {progress!.totalMaterialsInOrder}
</span>
</div>
<h2 id="execution-dialog-report-title" className="report-title">
{dryRun ? '预览执行报告' : hasErrors ? '执行完成 (有错误)' : '执行完成'}
</h2>
<p className="report-subtitle">
{dryRun
? '预览模式 - 未实际删除数据'
: hasErrors
? '部分操作未能完成,请查看下方错误信息'
: '所有操作已成功完成'}
</p>
)}
<div className="flex flex-col items-center">
<span className="text-xs text-gray-600"></span>
<span className="text-lg font-semibold text-blue-600">
{Math.round(progress?.progress || 0)}%
</span>
</div>
</div>
{progress?.currentOrderNumber && (
<div className="flex items-center justify-center gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200">
<Package size={14} className="text-blue-600" />
<span className="text-sm text-gray-600">:</span>
<span className="text-sm font-medium text-gray-900 font-mono">
{progress.currentOrderNumber}
</span>
</div>
)}
<div className="report-body">
{showProgress ? (
// Progress View Content
<div className="progress-content">
<div className="progress-bar-container">
<div
className="progress-bar-fill"
style={{ width: `${progress?.progress || 0}%` }}
/>
</div>
<div className="progress-stats">
<div className="progress-stat-item">
<span className="stat-label"></span>
<span className="stat-value">
{Math.min(progress!.currentOrderIndex, progress!.totalOrders)} /{' '}
{progress!.totalOrders}
</span>
</div>
{progress!.totalMaterialsInOrder > 0 && (
<div className="progress-stat-item">
<span className="stat-label"></span>
<span className="stat-value">
{progress!.currentMaterialIndex} / {progress!.totalMaterialsInOrder}
</span>
</div>
)}
<div className="progress-stat-item">
<span className="stat-label"></span>
<span className="stat-value">{Math.round(progress?.progress || 0)}%</span>
</div>
</div>
{progress?.currentOrderNumber && (
<div className="current-order-info">
<Package size={14} className="order-icon" />
<span className="order-label">:</span>
<span className="order-number">{progress.currentOrderNumber}</span>
</div>
)}
{estimatedTime && (
<div className="estimated-time-info">
<div className="estimated-time-item">
<span className="time-label"></span>
<span className="time-value">{estimatedTime.remainingMinutes} </span>
</div>
<div className="estimated-time-item">
<span className="time-label"></span>
<span className="time-value">{estimatedTime.formattedTime}</span>
<span className="time-label"></span>
</div>
</div>
)}
{estimatedTime && (
<div className="flex flex-col items-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200">
<div className="flex items-center gap-2 text-sm">
<span className="text-gray-600"></span>
<span className="font-semibold text-green-600">
{estimatedTime.remainingMinutes}
</span>
</div>
) : (
// Result View Content
<>
<div className="stats-grid">
<div className="stat-card">
<div className="stat-icon orders">
<Package size={20} />
</div>
<div className="stat-content">
<div className="stat-label"></div>
<div className="stat-value">{ordersProcessed}</div>
</div>
</div>
<div className="stat-card">
<div className="stat-icon deleted">
<CheckCircle size={20} />
</div>
<div className="stat-content">
<div className="stat-label">{dryRun ? '拟删除物料' : '删除物料'}</div>
<div className="stat-value">{materialsDeleted}</div>
</div>
</div>
<div className="stat-card">
<div className="stat-icon skipped">
<SkipForward size={20} />
</div>
<div className="stat-content">
<div className="stat-label"></div>
<div className="stat-value">{materialsSkipped}</div>
</div>
</div>
{hasErrors && (
<div className="stat-card">
<div className="stat-icon errors">
<XCircle size={20} />
</div>
<div className="stat-content">
<div className="stat-label"></div>
<div className="stat-value error">{errors.length}</div>
</div>
</div>
)}
</div>
{hasErrors && (
<div className="errors-section">
<div className="errors-title"></div>
<div className="errors-list">
{errors.map((error, index) => (
<div key={index} className="error-item">
<XCircle size={14} className="error-icon" />
<span className="error-text">{error}</span>
</div>
))}
</div>
</div>
)}
{!hasErrors && !dryRun && (
<div className="success-message">
<CheckCircle size={16} className="success-icon" />
<span> ERP </span>
</div>
)}
{!hasErrors && dryRun && (
<div className="preview-message">
<Package size={16} className="preview-icon" />
<span></span>
</div>
)}
</>
)}
</div>
<div className="report-footer">
{!showProgress && (
<button className="btn-report-close" onClick={onClose}>
</button>
)}
</div>
<style>{`
.execution-report-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
animation: fadeIn 0.2s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.execution-report-dialog {
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
max-width: 90vw;
animation: slideDown 0.2s ease-out;
transition: width 0.3s ease;
}
.progress-header,
.report-header {
text-align: center;
padding: 24px 24px 16px 24px;
border-bottom: 1px solid #f0f0f0;
}
.progress-icon-wrapper,
.report-icon-wrapper {
display: flex;
justify-content: center;
margin-bottom: 12px;
}
.progress-icon {
width: 48px;
height: 48px;
color: #1890ff;
animation: spin 1.5s linear infinite;
}
.progress-title {
font-size: 20px;
font-weight: 600;
color: #333;
margin: 0 0 8px 0;
}
.progress-subtitle {
font-size: 13px;
color: #666;
margin: 0;
}
.report-icon {
width: 48px;
height: 48px;
}
.report-icon.success {
color: #52c41a;
}
.report-icon.error {
color: #ff4d4f;
}
.report-icon.preview {
color: #faad14;
}
.report-title {
font-size: 20px;
font-weight: 600;
color: #333;
margin: 0 0 8px 0;
}
.report-subtitle {
font-size: 13px;
color: #999;
margin: 0;
}
.report-body {
padding: 20px 24px;
}
/* Progress View Styles */
.progress-content {
display: flex;
flex-direction: column;
gap: 16px;
}
.progress-bar-container {
width: 100%;
height: 24px;
background: linear-gradient(90deg, #e6f7ff 0%, #bae7ff 100%);
border-radius: 12px;
overflow: hidden;
border: 1px solid #91d5ff;
position: relative;
}
.progress-bar-fill {
height: 100%;
background: linear-gradient(90deg, #1890ff 0%, #096dd9 100%);
border-radius: 12px;
transition: width 0.3s ease;
position: relative;
overflow: hidden;
}
.progress-bar-fill::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(
90deg,
transparent 0%,
rgba(255, 255, 255, 0.3) 50%,
transparent 100%
);
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(100%);
}
}
.progress-stats {
display: flex;
justify-content: space-around;
padding: 16px;
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #e8e8e8;
}
.progress-stat-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.progress-stat-item .stat-label {
font-size: 12px;
color: #666;
}
.progress-stat-item .stat-value {
font-size: 18px;
font-weight: 600;
color: #1890ff;
}
.current-order-info {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
background: #f0f5ff;
border-radius: 6px;
border: 1px solid #d6e4ff;
}
.current-order-info .order-icon {
color: #1890ff;
}
.current-order-info .order-label {
font-size: 13px;
color: #666;
}
.current-order-info .order-number {
font-size: 14px;
font-weight: 500;
color: #333;
font-family: monospace;
}
.estimated-time-info {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 12px;
background: #f6ffed;
border-radius: 6px;
border: 1px solid #b7eb8f;
}
.estimated-time-item {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
}
.estimated-time-item .time-label {
color: #666;
}
.estimated-time-item .time-value {
font-size: 14px;
font-weight: 600;
color: #52c41a;
}
/* Result View Styles */
.stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.stat-card {
background: #f8f9fa;
border-radius: 6px;
padding: 12px;
display: flex;
align-items: center;
gap: 10px;
border: 1px solid #e8e8e8;
}
.stat-card:nth-child(4) {
grid-column: span 3;
}
.stat-icon {
width: 36px;
height: 36px;
border-radius: 6px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.stat-icon.orders {
background: #e6f7ff;
color: #1890ff;
}
.stat-icon.deleted {
background: #f6ffed;
color: #52c41a;
}
.stat-icon.skipped {
background: #fff7e6;
color: #faad14;
}
.stat-icon.errors {
background: #fff1f0;
color: #ff4d4f;
}
.stat-content {
flex: 1;
min-width: 0;
}
.stat-label {
font-size: 12px;
color: #666;
margin-bottom: 4px;
}
.stat-value {
font-size: 20px;
font-weight: 600;
color: #333;
line-height: 1;
}
.stat-value.error {
color: #ff4d4f;
}
.errors-section {
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #f0f0f0;
}
.errors-title {
font-size: 13px;
font-weight: 600;
color: #ff4d4f;
margin-bottom: 8px;
}
.errors-list {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 150px;
overflow-y: auto;
}
.error-item {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 8px 10px;
background: #fff1f0;
border-radius: 4px;
border: 1px solid #ffccc7;
}
.error-icon {
color: #ff4d4f;
flex-shrink: 0;
margin-top: 1px;
}
.error-text {
font-size: 12px;
color: #333;
word-break: break-word;
}
.success-message,
.preview-message {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
border-radius: 6px;
font-size: 13px;
}
.success-message {
background: #f6ffed;
color: #52c41a;
border: 1px solid #b7eb8f;
}
.preview-message {
background: #fff7e6;
color: #faad14;
border: 1px solid #ffd591;
}
.success-icon,
.preview-icon {
flex-shrink: 0;
}
.report-footer {
padding: 16px 24px;
border-top: 1px solid #f0f0f0;
display: flex;
justify-content: center;
}
.btn-report-close {
background: #1890ff;
color: #fff;
border: none;
border-radius: 6px;
padding: 10px 32px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
}
.btn-report-close:hover {
background: #40a9ff;
}
.btn-report-close:active {
background: #096dd9;
}
`}</style>
<div className="flex items-center gap-2 text-sm">
<span className="text-gray-600"></span>
<span className="font-semibold text-green-600">{estimatedTime.formattedTime}</span>
<span className="text-gray-600"></span>
</div>
</div>
)}
</div>
</div>
</FocusLock>
) : (
// Result View Content
<>
<div className="grid grid-cols-3 gap-3 mb-4">
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
<div className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0">
<Package size={20} className="text-blue-600" />
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-gray-600"></div>
<div className="text-xl font-semibold text-gray-900">{ordersProcessed}</div>
</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
<div className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center flex-shrink-0">
<CheckCircle size={20} className="text-green-600" />
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-gray-600">{dryRun ? '拟删除物料' : '删除物料'}</div>
<div className="text-xl font-semibold text-gray-900">{materialsDeleted}</div>
</div>
</div>
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200">
<div className="w-9 h-9 rounded-lg bg-amber-50 flex items-center justify-center flex-shrink-0">
<SkipForward size={20} className="text-amber-600" />
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-gray-600"></div>
<div className="text-xl font-semibold text-gray-900">{materialsSkipped}</div>
</div>
</div>
{hasErrors && (
<div className="bg-gray-50 rounded-lg p-3 flex items-center gap-3 border border-gray-200 col-span-3">
<div className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center flex-shrink-0">
<XCircle size={20} className="text-red-600" />
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-gray-600"></div>
<div className="text-xl font-semibold text-red-600">{errors.length}</div>
</div>
</div>
)}
</div>
{hasErrors && (
<div className="mt-4 pt-4 border-t border-gray-200">
<div className="text-sm font-semibold text-red-600 mb-2"></div>
<div className="flex flex-col gap-2 max-h-40 overflow-y-auto">
{errors.map((error, index) => (
<div
key={index}
className="flex items-start gap-2 p-2 bg-red-50 rounded border border-red-200"
>
<XCircle size={14} className="text-red-600 flex-shrink-0 mt-0.5" />
<span className="text-sm text-gray-900 break-words">{error}</span>
</div>
))}
</div>
</div>
)}
{!hasErrors && !dryRun && (
<div className="flex items-center justify-center gap-2 p-3 bg-green-50 rounded-lg border border-green-200 text-green-700 text-sm">
<CheckCircle size={16} className="flex-shrink-0" />
<span> ERP </span>
</div>
)}
{!hasErrors && dryRun && (
<div className="flex items-center justify-center gap-2 p-3 bg-amber-50 rounded-lg border border-amber-200 text-amber-700 text-sm">
<Package size={16} className="flex-shrink-0" />
<span></span>
</div>
)}
</>
)}
</Modal>
)
}

View File

@@ -8,8 +8,7 @@
*/
import React, { useState, useRef } from 'react'
import FocusLock from 'react-focus-lock'
import { useDialogFocus } from '../hooks/useDialogFocus'
import { Modal } from './ui/Modal'
interface LoginDialogProps {
isOpen: boolean
@@ -31,26 +30,15 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
const [isLoggingIn, setIsLoggingIn] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const usernameInputRef = useRef<HTMLInputElement>(null)
const dialogRef = useRef<HTMLDivElement>(null)
const errorRef = useRef<HTMLDivElement>(null)
// Setup focus management with useDialogFocus hook
const { focusLockProps } = useDialogFocus({
isOpen,
dialogRef,
onClose: onCancel,
initialFocusSelector: 'input[type="text"]' // Focus username input initially
})
// Display error message with aria-live
const showError = (message: string): void => {
setErrorMessage(message)
// Also call the original onError callback for backward compatibility
onError(message)
}
const handleLogin = async (): Promise<void> => {
// Clear error message when attempting login
setErrorMessage('')
if (!username.trim()) {
@@ -80,89 +68,81 @@ export const LoginDialog: React.FC<LoginDialogProps> = ({
}
}
if (!isOpen) return null
return (
<FocusLock {...focusLockProps}>
<div
className="login-overlay"
onKeyDown={handleKeyDown}
role="dialog"
aria-modal="true"
aria-labelledby="login-dialog-title"
>
<div className="login-dialog" ref={dialogRef}>
<div className="login-header">
<h2 id="login-dialog-title" className="login-title">
</h2>
<p className="computer-name">{computerName}</p>
<Modal
isOpen={isOpen}
onClose={onCancel}
title="请登录"
size="md"
showCloseButton={true}
initialFocusSelector='input[type="text"]'
ariaDescribedBy={errorMessage ? 'login-dialog-error' : undefined}
>
<div onKeyDown={handleKeyDown}>
{/* Error message area with aria-live for screen readers */}
{errorMessage && (
<div
ref={errorRef}
id="login-dialog-error"
className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-sm"
role="alert"
aria-live="polite"
tabIndex={-1}
>
{errorMessage}
</div>
)}
{/* Error message area with aria-live for screen readers */}
{errorMessage && (
<div
ref={errorRef}
className="error-message mb-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-sm"
role="alert"
aria-live="polite"
tabIndex={-1}
>
{errorMessage}
</div>
)}
<div className="space-y-4">
<div className="text-sm text-gray-600">{computerName}</div>
<div className="login-body">
<div className="form-group">
<label className="form-label text-slate-700">:</label>
<input
ref={usernameInputRef}
type="text"
className="form-input border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="请输入用户名"
disabled={isLoggingIn}
/>
</div>
<div className="form-group mt-4">
<label className="form-label text-slate-700">:</label>
<input
type="password"
className="form-input border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="请输入密码"
disabled={isLoggingIn}
/>
</div>
</div>
<div className="login-footer mt-6 flex justify-end gap-3">
<button
className="btn btn-secondary px-4 py-2 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-700 transition-colors"
onClick={onCancel}
<div>
<label className="block text-sm text-slate-700 mb-1">:</label>
<input
ref={usernameInputRef}
type="text"
className="border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="请输入用户名"
disabled={isLoggingIn}
>
</button>
<button
className="btn btn-primary px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white transition-colors disabled:opacity-50"
onClick={handleLogin}
disabled={isLoggingIn}
>
{isLoggingIn ? '登录中...' : '登录'}
</button>
/>
</div>
<div className="login-version">v1.0</div>
<div>
<label className="block text-sm text-slate-700 mb-1">:</label>
<input
type="password"
className="border border-slate-300 rounded-md p-2 w-full text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="请输入密码"
disabled={isLoggingIn}
/>
</div>
</div>
<div className="mt-6 flex justify-end gap-3">
<button
className="px-4 py-2 rounded-md bg-slate-100 hover:bg-slate-200 text-slate-700 transition-colors"
onClick={onCancel}
disabled={isLoggingIn}
>
</button>
<button
className="px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white transition-colors disabled:opacity-50"
onClick={handleLogin}
disabled={isLoggingIn}
>
{isLoggingIn ? '登录中...' : '登录'}
</button>
</div>
<div className="mt-4 text-xs text-gray-400 text-right">v1.0</div>
</div>
</FocusLock>
</Modal>
)
}
export default LoginDialog
// Styles are now handled by Tailwind classes in the component

View File

@@ -27,13 +27,15 @@ interface MaterialTypeManagementDialogProps {
onClose: () => void
isAdmin: boolean
currentUsername: string
triggerRef?: React.RefObject<HTMLButtonElement | null>
}
export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialogProps> = ({
isOpen,
onClose,
isAdmin,
currentUsername
currentUsername,
triggerRef
}) => {
const [rows, setRows] = useState<RowState[]>([])
const [managers, setManagers] = useState<string[]>([])
@@ -304,7 +306,13 @@ export const MaterialTypeManagementDialog: React.FC<MaterialTypeManagementDialog
}
return (
<Modal isOpen={isOpen} onClose={handleClose} title="物料类型管理" size="2xl">
<Modal
isOpen={isOpen}
onClose={handleClose}
title="物料类型管理"
size="2xl"
triggerRef={triggerRef}
>
<div onKeyDown={handleKeyDown}>
{/* Manager filter (admin only) */}
{isAdmin && (

View File

@@ -8,8 +8,7 @@
*/
import React, { useState, useEffect, useRef } from 'react'
import FocusLock from 'react-focus-lock'
import { useDialogFocus } from '../hooks/useDialogFocus'
import { Modal } from './ui/Modal'
export interface UserInfo {
id: number
@@ -24,6 +23,7 @@ interface UserSelectionDialogProps {
currentUsername: string
onSelectUser: (user: UserInfo) => void
onCancel: () => void
triggerRef?: React.RefObject<HTMLElement | null>
}
export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
@@ -31,18 +31,12 @@ export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
users,
currentUsername,
onSelectUser,
onCancel
onCancel,
triggerRef
}) => {
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
const dialogRef = useRef<HTMLDivElement>(null)
const { focusLockProps } = useDialogFocus({
isOpen,
dialogRef,
onClose: onCancel,
initialFocusSelector: users.length > 0 ? '.user-item:first-child' : undefined
})
// Reset selection when dialog opens
useEffect(() => {
if (isOpen) {
@@ -65,238 +59,85 @@ export const UserSelectionDialog: React.FC<UserSelectionDialogProps> = ({
onSelectUser(user)
}
const userTypeStyles: Record<string, string> = {
Admin: 'bg-amber-50 text-amber-600',
User: 'bg-blue-50 text-blue-600',
Guest: 'bg-gray-100 text-gray-600'
}
if (!isOpen) return null
return (
<FocusLock {...focusLockProps}>
<div
className="user-selection-overlay"
role="dialog"
aria-modal="true"
aria-labelledby="user-selection-dialog-title"
>
<div className="user-selection-dialog" ref={dialogRef}>
<div className="user-selection-header">
<h2 className="user-selection-title" id="user-selection-dialog-title">
</h2>
<p className="user-selection-hint">{currentUsername}</p>
</div>
<Modal
isOpen={isOpen}
onClose={onCancel}
title="选择用户"
size="md"
triggerRef={triggerRef}
initialFocusSelector={users.length > 0 ? '.user-item:first-child' : undefined}
ariaDescribedBy="user-selection-description"
>
<div ref={dialogRef} className="max-h-[60vh] flex flex-col">
<div className="text-sm text-gray-600 mb-4">{currentUsername}</div>
<p id="user-selection-description" className="sr-only">
</p>
<div className="user-selection-body">
<div className="user-list">
{users.map((user) => (
<div
key={user.id}
className={`user-item ${selectedUserId === user.id ? 'selected' : ''}`}
onClick={() => setSelectedUserId(user.id)}
onDoubleClick={() => handleDoubleClick(user)}
>
<div className="user-item-content">
<div className="user-item-row">
<span className="user-name">{user.username}</span>
<span className={`user-type user-type-${user.userType.toLowerCase()}`}>
{user.userType}
</span>
</div>
{user.createTime && (
<div className="user-item-row">
<span className="user-create-time">
{new Date(user.createTime).toLocaleString('zh-CN')}
</span>
</div>
)}
</div>
<div className="flex-1 overflow-y-auto mb-4">
<div className="flex flex-col gap-2">
{users.map((user) => (
<div
key={user.id}
className={`user-item p-3 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-blue-500 hover:bg-green-50 ${
selectedUserId === user.id ? 'border-blue-500 bg-blue-50' : ''
}`}
onClick={() => setSelectedUserId(user.id)}
onDoubleClick={() => handleDoubleClick(user)}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
setSelectedUserId(user.id)
}
}}
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-900">{user.username}</span>
<span
className={`text-xs px-2 py-1 rounded font-medium ${userTypeStyles[user.userType]}`}
>
{user.userType}
</span>
</div>
))}
</div>
{user.createTime && (
<div className="mt-1 text-xs text-gray-500">
{new Date(user.createTime).toLocaleString('zh-CN')}
</div>
)}
</div>
))}
</div>
</div>
<div className="user-selection-footer">
<div className="border-t border-gray-200 pt-4">
<div className="flex justify-center gap-3">
<button
className="btn btn-primary"
className="px-6 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
onClick={handleConfirm}
disabled={selectedUserId === null}
>
</button>
<button className="btn btn-secondary" onClick={onCancel}>
<button
className="px-6 py-2 rounded-md bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium transition-colors"
onClick={onCancel}
>
</button>
</div>
<div className="user-selection-hint-footer"></div>
<div className="text-center text-xs text-gray-500 mt-3"></div>
</div>
</div>
<style>{`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.user-selection-dialog {
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
width: 450px;
max-height: 80vh;
display: flex;
flex-direction: column;
}
.user-selection-header {
padding: 20px 24px;
border-bottom: 1px solid #f0f0f0;
}
.user-selection-title {
font-size: 18px;
font-weight: 600;
color: #333;
margin: 0 0 8px 0;
}
.user-selection-hint {
font-size: 13px;
color: #666;
margin: 0;
}
.user-selection-body {
flex: 1;
overflow-y: auto;
padding: 16px 24px;
min-height: 200px;
max-height: 400px;
}
.user-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.user-item {
padding: 12px 16px;
border: 1px solid #e8e8e8;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.user-item:hover {
border-color: #1890ff;
background: #f6ffed;
}
.user-item.selected {
border-color: #1890ff;
background: #e6f7ff;
}
.user-item-content {
display: flex;
flex-direction: column;
gap: 4px;
}
.user-item-row {
display: flex;
align-items: center;
gap: 12px;
}
.user-name {
font-size: 14px;
font-weight: 500;
color: #333;
}
.user-type {
font-size: 12px;
padding: 2px 8px;
border-radius: 4px;
font-weight: 500;
}
.user-type-admin {
background: #fff7e6;
color: #fa8c16;
}
.user-type-user {
background: #e6f7ff;
color: #1890ff;
}
.user-type-guest {
background: #f5f5f5;
color: #666;
}
.user-create-time {
font-size: 12px;
color: #999;
}
.user-selection-footer {
display: flex;
gap: 12px;
justify-content: center;
padding: 16px 24px;
border-top: 1px solid #f0f0f0;
}
.btn {
padding: 10px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-primary {
background: #1890ff;
color: #fff;
}
.btn-primary:hover:not(:disabled) {
background: #40a9ff;
}
.btn-secondary {
background: #f5f5f5;
color: #666;
}
.btn-secondary:hover:not(:disabled) {
background: #e8e8e8;
}
.user-selection-hint-footer {
text-align: center;
font-size: 12px;
color: #999;
padding: 8px 16px;
border-top: 1px solid #f0f0f0;
}
`}</style>
</FocusLock>
</Modal>
)
}

View File

@@ -20,6 +20,14 @@ interface ModalProps {
triggerRef?: React.RefObject<HTMLElement | null>
/** ID of the title element (for aria-labelledby) */
titleId?: string
/** Selector for the element to focus initially inside the modal */
initialFocusSelector?: string
/** ID of the element that describes the modal (for aria-describedby) */
ariaDescribedBy?: string
/** Whether this is an alert dialog (role="alertdialog" instead of "dialog") */
isAlertDialog?: boolean
/** Whether to disable escape key handling (e.g., during execution) */
disableEscapeKey?: boolean
}
const sizeStyles: Record<string, string> = {
@@ -39,7 +47,11 @@ export function Modal({
size = 'md',
showCloseButton = true,
triggerRef,
titleId
titleId,
initialFocusSelector,
ariaDescribedBy,
isAlertDialog = false,
disableEscapeKey = false
}: ModalProps): React.JSX.Element | null {
const dialogRef = useRef<HTMLDivElement>(null)
const [generatedId] = useState(
@@ -56,18 +68,27 @@ export function Modal({
isOpen,
dialogRef,
onClose,
triggerRef: triggerRef || undefined
triggerRef,
initialFocusSelector,
shouldCloseOnEscape: !disableEscapeKey
})
if (!isOpen) return null
return (
<FocusLock {...focusLockProps}>
<div className="fixed inset-0 z-50 overflow-y-auto">
<div
className="fixed inset-0 z-50 overflow-y-auto"
role={isAlertDialog ? 'alertdialog' : 'dialog'}
aria-modal="true"
aria-labelledby={generatedTitleId}
aria-describedby={ariaDescribedBy}
>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
onClick={onClose}
aria-hidden="true"
/>
{/* Modal container */}
@@ -75,9 +96,6 @@ export function Modal({
<div
ref={dialogRef}
className={`relative w-full ${sizeStyles[size]} bg-white rounded-lg shadow-xl transform transition-all`}
role="dialog"
aria-modal="true"
aria-labelledby={generatedTitleId}
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
@@ -92,6 +110,7 @@ export function Modal({
<button
onClick={onClose}
className="p-1 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded"
aria-label="关闭对话框"
>
<X className="w-5 h-5" />
</button>

View File

@@ -166,21 +166,29 @@ export function useDialogFocus(options: UseDialogFocusOptions): UseDialogFocusRe
if (initialFocusSelector) {
const focusElement = dialogElement.querySelector(initialFocusSelector) as HTMLElement
if (focusElement && typeof focusElement.focus === 'function') {
// Delay focus to ensure DOM is ready
requestAnimationFrame(() => {
focusElement.focus()
})
return
// Check if element is visible and focusable
const style = window.getComputedStyle(focusElement)
if (style.display !== 'none' && style.visibility !== 'hidden') {
requestAnimationFrame(() => {
focusElement.focus({ preventScroll: true })
})
return
}
// Fallback: element found but not visible, log warning and try default
console.warn(`Focus element found but not visible: ${initialFocusSelector}`)
} else {
// Fallback: element not found, log warning and try default
console.warn(`Focus element not found for selector: ${initialFocusSelector}`)
}
}
// Otherwise, focus the first interactive element
const focusableSelectors = [
'button:not([disabled])',
'button:not([disabled]):not([tabindex="-1"])',
'a[href]',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled]):not([tabindex="-1"])',
'select:not([disabled]):not([tabindex="-1"])',
'textarea:not([disabled]):not([tabindex="-1"])',
'[tabindex]:not([tabindex="-1"])'
]
const firstFocusable = dialogElement.querySelector(
@@ -188,7 +196,7 @@ export function useDialogFocus(options: UseDialogFocusOptions): UseDialogFocusRe
) as HTMLElement
if (firstFocusable && typeof firstFocusable.focus === 'function') {
requestAnimationFrame(() => {
firstFocusable.focus()
firstFocusable.focus({ preventScroll: true })
})
}
}
@@ -203,16 +211,101 @@ export function useDialogFocus(options: UseDialogFocusOptions): UseDialogFocusRe
const restoreFocus = (): void => {
const triggerElement = triggerRef.current
if (triggerElement && typeof triggerElement.focus === 'function') {
// Delay to ensure dialog is fully unmounted
requestAnimationFrame(() => {
triggerElement.focus()
})
// Check if element still exists in DOM
if (!triggerElement || !document.contains(triggerElement)) {
if (import.meta.env.DEV) {
console.warn('[useDialogFocus] Trigger element not found in DOM, cannot restore focus')
}
return
}
// Check if element has a focus method
if (typeof triggerElement.focus !== 'function') {
if (import.meta.env.DEV) {
console.warn('[useDialogFocus] Trigger element does not have a focus method')
}
return
}
// Check if element is visible (not display: none)
const style = window.getComputedStyle(triggerElement)
if (style.display === 'none') {
if (import.meta.env.DEV) {
console.warn('[useDialogFocus] Trigger element is display: none, cannot restore focus')
}
return
}
if (style.visibility === 'hidden') {
if (import.meta.env.DEV) {
console.warn('[useDialogFocus] Trigger element is visibility: hidden, cannot restore focus')
}
return
}
// Check if element is disabled
if (triggerElement instanceof HTMLButtonElement && triggerElement.disabled) {
if (import.meta.env.DEV) {
console.warn('[useDialogFocus] Trigger element is disabled, cannot restore focus')
}
// Try to find nearest enabled ancestor or fallback to body
const focusableParent = findNearestFocusableElement(triggerElement)
if (focusableParent) {
focusableParent.focus({ preventScroll: true })
if (import.meta.env.DEV) {
console.info('[useDialogFocus] Restored focus to nearest focusable ancestor')
}
}
return
}
// All checks passed, restore focus
try {
triggerElement.focus({ preventScroll: true })
if (import.meta.env.DEV) {
console.info('[useDialogFocus] Successfully restored focus to trigger element')
}
} catch (error) {
if (import.meta.env.DEV) {
console.error('[useDialogFocus] Error restoring focus:', error)
}
}
}
// Wait for next tick to ensure dialog is closed
setTimeout(restoreFocus, 0)
// Helper function to find nearest focusable ancestor
const findNearestFocusableElement = (element: HTMLElement): HTMLElement | null => {
let parent = element.parentElement
const focusableSelectors = [
'button:not([disabled]):not([tabindex="-1"])',
'a[href]',
'input:not([disabled]):not([tabindex="-1"])',
'select:not([disabled]):not([tabindex="-1"])',
'textarea:not([disabled]):not([tabindex="-1"])',
'[tabindex]:not([tabindex="-1"])'
]
while (parent && parent !== document.body) {
// Check if parent itself is focusable
if (
focusableSelectors.some((selector) => parent?.matches(selector)) &&
window.getComputedStyle(parent).display !== 'none' &&
window.getComputedStyle(parent).visibility !== 'hidden'
) {
return parent
}
// Check if parent contains focusable element
const focusableChild = parent.querySelector(focusableSelectors.join(', ')) as HTMLElement
if (focusableChild) {
return focusableChild
}
parent = parent.parentElement
}
return null
}
// Use microtask queue to ensure this runs after DOM cleanup
queueMicrotask(restoreFocus)
}, [isOpen, triggerRef])
// Return focus lock configuration

View File

@@ -20,6 +20,9 @@ import ExecutionReportDialog from '../components/ExecutionReportDialog'
import { useCleaner } from '../hooks/useCleaner'
const CleanerPage: React.FC = () => {
const typeManagementButtonRef = React.useRef<HTMLButtonElement>(null)
const executeButtonRef = React.useRef<HTMLButtonElement>(null)
const {
isAdmin,
currentUsername,
@@ -249,6 +252,7 @@ const CleanerPage: React.FC = () => {
<div className="flex items-center gap-2">
<button
onClick={() => setIsTypeDialogOpen(true)}
ref={typeManagementButtonRef}
className="text-xs bg-white border border-slate-300 text-slate-700 px-3 py-1.5 rounded shadow-sm hover:bg-slate-50 flex items-center gap-1.5"
>
<Settings2 size={14} />
@@ -458,6 +462,7 @@ const CleanerPage: React.FC = () => {
</div>
<button
onClick={handleExecuteDeletion}
ref={executeButtonRef}
disabled={isRunning}
className={`${dryRun ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-600 hover:bg-red-700 shadow-red-500/30'} text-white px-8 py-2.5 rounded-lg font-medium shadow-md transition-all flex items-center gap-2 disabled:opacity-50 w-[300px] justify-center`}
>
@@ -473,6 +478,7 @@ const CleanerPage: React.FC = () => {
onClose={() => setIsTypeDialogOpen(false)}
isAdmin={isAdmin}
currentUsername={currentUsername}
triggerRef={typeManagementButtonRef}
/>
{/* Execution Report Dialog */}
@@ -487,6 +493,7 @@ const CleanerPage: React.FC = () => {
isExecuting={isExecuting}
progress={progress}
startTime={startTime}
triggerRef={executeButtonRef}
/>
</div>
)