fix(qa): 第五轮系统性质量保障缺陷修复 + 单元/集成测试
安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号 令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、 同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。 CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器 richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、 about/contact/erp-upgrade 补 ISR revalidate 与路由映射。 UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入 effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/ 吞错改横幅/表单 label-aria 关联。 新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data 等模块及 tests-integration 真库集成层。
This commit is contained in:
1 parent
040951c0a3
commit
a366bd1400
224 files changed
+8938
-5579
No files matched your search
@@ -47,10 +47,14 @@ describe('useCountUp', () => {
|
||||
});
|
||||
|
||||
it('should reach end value after sufficient time', () => {
|
||||
renderHook(() => useCountUp({ end: 100, duration: 500 }));
|
||||
const { result } = renderHook(() =>
|
||||
useCountUp({ end: 100, duration: 500 })
|
||||
);
|
||||
|
||||
// Simulate animation frames progressing past the duration
|
||||
advanceFrames([0, 100, 200, 300, 400, 500, 600]);
|
||||
|
||||
expect(result.current).toBe(100);
|
||||
});
|
||||
|
||||
it('should have intermediate values during animation', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, jest } from '@jest/globals';
|
||||
import { renderHook, render, screen, fireEvent } from '@testing-library/react';
|
||||
import { useState } from 'react';
|
||||
import { useState, type ReactElement } from 'react';
|
||||
import { useFocusTrap } from './use-focus-trap';
|
||||
|
||||
describe('useFocusTrap', () => {
|
||||
@@ -628,4 +628,211 @@ describe('useFocusTrap', () => {
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Focusability Filter', () => {
|
||||
it('should not treat tabIndex={-1} buttons as focusable', () => {
|
||||
function NegativeTabIndexTrap() {
|
||||
const ref = useFocusTrap<HTMLDivElement>(true);
|
||||
return (
|
||||
<div ref={ref}>
|
||||
<button tabIndex={-1} data-testid="neg-btn">programmatic only</button>
|
||||
<button data-testid="real-btn">real</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<NegativeTabIndexTrap />);
|
||||
|
||||
// 挂载时的初始焦点必须跳过 tabindex=-1(选择器 union 里 button 也会命中它)
|
||||
expect(document.activeElement).toBe(screen.getByTestId('real-btn'));
|
||||
|
||||
const preventDefaultSpy = jest.spyOn(Event.prototype, 'preventDefault');
|
||||
screen.getByTestId('real-btn').focus();
|
||||
fireEvent.keyDown(document, { key: 'Tab' });
|
||||
// real-btn 是唯一的 first/last,Tab 应留在原地;旧实现会把焦点交给 -1 按钮
|
||||
expect(preventDefaultSpy).toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(screen.getByTestId('real-btn'));
|
||||
preventDefaultSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not treat input[type=hidden] as focusable', () => {
|
||||
function HiddenInputTrap() {
|
||||
const ref = useFocusTrap<HTMLDivElement>(true);
|
||||
return (
|
||||
<div ref={ref}>
|
||||
<input type="hidden" data-testid="hidden-input" />
|
||||
<button data-testid="after-hidden">visible</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<HiddenInputTrap />);
|
||||
|
||||
expect(document.activeElement).toBe(screen.getByTestId('after-hidden'));
|
||||
});
|
||||
|
||||
it('should not treat disabled controls as focusable', () => {
|
||||
function DisabledTrap() {
|
||||
const ref = useFocusTrap<HTMLDivElement>(true);
|
||||
return (
|
||||
<div ref={ref}>
|
||||
<button disabled data-testid="disabled-btn">disabled</button>
|
||||
<button data-testid="enabled-btn">enabled</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<DisabledTrap />);
|
||||
|
||||
expect(document.activeElement).toBe(screen.getByTestId('enabled-btn'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Escape Owner Contract', () => {
|
||||
function OwnerTrap({ isActive, onEscape }: { isActive: boolean; onEscape?: () => void }) {
|
||||
const ref = useFocusTrap<HTMLDivElement>(isActive, { onEscape });
|
||||
return (
|
||||
<div>
|
||||
<button data-testid="opener">opener</button>
|
||||
<button data-testid="elsewhere">elsewhere</button>
|
||||
<div ref={ref} data-testid="trap">
|
||||
<button data-testid="inside">inside</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function openWithOpener(rerender: (ui: ReactElement) => void, onEscape?: () => void) {
|
||||
(screen.getByTestId('opener') as HTMLElement).focus();
|
||||
rerender(<OwnerTrap isActive onEscape={onEscape} />);
|
||||
}
|
||||
|
||||
it('should notify the owner and keep focus inside the still-open trap on Escape', () => {
|
||||
const onEscape = jest.fn();
|
||||
const { rerender } = render(<OwnerTrap isActive={false} />);
|
||||
openWithOpener(rerender, onEscape);
|
||||
expect(document.activeElement).toBe(screen.getByTestId('inside'));
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
|
||||
expect(onEscape).toHaveBeenCalledTimes(1);
|
||||
// 焦点不得在 owner 还没关闭陷阱前逃到 trap 之外
|
||||
expect(document.activeElement).toBe(screen.getByTestId('inside'));
|
||||
});
|
||||
|
||||
it('should return focus to the opener once the owner actually closes the trap', () => {
|
||||
const onEscape = jest.fn();
|
||||
const { rerender } = render(<OwnerTrap isActive={false} />);
|
||||
openWithOpener(rerender, onEscape);
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
rerender(<OwnerTrap isActive={false} onEscape={onEscape} />);
|
||||
|
||||
expect(document.activeElement).toBe(screen.getByTestId('opener'));
|
||||
});
|
||||
|
||||
it('should preventDefault Escape when the owner handles it', () => {
|
||||
const preventDefaultSpy = jest.spyOn(Event.prototype, 'preventDefault');
|
||||
const onEscape = jest.fn();
|
||||
const { rerender } = render(<OwnerTrap isActive={false} />);
|
||||
openWithOpener(rerender, onEscape);
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
|
||||
expect(preventDefaultSpy).toHaveBeenCalled();
|
||||
preventDefaultSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should keep the legacy immediate focus return when no owner is registered', () => {
|
||||
const { rerender } = render(<OwnerTrap isActive={false} />);
|
||||
openWithOpener(rerender);
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
|
||||
expect(document.activeElement).toBe(screen.getByTestId('opener'));
|
||||
});
|
||||
|
||||
it('should not steal focus the user moved outside before the trap closed', () => {
|
||||
const onEscape = jest.fn();
|
||||
const { rerender } = render(<OwnerTrap isActive={false} />);
|
||||
openWithOpener(rerender, onEscape);
|
||||
|
||||
(screen.getByTestId('elsewhere') as HTMLElement).focus();
|
||||
rerender(<OwnerTrap isActive={false} onEscape={onEscape} />);
|
||||
|
||||
expect(document.activeElement).toBe(screen.getByTestId('elsewhere'));
|
||||
});
|
||||
|
||||
it('should restore focus to the opener when the trap container unmounts', () => {
|
||||
// 对应 header 抽屉:面板随状态卸载,焦点不能掉回 body。
|
||||
function ConditionalTrap() {
|
||||
const [active, setActive] = useState(false);
|
||||
const ref = useFocusTrap<HTMLDivElement>(active);
|
||||
return (
|
||||
<div>
|
||||
<button data-testid="opener" onClick={() => setActive((prev) => !prev)}>toggle</button>
|
||||
{active && (
|
||||
<div ref={ref} data-testid="trap">
|
||||
<button data-testid="inside">inside</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<ConditionalTrap />);
|
||||
(screen.getByTestId('opener') as HTMLElement).focus();
|
||||
|
||||
fireEvent.click(screen.getByTestId('opener'));
|
||||
expect(document.activeElement).toBe(screen.getByTestId('inside'));
|
||||
|
||||
fireEvent.click(screen.getByTestId('opener'));
|
||||
expect(screen.queryByTestId('trap')).not.toBeInTheDocument();
|
||||
expect(document.activeElement).toBe(screen.getByTestId('opener'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Nested Scroll Lock', () => {
|
||||
function NestedTraps({ secondActive }: { secondActive: boolean }) {
|
||||
const outerRef = useFocusTrap<HTMLDivElement>(true);
|
||||
const innerRef = useFocusTrap<HTMLDivElement>(secondActive);
|
||||
return (
|
||||
<>
|
||||
<div ref={outerRef} data-testid="outer">
|
||||
<button data-testid="outer-btn">outer</button>
|
||||
</div>
|
||||
{secondActive && (
|
||||
<div ref={innerRef} data-testid="inner">
|
||||
<button data-testid="inner-btn">inner</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
it('should keep the body locked when a nested trap deactivates first', () => {
|
||||
const { rerender, unmount } = render(<NestedTraps secondActive={false} />);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
rerender(<NestedTraps secondActive />);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
// 内层解锁不能把外层一起放开
|
||||
rerender(<NestedTraps secondActive={false} />);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
unmount();
|
||||
expect(document.body.style.overflow).toBe('unset');
|
||||
});
|
||||
|
||||
it('should restore the pre-existing overflow value rather than a hardcoded unset', () => {
|
||||
document.body.style.overflow = 'scroll';
|
||||
const { unmount } = render(<NestedTraps secondActive={false} />);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
unmount();
|
||||
expect(document.body.style.overflow).toBe('scroll');
|
||||
document.body.style.overflow = 'unset';
|
||||
});
|
||||
});
|
||||
});
|
||||
+101
-19
@@ -2,26 +2,81 @@
|
||||
|
||||
import { useEffect, useRef, useCallback } from 'react';
|
||||
|
||||
export function useFocusTrap<T extends HTMLElement>(isActive: boolean) {
|
||||
export interface UseFocusTrapOptions {
|
||||
/**
|
||||
* Escape 的归属回调。提供时 hook 只吞掉事件并通知调用方,焦点在陷阱停用后
|
||||
* (容器卸载 / isActive 转 false)才归还给唤起元素;未提供时保留旧行为:
|
||||
* 立即把焦点还给唤起元素。
|
||||
*/
|
||||
onEscape?: () => void;
|
||||
}
|
||||
|
||||
// `[tabindex]` 单独列出后由 isFocusable 排除负值,避免把 tabIndex={-1} 当可聚焦。
|
||||
const FOCUSABLE_SELECTOR = 'a[href], button, input, select, textarea, [tabindex]';
|
||||
|
||||
function isFocusable(el: HTMLElement): boolean {
|
||||
if (el.hasAttribute('disabled')) return false;
|
||||
if (el.getAttribute('type') === 'hidden') return false;
|
||||
const tabIndex = el.getAttribute('tabindex');
|
||||
if (tabIndex !== null && Number.parseInt(tabIndex, 10) < 0) return false;
|
||||
return el.offsetParent !== null;
|
||||
}
|
||||
|
||||
function isSentinel(el: Element | null): boolean {
|
||||
return !el || el === document.body || el === document.documentElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动锁栈:多个 trap 层叠时共享一次 overflow 覆写,
|
||||
* 只有最外层(栈空)解除时才恢复原始值。
|
||||
*/
|
||||
const scrollLock: { owners: symbol[]; previousOverflow: string | null } = {
|
||||
owners: [],
|
||||
previousOverflow: null,
|
||||
};
|
||||
|
||||
function acquireScrollLock(token: symbol): void {
|
||||
if (scrollLock.owners.length === 0) {
|
||||
scrollLock.previousOverflow = document.body.style.overflow;
|
||||
}
|
||||
scrollLock.owners.push(token);
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function releaseScrollLock(token: symbol): void {
|
||||
const index = scrollLock.owners.indexOf(token);
|
||||
if (index === -1) return;
|
||||
scrollLock.owners.splice(index, 1);
|
||||
if (scrollLock.owners.length === 0) {
|
||||
document.body.style.overflow = scrollLock.previousOverflow ?? '';
|
||||
scrollLock.previousOverflow = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function useFocusTrap<T extends HTMLElement>(
|
||||
isActive: boolean,
|
||||
options: UseFocusTrapOptions = {}
|
||||
) {
|
||||
const containerRef = useRef<T>(null);
|
||||
const previousActiveElement = useRef<HTMLElement | null>(null);
|
||||
const onEscapeRef = useRef<UseFocusTrapOptions['onEscape']>(options.onEscape);
|
||||
|
||||
useEffect(() => {
|
||||
onEscapeRef.current = options.onEscape;
|
||||
}, [options.onEscape]);
|
||||
|
||||
const getFocusableElements = useCallback(() => {
|
||||
if (!containerRef.current) return [];
|
||||
|
||||
const elements = containerRef.current.querySelectorAll<HTMLElement>(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
|
||||
return Array.from(elements).filter(
|
||||
(el) => !el.hasAttribute('disabled') && el.offsetParent !== null
|
||||
);
|
||||
|
||||
const elements = containerRef.current.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
|
||||
|
||||
return Array.from(elements).filter(isFocusable);
|
||||
}, []);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (!isActive || !containerRef.current) return;
|
||||
|
||||
|
||||
if (event.key === 'Tab') {
|
||||
const focusableElements = getFocusableElements();
|
||||
const firstElement = focusableElements[0];
|
||||
@@ -41,6 +96,13 @@ export function useFocusTrap<T extends HTMLElement>(isActive: boolean) {
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
const owner = onEscapeRef.current;
|
||||
if (owner) {
|
||||
// 关闭与否由调用方决定,焦点归还交给停用时的清理逻辑。
|
||||
event.preventDefault();
|
||||
owner();
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
previousActiveElement.current?.focus();
|
||||
}
|
||||
@@ -49,19 +111,39 @@ export function useFocusTrap<T extends HTMLElement>(isActive: boolean) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isActive) {
|
||||
previousActiveElement.current = document.activeElement as HTMLElement;
|
||||
|
||||
const focusableElements = getFocusableElements();
|
||||
focusableElements[0]?.focus();
|
||||
if (!isActive) return;
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
const container = containerRef.current;
|
||||
const opener = document.activeElement as HTMLElement | null;
|
||||
previousActiveElement.current = isSentinel(opener) ? null : opener;
|
||||
|
||||
const token = Symbol('focus-trap');
|
||||
let focusOwned = false;
|
||||
const trackFocus = () => {
|
||||
focusOwned = !!container && container.contains(document.activeElement);
|
||||
};
|
||||
|
||||
getFocusableElements()[0]?.focus();
|
||||
trackFocus();
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
document.addEventListener('focusin', trackFocus);
|
||||
acquireScrollLock(token);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'unset';
|
||||
document.removeEventListener('focusin', trackFocus);
|
||||
releaseScrollLock(token);
|
||||
|
||||
// 焦点仍归陷阱所有(含容器卸载后焦点被丢弃)才归还唤起元素;
|
||||
// 用户已把焦点移去别处时不抢占。
|
||||
const active = document.activeElement;
|
||||
const stillInTrap = !!container && container.contains(active);
|
||||
const target = previousActiveElement.current;
|
||||
if ((focusOwned || stillInTrap) && target && document.contains(target)) {
|
||||
target.focus();
|
||||
}
|
||||
previousActiveElement.current = null;
|
||||
};
|
||||
}, [isActive, handleKeyDown, getFocusableElements]);
|
||||
|
||||
|
||||
@@ -1,293 +0,0 @@
|
||||
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useKeyboardShortcuts } from './use-keyboard-shortcuts';
|
||||
|
||||
describe('useKeyboardShortcuts', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Mod+K Shortcut', () => {
|
||||
it('should call onSearch when Cmd+K is pressed', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'k', metaKey: true })
|
||||
);
|
||||
|
||||
expect(onSearch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should call onSearch when Ctrl+K is pressed', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'k', ctrlKey: true })
|
||||
);
|
||||
|
||||
expect(onSearch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should prevent default on Mod+K', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'k',
|
||||
metaKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
const preventDefaultSpy = jest.spyOn(event, 'preventDefault');
|
||||
|
||||
document.dispatchEvent(event);
|
||||
|
||||
expect(preventDefaultSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Alt+H Shortcut', () => {
|
||||
it('should call onNavigateHome when Alt+H is pressed', () => {
|
||||
const onNavigateHome = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onNavigateHome }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'h', altKey: true })
|
||||
);
|
||||
|
||||
expect(onNavigateHome).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should prevent default on Alt+H', () => {
|
||||
const onNavigateHome = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onNavigateHome }));
|
||||
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'h',
|
||||
altKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
const preventDefaultSpy = jest.spyOn(event, 'preventDefault');
|
||||
|
||||
document.dispatchEvent(event);
|
||||
|
||||
expect(preventDefaultSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Skip to Content (Tab from skip link)', () => {
|
||||
it('should call onSkipToContent when Tab is pressed from skip-to-content element', () => {
|
||||
const onSkipToContent = jest.fn();
|
||||
|
||||
// Simulate a skip-to-content link being focused
|
||||
const skipLink = document.createElement('a');
|
||||
skipLink.setAttribute('data-skip-to-content', 'true');
|
||||
document.body.appendChild(skipLink);
|
||||
|
||||
// Set it as the active element
|
||||
jest.spyOn(document, 'activeElement', 'get').mockReturnValue(skipLink);
|
||||
|
||||
renderHook(() => useKeyboardShortcuts({ onSkipToContent }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', shiftKey: false })
|
||||
);
|
||||
|
||||
expect(onSkipToContent).toHaveBeenCalledTimes(1);
|
||||
|
||||
document.body.removeChild(skipLink);
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Input Element Guard', () => {
|
||||
it('should not trigger shortcuts when event originates from input element', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
// Create an input element and dispatch event on it (event.target will be the input)
|
||||
const input = document.createElement('input');
|
||||
document.body.appendChild(input);
|
||||
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent('keydown', {
|
||||
key: 'k',
|
||||
metaKey: true,
|
||||
bubbles: true,
|
||||
})
|
||||
);
|
||||
|
||||
expect(onSearch).not.toHaveBeenCalled();
|
||||
document.body.removeChild(input);
|
||||
});
|
||||
|
||||
it('should not trigger shortcuts when event originates from textarea', () => {
|
||||
const onNavigateHome = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onNavigateHome }));
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
document.body.appendChild(textarea);
|
||||
|
||||
textarea.dispatchEvent(
|
||||
new KeyboardEvent('keydown', {
|
||||
key: 'h',
|
||||
altKey: true,
|
||||
bubbles: true,
|
||||
})
|
||||
);
|
||||
|
||||
expect(onNavigateHome).not.toHaveBeenCalled();
|
||||
document.body.removeChild(textarea);
|
||||
});
|
||||
|
||||
it('should not trigger shortcuts when event originates from select element', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
const select = document.createElement('select');
|
||||
document.body.appendChild(select);
|
||||
|
||||
select.dispatchEvent(
|
||||
new KeyboardEvent('keydown', {
|
||||
key: 'k',
|
||||
metaKey: true,
|
||||
bubbles: true,
|
||||
})
|
||||
);
|
||||
|
||||
expect(onSearch).not.toHaveBeenCalled();
|
||||
document.body.removeChild(select);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should work with no callbacks provided', () => {
|
||||
renderHook(() => useKeyboardShortcuts());
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'k', metaKey: true })
|
||||
);
|
||||
// Should not throw
|
||||
});
|
||||
|
||||
it('should not call callbacks for non-matching keys', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'a', metaKey: true })
|
||||
);
|
||||
|
||||
expect(onSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onSearch when Ctrl is pressed without K', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'j', ctrlKey: true })
|
||||
);
|
||||
|
||||
expect(onSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onNavigateHome when Alt is pressed without H', () => {
|
||||
const onNavigateHome = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onNavigateHome }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'g', altKey: true })
|
||||
);
|
||||
|
||||
expect(onNavigateHome).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onNavigateHome when H is pressed without Alt', () => {
|
||||
const onNavigateHome = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onNavigateHome }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'h', altKey: false })
|
||||
);
|
||||
|
||||
expect(onNavigateHome).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onSkipToContent when Tab is pressed without skip-to-content element', () => {
|
||||
const onSkipToContent = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSkipToContent }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', shiftKey: false })
|
||||
);
|
||||
|
||||
expect(onSkipToContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onSkipToContent when Shift+Tab is pressed from skip-to-content element', () => {
|
||||
const onSkipToContent = jest.fn();
|
||||
|
||||
const skipLink = document.createElement('a');
|
||||
skipLink.setAttribute('data-skip-to-content', 'true');
|
||||
document.body.appendChild(skipLink);
|
||||
jest.spyOn(document, 'activeElement', 'get').mockReturnValue(skipLink);
|
||||
|
||||
renderHook(() => useKeyboardShortcuts({ onSkipToContent }));
|
||||
|
||||
// Shift+Tab should not trigger skip-to-content (only Tab without shift)
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true })
|
||||
);
|
||||
|
||||
expect(onSkipToContent).not.toHaveBeenCalled();
|
||||
|
||||
document.body.removeChild(skipLink);
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should not call onSkipToContent when activeElement is null', () => {
|
||||
const onSkipToContent = jest.fn();
|
||||
jest.spyOn(document, 'activeElement', 'get').mockReturnValue(null);
|
||||
|
||||
renderHook(() => useKeyboardShortcuts({ onSkipToContent }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', shiftKey: false })
|
||||
);
|
||||
|
||||
// When activeElement is null, optional chaining prevents crash
|
||||
expect(onSkipToContent).not.toHaveBeenCalled();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should not call onSearch when neither metaKey nor ctrlKey is pressed', () => {
|
||||
const onSearch = jest.fn();
|
||||
renderHook(() => useKeyboardShortcuts({ onSearch }));
|
||||
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'k', metaKey: false, ctrlKey: false })
|
||||
);
|
||||
|
||||
expect(onSearch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Lifecycle', () => {
|
||||
it('should add keydown listener on mount', () => {
|
||||
const spy = jest.spyOn(document, 'addEventListener');
|
||||
renderHook(() => useKeyboardShortcuts());
|
||||
expect(spy).toHaveBeenCalledWith('keydown', expect.any(Function));
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should remove keydown listener on unmount', () => {
|
||||
const spy = jest.spyOn(document, 'removeEventListener');
|
||||
const { unmount } = renderHook(() => useKeyboardShortcuts());
|
||||
unmount();
|
||||
expect(spy).toHaveBeenCalledWith('keydown', expect.any(Function));
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useCallback } from 'react';
|
||||
|
||||
interface KeyboardShortcutsProps {
|
||||
onSearch?: () => void;
|
||||
onNavigateHome?: () => void;
|
||||
onSkipToContent?: () => void;
|
||||
}
|
||||
|
||||
export function useKeyboardShortcuts({
|
||||
onSearch,
|
||||
onNavigateHome,
|
||||
onSkipToContent,
|
||||
}: KeyboardShortcutsProps = {}) {
|
||||
const handleKeyDown = useCallback((event: KeyboardEvent) => {
|
||||
if (event.target instanceof HTMLInputElement ||
|
||||
event.target instanceof HTMLTextAreaElement ||
|
||||
event.target instanceof HTMLSelectElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isModKey = event.metaKey || event.ctrlKey;
|
||||
|
||||
switch (true) {
|
||||
case isModKey && event.key === 'k':
|
||||
event.preventDefault();
|
||||
onSearch?.();
|
||||
break;
|
||||
case event.altKey && event.key === 'h':
|
||||
event.preventDefault();
|
||||
onNavigateHome?.();
|
||||
break;
|
||||
case event.key === 'Tab' && !event.shiftKey && (document.activeElement?.getAttribute('data-skip-to-content') === 'true' || document.activeElement?.getAttribute('data-skip-to-content')):
|
||||
event.preventDefault();
|
||||
onSkipToContent?.();
|
||||
break;
|
||||
}
|
||||
}, [onSearch, onNavigateHome, onSkipToContent]);
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleKeyDown]);
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import { render, screen, act, fireEvent } from '@testing-library/react';
|
||||
|
||||
// ─── Mocks ───────────────────────────────────────────────────────────────
|
||||
|
||||
const mockPush = jest.fn();
|
||||
|
||||
jest.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: jest.fn() }),
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}));
|
||||
|
||||
jest.mock('framer-motion', () => ({
|
||||
@@ -271,6 +273,62 @@ describe('SwipeNavigation', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests: SwipeNavigation · edge-swipe 手势真的能触发(P-1) ───────────
|
||||
|
||||
describe('SwipeNavigation · edge-swipe gestures', () => {
|
||||
function swipe(fromX: number, toX: number) {
|
||||
fireEvent.touchStart(document.body, {
|
||||
touches: [{ clientX: fromX, clientY: 0, identifier: 0 }],
|
||||
});
|
||||
fireEvent.touchMove(document.body, {
|
||||
touches: [{ clientX: toX, clientY: 0, identifier: 0 }],
|
||||
});
|
||||
fireEvent.touchEnd(document.body);
|
||||
}
|
||||
|
||||
it('right swipe started at the left edge of the page pushes prevRoute', async () => {
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true });
|
||||
const { SwipeNavigation } = await import('./use-swipe-gesture');
|
||||
render(<SwipeNavigation prevRoute="/prev" nextRoute="/next" />);
|
||||
mockPush.mockClear();
|
||||
|
||||
swipe(5, 600);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(mockPush).toHaveBeenCalledWith('/prev');
|
||||
});
|
||||
|
||||
it('left swipe started at the right edge of the page pushes nextRoute', async () => {
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true });
|
||||
const { SwipeNavigation } = await import('./use-swipe-gesture');
|
||||
render(<SwipeNavigation prevRoute="/prev" nextRoute="/next" />);
|
||||
mockPush.mockClear();
|
||||
|
||||
swipe(1019, 400);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(mockPush).toHaveBeenCalledWith('/next');
|
||||
});
|
||||
|
||||
it('keeps the edge threshold: a middle-of-screen touch never swipes', async () => {
|
||||
Object.defineProperty(window, 'innerWidth', { value: 1024, configurable: true });
|
||||
const { SwipeNavigation } = await import('./use-swipe-gesture');
|
||||
render(<SwipeNavigation prevRoute="/prev" nextRoute="/next" />);
|
||||
mockPush.mockClear();
|
||||
|
||||
swipe(500, 900);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(mockPush).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests: PullToRefresh ────────────────────────────────────────────────
|
||||
|
||||
describe('PullToRefresh', () => {
|
||||
|
||||
@@ -103,8 +103,10 @@ export function useSwipeGesture(options: SwipeGestureOptions = {}) {
|
||||
}, [onSwipeLeft, onSwipeRight]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = containerRef.current || document;
|
||||
|
||||
// 挂到 document:调用方的 containerRef 容器是无尺寸装饰层,触摸永远无法从中冒泡;
|
||||
// 命中区域仍由 handleTouchStart 的 edgeSize 阈值收窄。
|
||||
const element = document;
|
||||
|
||||
element.addEventListener('touchstart', handleTouchStart, { passive: true });
|
||||
element.addEventListener('touchmove', handleTouchMove, { passive: false });
|
||||
element.addEventListener('touchend', handleTouchEnd, { passive: true });
|
||||
@@ -234,13 +236,13 @@ export function SwipeNavigation({
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-4 mt-2">
|
||||
{prevRoute && (
|
||||
<div className="flex items-center gap-1 text-[var(--color-brand)]">
|
||||
<div className="flex items-center gap-1 text-brand-ink">
|
||||
<ArrowLeft className="w-3 h-3" />
|
||||
<span className="text-xs">{prevLabel}</span>
|
||||
</div>
|
||||
)}
|
||||
{nextRoute && (
|
||||
<div className="flex items-center gap-1 text-[var(--color-brand)]">
|
||||
<div className="flex items-center gap-1 text-brand-ink">
|
||||
<span className="text-xs">{nextLabel}</span>
|
||||
<ArrowRight className="w-3 h-3" />
|
||||
</div>
|
||||
@@ -332,13 +334,13 @@ export function PullToRefresh({ onRefresh, children, className }: PullToRefreshP
|
||||
>
|
||||
<motion.div
|
||||
animate={{ rotate: isRefreshing ? 360 : pullDistance > 60 ? 180 : 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
transition={{ duration: 0.28 }}
|
||||
>
|
||||
<svg
|
||||
className={cn(
|
||||
'w-6 h-6 transition-colors',
|
||||
pullDistance > 60
|
||||
? 'text-[var(--color-brand)]'
|
||||
? 'text-brand-ink'
|
||||
: 'text-[var(--color-text-subtle)]'
|
||||
)}
|
||||
fill="none"
|
||||
|
||||
Reference in new issue
Block a user