front/src/views/site/lib/site-panel-focus.ts
zzh 20ba37f1df
All checks were successful
Build and Deploy Front / deploy (push) Successful in 6m56s
feat: 官网首页意图缎带、联系信息与导航坞交互优化
收敛欢迎区意图入口与联系字段,优化波浪性能,并完善面板开关、焦点陷阱与无障碍属性。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 11:31:31 +08:00

50 lines
1.8 KiB
TypeScript

/** Focus helpers for homepage nav sheets (dialog). */
const FOCUSABLE =
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
let trapRoot: HTMLElement | null = null;
let onKey: ((e: KeyboardEvent) => void) | null = null;
function listFocusable(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => {
if (el.hasAttribute('disabled') || el.getAttribute('aria-hidden') === 'true') return false;
// offsetParent is null for fixed/absolute in some cases — also check client rects
const style = window.getComputedStyle(el);
if (style.visibility === 'hidden' || style.display === 'none') return false;
return el.getClientRects().length > 0;
});
}
export function activatePanelFocus(root: HTMLElement) {
deactivatePanelFocus();
trapRoot = root;
const closeBtn = root.querySelector<HTMLElement>(
'.ai-guide-panel__close, .ai-routes-panel__close, [data-panel-close]',
);
const nodes = listFocusable(root);
(closeBtn && nodes.includes(closeBtn) ? closeBtn : nodes[0])?.focus();
onKey = (e: KeyboardEvent) => {
if (e.key !== 'Tab' || !trapRoot) return;
const list = listFocusable(trapRoot);
if (list.length === 0) return;
const first = list[0];
const last = list[list.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
};
document.addEventListener('keydown', onKey, true);
}
export function deactivatePanelFocus() {
if (onKey) document.removeEventListener('keydown', onKey, true);
onKey = null;
trapRoot = null;
}