@a11y-oracle/focus-analyzer

中文文档
1.3.2发布于 2026/03/12MITTypeScriptES Module近 30 天下载 6255

Focus indicator CSS analysis (WCAG 2.4.12), tab order extraction, and keyboard trap detection

原始使用文档
文档目录8 节
  1. Installation
  2. Usage
  3. API Reference
  4. FocusAnalyzer
  5. Pure Utility Functions
  6. Types
  7. Exports
  8. Limitations

@a11y-oracle/focus-analyzer

Focus state analysis for accessibility testing. Provides visual focus indicator inspection, WCAG contrast ratio calculation, DOM tab order extraction, and keyboard trap detection.

This is a low-level building block used internally by @a11y-oracle/core-engine. Most users should use the Playwright or Cypress plugin instead.

Installation

npm install @a11y-oracle/focus-analyzer

Usage

import { FocusAnalyzer } from '@a11y-oracle/focus-analyzer';

const analyzer = new FocusAnalyzer(cdpSession);

// Analyze the focus indicator on the currently focused element
const indicator = await analyzer.getFocusIndicator();
console.log(indicator.isVisible);     // true
console.log(indicator.contrastRatio); // 12.63
console.log(indicator.meetsWCAG_AA);  // true (visible + contrast >= 3.0)
console.log(indicator.outlineColor);  // "rgb(0, 95, 204)"
console.log(indicator.outlineWidth);  // "3px"

// Extract all tabbable elements in DOM tab order
const entries = await analyzer.getTabOrder();
entries.forEach(e => {
  console.log(`${e.index}: ${e.tag}#${e.id} (tabIndex=${e.tabIndex})`);
});

// Detect keyboard traps (WCAG 2.1.2)
const result = await analyzer.detectKeyboardTrap('#modal-container', 20);
if (result.isTrapped) {
  console.log('Focus is trapped!');
} else {
  console.log(`Focus escaped to: ${result.escapeElement?.tag}`);
}

API Reference

FocusAnalyzer

constructor(cdp: CDPSessionLike)

Create a new focus analyzer. Internally creates a KeyboardEngine for trap detection.

  • cdp — Any CDP-compatible session (uses the CDPSessionLike interface from @a11y-oracle/cdp-types).

getFocusIndicator(): Promise<FocusIndicator>

Analyze the visual focus indicator of the currently focused element.

Extracts computed CSS properties (outline, box-shadow, border-color, background-color) via Runtime.evaluate, then calculates the contrast ratio of the focus indicator against the background.

Returns a default "not visible" indicator if no element has focus.

Visibility detection:

  • An element has a visible outline if outline-width is not 0px and the outline color has a non-zero alpha channel (detects both the transparent keyword and rgba(0, 0, 0, 0) which Chrome reports for transparent outlines)
  • An element has a visible box-shadow if box-shadow is not none

Contrast calculation:

  • For outlines: contrast ratio between outline-color and background-color
  • For box-shadows: extracts all colors from the box-shadow value, filters out transparent ones, and uses the outermost visible color (last non-transparent) for contrast calculation. This correctly handles Tailwind CSS multi-ring patterns where the decorative spacer ring appears first and the actual focus indicator ring appears last.
  • Returns contrastRatio: null if colors cannot be reliably parsed (e.g., gradients, complex color functions)

WCAG 2.4.12 AA compliance: meetsWCAG_AA is true when the indicator is visible AND the contrast ratio >= 3.0.

getTabOrder(): Promise<TabOrderEntry[]>

Extract all tabbable elements from the DOM in tab order.

Queries for focusable elements (a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]), then filters out:

  • Elements with tabIndex < 0
  • Hidden elements (display: none, visibility: hidden)
  • Elements with no layout (offsetParent === null)
  • Elements inside [inert] containers

Results are sorted by tabIndex value: positive tabIndex values first (ascending), then tabIndex=0 elements in DOM order.

detectKeyboardTrap(selector: string, maxTabs?: number): Promise<TraversalResult>

Detect whether focus is trapped inside a container (WCAG 2.1.2).

  1. Focuses the first tabbable element inside the container matching selector
  2. Presses Tab repeatedly (up to maxTabs, default 50)
  3. After each Tab, checks whether focus has left the container
  4. Returns immediately if focus escapes, or declares a trap if maxTabs is exhausted

Returns { isTrapped: false, tabCount: 0 } if the container doesn't exist or has no focusable elements.

Pure Utility Functions

The package also exports pure functions for color parsing and WCAG contrast calculation:

parseColor(css: string): RGBColor | null

