Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 | 25x 25x 3x 3x 418x 417x 1x 2x 2x 2x 1x 2x 4x 4x 1x 4x 1x 4x 1x 4x 1x 4x 2x 2x 1x 2x 2x 2x 1x 2x 2x 2x 2x 1x 2x 4x 2x 2x 7x 7x 7x 6x 2x 2x 4x 2x 2x 1x 1x 1x 7x 1x 1x 6x 1x 1x 7x 5x 3x 3x 25x 25x 25x 11x 6x 6x 6x 6x 6x 6x 6x 6x 6x 11x 11x 11x 11x 11x 9x 9x 11x 16x 16x 11x 7x 11x 11x 2x 2x 2x 11x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 36x 36x 12x 24x 24x | /**
* Accessibility utility functions for WCAG 2.1 AA compliance
*
* This module provides helper functions to enhance accessibility across the application,
* including ARIA attributes, keyboard navigation, and screen reader support.
*
* @module utils/accessibility
*/
import { SecurityLevel } from '../types/cia';
/**
* ARIA roles for common components
*/
export const ARIA_ROLES = {
NAVIGATION: 'navigation',
MAIN: 'main',
COMPLEMENTARY: 'complementary',
REGION: 'region',
ARTICLE: 'article',
BANNER: 'banner',
CONTENTINFO: 'contentinfo',
SEARCH: 'search',
TABLIST: 'tablist',
TAB: 'tab',
TABPANEL: 'tabpanel',
BUTTON: 'button',
LINK: 'link',
LIST: 'list',
LISTITEM: 'listitem',
ALERT: 'alert',
STATUS: 'status',
PROGRESSBAR: 'progressbar',
} as const;
/**
* ARIA live region politeness levels
*/
export const ARIA_LIVE = {
OFF: 'off',
POLITE: 'polite',
ASSERTIVE: 'assertive',
} as const;
/**
* Create an accessible label for a security level
*
* Generates WCAG-compliant ARIA labels for security level selectors and displays,
* ensuring screen readers properly announce the component and its current level.
*
* @param level - The security level (None, Low, Moderate, High, Very High)
* @param component - The CIA component (availability, integrity, confidentiality)
* @returns An accessible label string formatted for screen readers
*
* @example
* ```typescript
* // Availability level label
* getSecurityLevelAriaLabel('High', 'availability')
* // 'Availability security level: High'
*
* // Integrity level label
* getSecurityLevelAriaLabel('Moderate', 'integrity')
* // 'Integrity security level: Moderate'
*
* // Confidentiality level label
* getSecurityLevelAriaLabel('Very High', 'confidentiality')
* // 'Confidentiality security level: Very High'
*
* // Usage in component
* <select aria-label={getSecurityLevelAriaLabel(level, 'availability')}>
* {levels.map(l => <option key={l} value={l}>{l}</option>)}
* </select>
* ```
*/
export function getSecurityLevelAriaLabel(
level: SecurityLevel,
component: 'availability' | 'integrity' | 'confidentiality'
): string {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
return `${componentName} security level: ${level}`;
}
/**
* Create an accessible description for a widget
*
* Generates descriptive ARIA descriptions for widgets to provide context
* to screen reader users about the widget's purpose and content.
*
* @param widgetType - Type of widget (e.g., 'Security Metrics', 'Risk Analysis')
* @param description - Optional additional description
* @returns An accessible description string
*
* @example
* ```typescript
* // Without additional description
* getWidgetAriaDescription('Security Metrics')
* // 'Security Metrics widget'
*
* // With additional description
* getWidgetAriaDescription('Risk Analysis', 'Shows current risk levels')
* // 'Risk Analysis widget. Shows current risk levels'
*
* getWidgetAriaDescription('Cost Estimation', 'CAPEX and OPEX breakdown')
* // 'Cost Estimation widget. CAPEX and OPEX breakdown'
*
* // Usage in component
* <div
* role="region"
* aria-label={widgetTitle}
* aria-describedby="widget-desc"
* >
* <span id="widget-desc" className="sr-only">
* {getWidgetAriaDescription(widgetType, description)}
* </span>
* {widgetContent}
* </div>
* ```
*/
export function getWidgetAriaDescription(
widgetType: string,
description?: string
): string {
if (description) {
return `${widgetType} widget. ${description}`;
}
return `${widgetType} widget`;
}
/**
* Generate ARIA props for a tab component
*
* Creates a complete set of ARIA properties for tab controls following
* WAI-ARIA Authoring Practices for tab patterns. Ensures proper keyboard
* navigation and screen reader announcements.
*
* @param id - Unique tab identifier
* @param isSelected - Whether the tab is currently selected/active
* @param controls - ID of the tabpanel this tab controls
* @returns ARIA props object with role, selection state, controls reference, and keyboard focus
*
* @example
* ```typescript
* // Selected tab
* const selectedTabProps = getTabAriaProps('tab-security', true, 'panel-security');
* // {
* // role: 'tab',
* // 'aria-selected': true,
* // 'aria-controls': 'panel-security',
* // id: 'tab-security',
* // tabIndex: 0
* // }
*
* // Unselected tab
* const unselectedTabProps = getTabAriaProps('tab-compliance', false, 'panel-compliance');
* // {
* // role: 'tab',
* // 'aria-selected': false,
* // 'aria-controls': 'panel-compliance',
* // id: 'tab-compliance',
* // tabIndex: -1
* // }
*
* // Usage in component
* <div role="tablist">
* {tabs.map(tab => (
* <button
* key={tab.id}
* {...getTabAriaProps(tab.id, tab.id === selectedTab, `panel-${tab.id}`)}
* onClick={() => selectTab(tab.id)}
* >
* {tab.label}
* </button>
* ))}
* </div>
* ```
*/
export function getTabAriaProps(
id: string,
isSelected: boolean,
controls: string
): {
role: string;
'aria-selected': boolean;
'aria-controls': string;
id: string;
tabIndex: number;
} {
return {
role: ARIA_ROLES.TAB,
'aria-selected': isSelected,
'aria-controls': controls,
id,
tabIndex: isSelected ? 0 : -1,
};
}
/**
* Generate ARIA props for a tab panel
*
* @param id - Panel identifier
* @param labelledBy - ID of the tab that labels this panel
* @param isHidden - Whether the panel is currently hidden
* @returns ARIA props object
*/
export function getTabPanelAriaProps(
id: string,
labelledBy: string,
isHidden: boolean
): {
role: string;
id: string;
'aria-labelledby': string;
hidden?: boolean;
tabIndex: number;
} {
const props: {
role: string;
id: string;
'aria-labelledby': string;
hidden?: boolean;
tabIndex: number;
} = {
role: ARIA_ROLES.TABPANEL,
id,
'aria-labelledby': labelledBy,
tabIndex: 0,
};
if (isHidden) {
props.hidden = true;
}
return props;
}
/**
* Generate ARIA props for a button
*
* @param label - Button label
* @param isPressed - Whether button is in pressed state (for toggle buttons)
* @param isExpanded - Whether button controls expanded content
* @param controls - ID of element controlled by this button
* @returns ARIA props object
*/
export function getButtonAriaProps(
label: string,
options?: {
isPressed?: boolean;
isExpanded?: boolean;
controls?: string;
describedBy?: string;
}
): {
'aria-label': string;
'aria-pressed'?: boolean;
'aria-expanded'?: boolean;
'aria-controls'?: string;
'aria-describedby'?: string;
} {
const props: {
'aria-label': string;
'aria-pressed'?: boolean;
'aria-expanded'?: boolean;
'aria-controls'?: string;
'aria-describedby'?: string;
} = {
'aria-label': label,
};
if (options?.isPressed !== undefined) {
props['aria-pressed'] = options.isPressed;
}
if (options?.isExpanded !== undefined) {
props['aria-expanded'] = options.isExpanded;
}
if (options?.controls) {
props['aria-controls'] = options.controls;
}
if (options?.describedBy) {
props['aria-describedby'] = options.describedBy;
}
return props;
}
/**
* Generate ARIA props for a select/dropdown component
*
* @param label - Select label
* @param value - Current value
* @param required - Whether selection is required
* @returns ARIA props object
*/
export function getSelectAriaProps(
label: string,
value: string,
required = false
): {
'aria-label': string;
'aria-required'?: boolean;
'aria-describedby'?: string;
} {
const props: {
'aria-label': string;
'aria-required'?: boolean;
'aria-describedby'?: string;
} = {
'aria-label': label,
};
if (required) {
props['aria-required'] = true;
}
return props;
}
/**
* Generate ARIA props for a progress bar or meter
*
* @param label - Progress bar label
* @param valuenow - Current value
* @param valuemin - Minimum value
* @param valuemax - Maximum value
* @param valuetext - Textual representation of value
* @returns ARIA props object
*/
export function getProgressAriaProps(
label: string,
valuenow: number,
valuemin = 0,
valuemax = 100,
valuetext?: string
): {
role: string;
'aria-label': string;
'aria-valuenow': number;
'aria-valuemin': number;
'aria-valuemax': number;
'aria-valuetext'?: string;
} {
const props: {
role: string;
'aria-label': string;
'aria-valuenow': number;
'aria-valuemin': number;
'aria-valuemax': number;
'aria-valuetext'?: string;
} = {
role: ARIA_ROLES.PROGRESSBAR,
'aria-label': label,
'aria-valuenow': valuenow,
'aria-valuemin': valuemin,
'aria-valuemax': valuemax,
};
if (valuetext) {
props['aria-valuetext'] = valuetext;
}
return props;
}
/**
* Generate ARIA props for a status/live region
*
* @param message - Status message
* @param politeness - ARIA live politeness level
* @returns ARIA props object
*/
export function getStatusAriaProps(
message: string,
politeness: keyof typeof ARIA_LIVE = 'POLITE'
): {
role: string;
'aria-live': string;
'aria-atomic': boolean;
} {
return {
role: ARIA_ROLES.STATUS,
'aria-live': ARIA_LIVE[politeness],
'aria-atomic': true,
};
}
/**
* Generate ARIA props for a chart/visualization
*
* @param label - Chart label
* @param description - Detailed chart description
* @param descriptionId - ID of element containing description
* @returns ARIA props object
*/
export function getChartAriaProps(
label: string,
description: string,
descriptionId?: string
): {
'aria-label': string;
'aria-describedby'?: string;
role: string;
} {
const props: {
'aria-label': string;
'aria-describedby'?: string;
role: string;
} = {
'aria-label': label,
role: 'img',
};
if (descriptionId) {
props['aria-describedby'] = descriptionId;
}
return props;
}
/**
* Check if an element should be keyboard focusable
*
* @param isInteractive - Whether element is interactive
* @param isDisabled - Whether element is disabled
* @returns tabIndex value (-1, 0, or undefined)
*/
export function getTabIndex(
isInteractive: boolean,
isDisabled = false
): number | undefined {
if (isDisabled) {
return -1;
}
return isInteractive ? 0 : undefined;
}
/**
* Handle keyboard navigation for arrow keys in a list or grid
*
* @param event - Keyboard event
* @param currentIndex - Current focused item index
* @param totalItems - Total number of items
* @param onIndexChange - Callback when index changes
* @param orientation - List orientation (horizontal or vertical)
*/
export function handleArrowKeyNavigation(
event: React.KeyboardEvent,
currentIndex: number,
totalItems: number,
onIndexChange: (newIndex: number) => void,
orientation: 'horizontal' | 'vertical' = 'vertical'
): void {
const { key } = event;
let newIndex = currentIndex;
if (orientation === 'vertical') {
if (key === 'ArrowDown') {
newIndex = Math.min(currentIndex + 1, totalItems - 1);
event.preventDefault();
} else if (key === 'ArrowUp') {
newIndex = Math.max(currentIndex - 1, 0);
event.preventDefault();
}
} else {
if (key === 'ArrowRight') {
newIndex = Math.min(currentIndex + 1, totalItems - 1);
event.preventDefault();
E} else if (key === 'ArrowLeft') {
newIndex = Math.max(currentIndex - 1, 0);
event.preventDefault();
}
}
if (key === 'Home') {
newIndex = 0;
event.preventDefault();
} else if (key === 'End') {
newIndex = totalItems - 1;
event.preventDefault();
}
if (newIndex !== currentIndex) {
onIndexChange(newIndex);
}
}
/**
* Generate accessible name for a metric or data point
*
* @param label - Metric label
* @param value - Metric value
* @param unit - Optional unit (%, $, etc.)
* @returns Accessible description string
*/
export function getMetricAccessibleName(
label: string,
value: string | number,
unit?: string
): string {
const unitString = unit ? ` ${unit}` : '';
return `${label}: ${value}${unitString}`;
}
// Singleton live region for screen reader announcements
let liveRegionElement: HTMLDivElement | null = null;
let cleanupTimeout: ReturnType<typeof setTimeout> | null = null;
const pendingTimeouts: Array<ReturnType<typeof setTimeout>> = [];
/**
* Get or create the singleton live region element
*/
function getLiveRegion(): HTMLDivElement {
if (!liveRegionElement || !document.body.contains(liveRegionElement)) {
liveRegionElement = document.createElement('div');
liveRegionElement.setAttribute('aria-atomic', 'true');
liveRegionElement.setAttribute('class', 'sr-only');
liveRegionElement.style.position = 'absolute';
liveRegionElement.style.left = '-10000px';
liveRegionElement.style.width = '1px';
liveRegionElement.style.height = '1px';
liveRegionElement.style.overflow = 'hidden';
document.body.appendChild(liveRegionElement);
}
return liveRegionElement;
}
/**
* Announce a message to screen readers using ARIA live region
* Uses a singleton live region to prevent duplicate announcements
*
* @param message - Message to announce
* @param politeness - ARIA live politeness level
*/
export function announceToScreenReader(
message: string,
politeness: 'polite' | 'assertive' = 'polite'
): void {
const liveRegion = getLiveRegion();
// Update politeness level if changed
liveRegion.setAttribute('aria-live', politeness);
// Clear existing content and cancel ALL pending timeouts to prevent accumulation
liveRegion.textContent = '';
if (cleanupTimeout) {
clearTimeout(cleanupTimeout);
cleanupTimeout = null;
}
// Clear all pending timeouts from rapid successive calls
while (pendingTimeouts.length > 0) {
const timeout = pendingTimeouts.pop();
Eif (timeout) clearTimeout(timeout);
}
// Delay to ensure screen readers detect the change
const messageTimeout = setTimeout(() => {
liveRegion.textContent = message;
}, 100);
pendingTimeouts.push(messageTimeout);
// Schedule cleanup after announcement (but keep the element for reuse)
cleanupTimeout = setTimeout(() => {
liveRegion.textContent = '';
// Clear completed timeout from pending array
const index = pendingTimeouts.indexOf(messageTimeout);
Eif (index > -1) pendingTimeouts.splice(index, 1);
}, 3000);
pendingTimeouts.push(cleanupTimeout);
}
/**
* Check if element has sufficient color contrast
* Note: This is a simplified check. Use dedicated tools for comprehensive testing.
*
* @param foreground - Foreground color (hex)
* @param background - Background color (hex)
* @param isLargeText - Whether text is large (18pt+ or 14pt+ bold)
* @returns Whether contrast meets WCAG AA standards
* @throws Error if colors are invalid hex values
*/
export function meetsContrastRequirement(
foreground: string,
background: string,
isLargeText = false
): boolean {
// Validate hex colors
const fgRgb = hexToRgb(foreground);
const bgRgb = hexToRgb(background);
Iif (!fgRgb || !bgRgb) {
console.warn(
`Invalid hex color provided to meetsContrastRequirement: foreground=${foreground}, background=${background}`
);
return false; // Fail validation for invalid colors
}
const requiredRatio = isLargeText ? 3 : 4.5;
const ratio = calculateContrastRatio(foreground, background);
return ratio >= requiredRatio;
}
/**
* Calculate color contrast ratio between two colors
*
* @param color1 - First color (hex)
* @param color2 - Second color (hex)
* @returns Contrast ratio (1-21)
*/
function calculateContrastRatio(color1: string, color2: string): number {
const l1 = getRelativeLuminance(color1);
const l2 = getRelativeLuminance(color2);
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
/**
* Get relative luminance of a color
*
* @param hex - Hex color string
* @returns Relative luminance (0-1)
*/
function getRelativeLuminance(hex: string): number {
const rgb = hexToRgb(hex);
Iif (!rgb) return 0;
const [r, g, b] = rgb.map((val) => {
const sRGB = val / 255;
return sRGB <= 0.03928 ? sRGB / 12.92 : Math.pow((sRGB + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/**
* Convert hex color to RGB
*
* @param hex - Hex color string
* @returns RGB array or null if invalid
*/
function hexToRgb(hex: string): [number, number, number] | null {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]
: null;
}
|