All files / utils accessibility.ts

28.67% Statements 41/143
13.48% Branches 12/89
40% Functions 10/25
29.28% Lines 41/140

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                                                                                      4x   4x       2x 2x 2x       1x 1x 1x                 1x 1x 1x                                                                               733x 733x                           4x                                             729x   729x 698x           31x 31x   729x                             782x                                         9x 9x     9x 18x 54x 54x       18x     9x 9x     9x 9x 9x                                     1x 1x                     1x 1x     1x                                       4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1x       1x                                                                                                                                                                    
/**
 * Accessibility utility functions for WCAG 2.1 Level AA compliance
 * Provides keyboard navigation, focus management, color contrast checking,
 * and screen reader support utilities
 * 
 * @module utils/accessibility
 * @category Accessibility
 * @korean 접근성 유틸리티
 */
 
import React from 'react';
import {
  KeyboardActions,
  FocusIndicatorStyle,
  ScreenReaderAnnouncement,
  ColorContrastConfig,
  WCAGComplianceResult,
  WCAGLevel,
  AriaAttributes,
  createBilingualLabel,
} from '../types/AccessibilityTypes';
import { KOREAN_COLORS } from '../types/constants';
 
/**
 * Handle keyboard navigation events with WCAG compliance
 * Supports Tab, Enter, Space, Escape, Arrow keys, Home, End
 * 
 * @param event - Keyboard event
 * @param actions - Actions to perform for different keys
 * 
 * @example
 * ```tsx
 * <div onKeyDown={(e) => handleKeyboardNav(e, {
 *   onActivate: () => handleClick(),
 *   onCancel: () => handleClose(),
 *   onNavigate: (dir) => handleMove(dir),
 * })}>
 * ```
 */
export function handleKeyboardNav(
  event: KeyboardEvent,
  actions: KeyboardActions
): void {
  const { key, shiftKey } = event;
 
  switch (key) {
    case 'Enter':
    case ' ':
      // Activate element (button, link, etc.)
      event.preventDefault();
      actions.onActivate?.();
      break;
 
    case 'Escape':
      // Cancel or close action
      event.preventDefault();
      actions.onCancel?.();
      break;
 
    case 'Tab':
      // Tab navigation (forward or backward with Shift)
      actions.onTab?.(shiftKey);
      break;
 
    case 'ArrowUp':
      // Navigate up
      event.preventDefault();
      actions.onNavigate?.('up');
      break;
 
    case 'ArrowDown':
      // Navigate down
      event.preventDefault();
      actions.onNavigate?.('down');
      break;
 
    case 'ArrowLeft':
      // Navigate left
      event.preventDefault();
      actions.onNavigate?.('left');
      break;
 
    case 'ArrowRight':
      // Navigate right
      event.preventDefault();
      actions.onNavigate?.('right');
      break;
 
    case 'Home':
      // Jump to start
      event.preventDefault();
      actions.onJump?.('start');
      break;
 
    case 'End':
      // Jump to end
      event.preventDefault();
      actions.onJump?.('end');
      break;
  }
}
 
/**
 * Get default focus indicator style (WCAG 2.1 Level AA compliant)
 * Uses 2px solid outline with high contrast cyan color
 * Computed lazily to avoid initialization order dependencies
 */
function getDefaultFocusStyle(): FocusIndicatorStyle {
  const rgb = hexToRgb(KOREAN_COLORS.PRIMARY_CYAN);
  return {
    outlineWidth: 2,
    outlineColor: KOREAN_COLORS.PRIMARY_CYAN,
    outlineOffset: 2,
    outlineStyle: 'solid',
    boxShadow: `0 0 0 2px rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.5)`,
    transitionDuration: 0.2,
  };
}
 
/**
 * Default focus indicator style (WCAG 2.1 Level AA compliant)
 * @deprecated Use getDefaultFocusStyle() instead for lazy computation
 */
export const DEFAULT_FOCUS_STYLE: FocusIndicatorStyle = getDefaultFocusStyle();
 
/**
 * Get focus indicator CSS style object
 * 
 * @param isFocused - Whether element is currently focused
 * @param customStyle - Optional custom focus style overrides
 * @returns CSS style object for focus indicator
 * 
 * @example
 * ```tsx
 * const [isFocused, setIsFocused] = useState(false);
 * <button
 *   style={getFocusStyle(isFocused)}
 *   onFocus={() => setIsFocused(true)}
 *   onBlur={() => setIsFocused(false)}
 * >
 * ```
 */