Parse a CSS color string to an RGBColor object. Supports:

  • rgb(r, g, b) and rgba(r, g, b, a)
  • Hex colors: #RGB, #RRGGBB, #RRGGBBAA
  • transparent (returns { r: 0, g: 0, b: 0, a: 0 })

Returns null for unsupported formats (named colors, hsl(), color(), etc.).

srgbToLinear(channel: number): number

Convert an sRGB channel value (0-255) to linear light.

relativeLuminance(color: RGBColor): number

Calculate WCAG relative luminance: L = 0.2126*R + 0.7152*G + 0.0722*B

contrastRatio(color1: RGBColor, color2: RGBColor): number

Calculate the WCAG contrast ratio between two colors. Returns a value between 1 (identical) and 21 (black on white).

meetsAA(ratio: number): boolean

Check if a contrast ratio meets WCAG AA for focus indicators (>= 3.0).

Types

RGBColor

interface RGBColor {
  r: number; // 0-255
  g: number; // 0-255
  b: number; // 0-255
  a: number; // 0-1
}

FocusIndicator

Full focus indicator analysis:

interface FocusIndicator {
  isVisible: boolean;
  outline: string;          // Raw outline shorthand
  outlineColor: string;     // e.g. "rgb(0, 95, 204)"
  outlineWidth: string;     // e.g. "3px"
  outlineOffset: string;    // e.g. "0px"
  boxShadow: string;        // e.g. "0px 0px 0px 3px rgb(52, 152, 219)"
  borderColor: string;
  backgroundColor: string;
  contrastRatio: number | null;
  meetsWCAG_AA: boolean;
}

TabOrderEntry

interface TabOrderEntry {
  index: number;     // Position in tab order (0-based)
  tag: string;       // "BUTTON"
  id: string;
  textContent: string;
  tabIndex: number;
  role: string;
  rect: { x: number; y: number; width: number; height: number };
}

TabOrderReport

interface TabOrderReport {
  entries: TabOrderEntry[];
  totalCount: number;
}

TraversalResult

interface TraversalResult {
  isTrapped: boolean;                  // true if focus never escaped
  tabCount: number;                    // Total Tab presses attempted
  visitedElements: TabOrderEntry[];    // Elements that received focus
  escapeElement: TabOrderEntry | null; // First element outside container
}

Exports

export { FocusAnalyzer } from '@a11y-oracle/focus-analyzer';
export { parseColor } from '@a11y-oracle/focus-analyzer';
export { srgbToLinear, relativeLuminance, contrastRatio, meetsAA } from '@a11y-oracle/focus-analyzer';
export type { RGBColor, FocusIndicator, TabOrderEntry, TraversalResult, TabOrderReport } from '@a11y-oracle/focus-analyzer';

Limitations

  • Complex focus indicators — Gradients, CSS color-mix(), and other advanced color functions return contrastRatio: null because they cannot be reliably parsed into a single color value.
  • Keyboard trap detection — Tests with Tab key only. Intentional focus traps (e.g., modal dialogs) should be tested separately with Escape key navigation.
  • tabIndex ordering — The tab order extraction follows the standard algorithm (positive tabIndex first, then tabIndex=0 in DOM order), but doesn't account for Shadow DOM boundaries.

版本与发布记录

@a11y-oracle/focus-analyzer 共发布 10 个版本,首次发布于 2026/03/05;过去 12 个月发布了 10 个版本。

版本发布日期距今
1.3.2latest2026/03/127 个月前
1.3.12026/03/117 个月前
1.3.02026/03/068 个月前
1.2.02026/03/068 个月前
1.1.42026/03/068 个月前
1.1.32026/03/068 个月前

关于 @a11y-oracle/focus-analyzer 的常见问题

@a11y-oracle/focus-analyzer 是什么?

Focus indicator CSS analysis (WCAG 2.4.12), tab order extraction, and keyboard trap detection

如何安装 @a11y-oracle/focus-analyzer?

在项目目录运行 npm install @a11y-oracle/focus-analyzer,或使用 pnpm add / yarn add / bun add。

@a11y-oracle/focus-analyzer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@a11y-oracle/focus-analyzer 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@a11y-oracle/focus-analyzer 可以商用吗?

@a11y-oracle/focus-analyzer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@a11y-oracle/focus-analyzer 的下载量有多少?

根据 npm 官方下载统计,@a11y-oracle/focus-analyzer 在 2026/10/05 – 2026/11/03 这 30 天内被下载 6,255 次,日均约 209 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@a11y-oracle/focus-analyzer 还在维护吗?

最新版本 1.3.2 发布于 2026/03/12(7 个月前);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/03/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。