export function getFocusStyle(
  isFocused: boolean,
  customStyle?: Partial<FocusIndicatorStyle>
): React.CSSProperties {
  const defaultStyle = getDefaultFocusStyle();
  
  if (!isFocused) {
    return {
      // Preserve browser default focus indicator instead of 'none'
      transition: `all ${defaultStyle.transitionDuration}s ease`,
    };
  }
 
  const style = { ...defaultStyle, ...customStyle };
  const rgb = hexToRgb(style.outlineColor ?? KOREAN_COLORS.PRIMARY_CYAN);
 
  return {
    outline: `${style.outlineWidth}px ${style.outlineStyle} rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,
    outlineOffset: `${style.outlineOffset}px`,
    boxShadow: style.boxShadow ?? `0 0 0 2px rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.5)`,
    transition: `all ${style.transitionDuration}s ease`,
  };
}
 
/**
 * Convert hex color to RGB components
 * 
 * @param hex - Hex color code (0xRRGGBB)
 * @returns RGB components
 */
export function hexToRgb(hex: number): { r: number; g: number; b: number } {
  return {
    r: (hex >> 16) & 255,
    g: (hex >> 8) & 255,
    b: hex & 255,
  };
}
 
/**
 * Calculate contrast ratio between two colors (WCAG 2.1)
 * 
 * @param foreground - Foreground color (hex)
 * @param background - Background color (hex)
 * @returns Contrast ratio (1-21)
 * 
 * @example
 * ```typescript
 * const ratio = getContrastRatio(KOREAN_COLORS.TEXT_PRIMARY, KOREAN_COLORS.UI_BACKGROUND_DARK);
 * console.log(`Contrast ratio: ${ratio.toFixed(2)}:1`); // Should be >= 4.5:1 for WCAG AA
 * ```
 */
export function getContrastRatio(foreground: number, background: number): number {
  const fg = hexToRgb(foreground);
  const bg = hexToRgb(background);
 
  // Calculate relative luminance (WCAG formula)
  const getLuminance = (r: number, g: number, b: number): number => {
    const [rs, gs, bs] = [r, g, b].map((c) => {
      const sRGB = c / 255;
      return sRGB <= 0.03928
        ? sRGB / 12.92
        : Math.pow((sRGB + 0.055) / 1.055, 2.4);
    });
    return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
  };
 
  const l1 = getLuminance(fg.r, fg.g, fg.b);
  const l2 = getLuminance(bg.r, bg.g, bg.b);
 
  // Contrast ratio formula
  const lighter = Math.max(l1, l2);
  const darker = Math.min(l1, l2);
  return (lighter + 0.05) / (darker + 0.05);
}
 
/**
 * Check if color combination meets WCAG contrast requirements
 * 
 * @param config - Color contrast configuration
 * @returns Whether contrast meets WCAG requirements
 * 
 * @example
 * ```typescript
 * const meetsWCAG = meetsContrastRequirement({
 *   foreground: KOREAN_COLORS.TEXT_PRIMARY,
 *   background: KOREAN_COLORS.UI_BACKGROUND_DARK,
 *   targetRatio: 4.5,
 * });
 * ```
 */
export function meetsContrastRequirement(config: ColorContrastConfig): boolean {
  const ratio = getContrastRatio(config.foreground, config.background);
  return ratio >= config.targetRatio;
}
 
/**
 * Get WCAG-compliant foreground color for given background
 * Returns white or black depending on which provides better contrast
 * 
 * @param background - Background color (hex)
 * @returns Foreground color (hex) that meets WCAG AA
 */
export function getAccessibleForeground(background: number): number {
  const whiteRatio = getContrastRatio(KOREAN_COLORS.TEXT_PRIMARY, background);
  const blackRatio = getContrastRatio(KOREAN_COLORS.BLACK_SOLID, background);
 
  // Return color with better contrast
  return whiteRatio >= blackRatio
    ? KOREAN_COLORS.TEXT_PRIMARY
    : KOREAN_COLORS.BLACK_SOLID;
}
 
/**
 * Announce message to screen readers
 * Creates a live region announcement with configurable politeness
 * 
 * @param announcement - Screen reader announcement configuration
 * 
 * @example
 * ```typescript
 * announceToScreenReader({
 *   message: '공격 성공 | Attack successful',
 *   politeness: 'polite',
 *   delay: 100,
 * });
 * ```
 */
let liveRegionInstance: HTMLElement | null = null;
 
export function announceToScreenReader(
  announcement: ScreenReaderAnnouncement
): void {
  const { message, politeness = 'polite', delay = 0 } = announcement;
 
  setTimeout(() => {
    // Create or get existing live region
    if (!liveRegionInstance) {
      liveRegionInstance = document.createElement('div');
      liveRegionInstance.id = 'sr-live-region';
      liveRegionInstance.setAttribute('aria-live', politeness);
      liveRegionInstance.setAttribute('aria-atomic', 'true');
      liveRegionInstance.style.cssText = `
        position: absolute;
        left: -10000px;
        width: 1px;
        height: 1px;
        overflow: hidden;
      `;
      document.body.appendChild(liveRegionInstance);
    }
 
    // Update politeness level if changed
    if (liveRegionInstance.getAttribute('aria-live') !== politeness) {
      liveRegionInstance.setAttribute('aria-live', politeness);
    }
 
    // Update message
    liveRegionInstance.textContent = message;
 
    // Clear message after 3 seconds
    setTimeout(() => {
      if (liveRegionInstance) {
        liveRegionInstance.textContent = '';
      }
    }, 3000);
  }, delay);
}
 
/**
 * Clean up screen reader live region (for testing or app unmount)
 */
export function cleanupScreenReaderRegion(): void {
  if (liveRegionInstance && liveRegionInstance.parentNode) {
    liveRegionInstance.parentNode.removeChild(liveRegionInstance);
    liveRegionInstance = null;
  }
}
 
/**
 * Trap focus within a container element
 * Prevents focus from leaving the container (e.g., for modals)
 * 
 * @param container - Container element to trap focus within
 * @returns Cleanup function to remove focus trap
 * 
 * @example
 * ```typescript
 * useEffect(() => {
 *   const cleanup = trapFocus(modalRef.current);
 *   return cleanup;
 * }, []);
 * ```
 */
export function trapFocus(container: HTMLElement | null): () => void {
  if (!container) return () => {};
 
  const focusableElements = getFocusableElements(container);
  const firstElement = focusableElements[0];
  const lastElement = focusableElements[focusableElements.length - 1];
 
  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key !== 'Tab') return;
 
    if (event.shiftKey) {
      // Shift + Tab: Move focus backward
      if (document.activeElement === firstElement) {
        event.preventDefault();
        lastElement?.focus();
      }
    } else {
      // Tab: Move focus forward
      if (document.activeElement === lastElement) {
        event.preventDefault();
        firstElement?.focus();
      }
    }
  };
 
  container.addEventListener('keydown', handleKeyDown);
 
  // Set initial focus
  firstElement?.focus();
 
  // Return cleanup function
  return () => {
    container.removeEventListener('keydown', handleKeyDown);
  };
}
 
/**
 * Get all focusable elements within a container
 * 
 * @param container - Container element
 * @returns Array of focusable elements
 */
export function getFocusableElements(
  container: HTMLElement
): HTMLElement[] {
  const selector = [
    'a[href]',
    'button:not([disabled])',
    'input:not([disabled])',
    'select:not([disabled])',
    'textarea:not([disabled])',
    '[tabindex]:not([tabindex="-1"])',
  ].join(', ');
 
  return Array.from(container.querySelectorAll<HTMLElement>(selector));
}
 
/**
 * Validate WCAG 2.1 Level AA compliance for a component
 * 
 * Note: Color contrast checking requires access to computed styles,
 * which is not available in all testing environments. This validation
 * focuses on structural accessibility attributes.
 * 
 * @param element - Element to validate
 * @param config - Validation configuration
 * @returns Compliance validation result
 */
export function validateWCAGCompliance(
  element: HTMLElement | null,
  config?: {
    checkKeyboard?: boolean;
    checkFocusVisible?: boolean;
    checkAria?: boolean;
  }
): WCAGComplianceResult {
  const {
    checkKeyboard = true,
    checkFocusVisible = true,
    checkAria = true,
  } = config ?? {};
 
  const issues: string[] = [];
  let keyboardAccessible = true;
  const colorContrast = true; // Note: Requires computed styles - use getContrastRatio() directly for color validation
  let focusVisible = true;
  let ariaLabels = true;
 
  if (!element) {
    issues.push('Element not found');
    return {
      level: WCAGLevel.A,
      compliant: false,
      criteria: {
        keyboardAccessible: false,
        colorContrast: false,
        focusVisible: false,
        ariaLabels: false,
        semanticHTML: false,
        errorIdentification: false,
      },
      issues,
    };
  }
 
  // Check keyboard accessibility
  if (checkKeyboard) {
    const isInteractive =
      element.tagName === 'BUTTON' ||
      element.tagName === 'A' ||
      element.tagName === 'INPUT' ||
      element.hasAttribute('onclick');
 
    if (isInteractive && element.getAttribute('tabindex') === '-1') {
      keyboardAccessible = false;
      issues.push('Interactive element not keyboard accessible');
    }
  }
 
  // Check ARIA labels
  if (checkAria) {
    const hasAriaLabel =
      element.hasAttribute('aria-label') ||
      element.hasAttribute('aria-labelledby');
 
    const hasTextContent = element.textContent?.trim();
 
    if (!hasAriaLabel && !hasTextContent) {
      ariaLabels = false;
      issues.push('Missing ARIA label or text content');
    }
  }
 
  // Check focus indicator
  if (checkFocusVisible) {
    const computedStyle = window.getComputedStyle(element);
    const outline = computedStyle.outline;
 
    if (outline === 'none' || outline === '') {
      focusVisible = false;
      issues.push('Missing visible focus indicator');
    }
  }
 
  const allPass =
    keyboardAccessible && colorContrast && focusVisible && ariaLabels;
 
  return {
    level: allPass ? WCAGLevel.AA : WCAGLevel.A,
    compliant: allPass,
    criteria: {
      keyboardAccessible,
      colorContrast, // Note: Always true - use getContrastRatio() for actual color validation
      focusVisible,
      ariaLabels,
      semanticHTML: true, // Requires manual verification
      errorIdentification: true, // Requires manual verification
    },
    issues,
  };
}
 
/**
 * Create comprehensive ARIA attributes for a component
 * 
 * @param label - Bilingual label (Korean | English)
 * @param role - ARIA role
 * @param additionalAttrs - Additional ARIA attributes
 * @returns Complete ARIA attributes object
 * 
 * @example
 * ```tsx
 * const ariaProps = createAriaAttributes(
 *   createBilingualLabel('공격', 'Attack'),
 *   'button',
 *   { 'aria-pressed': isPressed }
 * );
 * <button {...ariaProps}>
 * ```
 */
export function createAriaAttributes(
  label: string | { korean: string; english: string },
  role?: AriaAttributes['role'],
  additionalAttrs?: Partial<AriaAttributes>
): AriaAttributes {
  const bilingualLabel =
    typeof label === 'string'
      ? label
      : createBilingualLabel(label.korean, label.english).label;
 
  return {
    role,
    'aria-label': bilingualLabel,
    ...additionalAttrs,
  };
}
 
/**
 * Check if element is currently visible
 * Useful for skip-to-content and focus management
 * 
 * @param element - Element to check
 * @returns Whether element is visible
 */
export function isElementVisible(element: HTMLElement | null): boolean {
  if (!element) return false;
 
  const style = window.getComputedStyle(element);
  return (
    style.display !== 'none' &&
    style.visibility !== 'hidden' &&
    style.opacity !== '0' &&
    element.offsetParent !== null
  );
}
 
/**
 * Focus first error element in a form
 * Useful for form validation accessibility
 * 
 * @param container - Form container
 */
export function focusFirstError(container: HTMLElement): void {
  const errorElements = container.querySelectorAll<HTMLElement>(
    '[aria-invalid="true"]'
  );
 
  if (errorElements.length > 0) {
    errorElements[0].focus();
    announceToScreenReader({
      message: '오류가 발견되었습니다 | Errors found',
      politeness: 'assertive',
    });
  }
}
 
/**
 * Create skip to content link for keyboard navigation
 * Returns a link that allows users to skip to main content
 * 
 * @param targetId - ID of main content element
 * @returns Skip link element
 */
export function createSkipLink(targetId: string): HTMLAnchorElement {
  const skipLink = document.createElement('a');
  skipLink.href = `#${targetId}`;
  skipLink.textContent = '본문으로 건너뛰기 | Skip to content';
  skipLink.className = 'skip-link';
  skipLink.style.cssText = `
    position: absolute;
    top: -40px;
    left: 0;
    background: #00e6e6;
    color: #000;
    padding: 8px;
    text-decoration: none;
    z-index: 10000;
    font-weight: bold;
  `;
 
  // Show on focus
  skipLink.addEventListener('focus', () => {
    skipLink.style.top = '0';
  });
 
  // Hide on blur
  skipLink.addEventListener('blur', () => {
    skipLink.style.top = '-40px';
  });
 
  return skipLink;
}