All files / systems LayoutSystem.ts

100% Statements 59/59
100% Branches 54/54
100% Functions 12/12
100% Lines 59/59

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                                                                  20x 20x 20x             20x                 20x           20x                                                                                           27x 27x 27x                                                           16x 2x       14x 2x       12x 1x         11x 16x     16x         16x   16x                                                         328x 2x   326x 1x       325x 323x       2x 2x                                                   302x 302x   172x   128x   1x   1x                                                 8x   1x   5x   2x                                                 8x   1x   5x   2x                                       334x 334x 334x 334x   334x                                                                     2x     2x 2x 2x     2x     2x   2x                                       20x                                 1x                                   2x                                   2x                                   1x          
/**
 * Unified Layout System for consistent component positioning
 *
 * Provides grid-based layout calculations, responsive positioning utilities,
 * and alignment helpers for all screens in Black Trigram (흑괘).
 *
 * Features:
 * - 12-column grid system for consistent alignment
 * - Responsive positioning that adapts to screen size
 * - Safe area handling for mobile devices with notches
 * - Z-index hierarchy management
 * - Korean-English UI alignment support
 *
 * Performance target: <1ms for layout calculations
 *
 * @module systems/LayoutSystem
 * @category Systems
 * @korean 레이아웃시스템
 */
 
import { Position } from "../types/common";
import {
  ContainerBounds,
  HorizontalAlignment,
  ResponsivePosition,
  SafeAreaInsets,
  ScreenSize,
  VerticalAlignment,
} from "../types/LayoutTypes";
 
/**
 * Default grid configuration
 */
const DEFAULT_GRID_COLUMNS = 12;
const DEFAULT_GUTTER_SIZE = 20;
const BASE_DESKTOP_WIDTH = 1200;
 
/**
 * Base width for mobile arena scaling calculations (in pixels)
 * This represents the standard desktop arena width (80% of 1200px)
 * Used to calculate scale factor for mobile devices
 */
const MOBILE_ARENA_BASE_WIDTH = 960;
 
/**
 * Default row height for grid-based vertical positioning (in pixels)
 * Used when row index is specified in grid configuration
 * Can be overridden by providing explicit y position
 * 
 * @public
 */
export const DEFAULT_ROW_HEIGHT = 100;
 
/**
 * Default safe area insets for mobile devices
 * Based on typical iOS device dimensions (iPhone 14 Pro as reference)
 */
const DEFAULT_SAFE_AREA: SafeAreaInsets = {
  top: 44, // Status bar + notch
  right: 0,
  bottom: 34, // Home indicator
  left: 0,
};
 
/**
 * LayoutSystem Class
 *
 * Provides unified layout calculations and positioning utilities
 * for consistent component placement across all screens.
 *
 * @example
 * ```typescript
 * const layout = new LayoutSystem();
 *
 * // Calculate grid position
 * const pos = layout.calculateGridPosition(2, 4, 1200);
 * // Returns { x: 200, width: 380 } for column 2, span 4
 *
 * // Calculate responsive position
 * const screenSize = { width: 375, height: 667, isMobile: true, isTablet: false, isDesktop: false, isLandscape: false };
 * const responsivePos = layout.calculateResponsivePosition(
 *   { base: { x: 100, y: 50 } },
 *   screenSize
 * );
 * ```
 */
export class LayoutSystem {
  private readonly gridColumns: number;
  private readonly gutterSize: number;
  private readonly safeArea: SafeAreaInsets;
 
  /**
   * Create a new LayoutSystem instance
   *
   * @param gridColumns - Number of grid columns (default: 12)
   * @param gutterSize - Gutter size between columns in pixels (default: 20)
   * @param safeArea - Safe area insets for mobile devices
   */
  constructor(
    gridColumns: number = DEFAULT_GRID_COLUMNS,
    gutterSize: number = DEFAULT_GUTTER_SIZE,
    safeArea: SafeAreaInsets = DEFAULT_SAFE_AREA
  ) {
    this.gridColumns = gridColumns;
    this.gutterSize = gutterSize;
    this.safeArea = safeArea;
  }
 
  /**
   * Calculate position and width for grid-based layout
   *
   * Uses 12-column grid system for consistent alignment.
   * Accounts for gutters between columns.
   *
   * @param column - Starting column (0-11)
   * @param span - Number of columns to span (1-12)
   * @param containerWidth - Total container width in pixels
   * @param customGutter - Custom gutter size (optional)
   * @returns Position and width for the grid cell
   * @throws Error if column or span are outside valid ranges
   *
   * @example
   * ```typescript
   * // Center element spanning 6 columns
   * const pos = layout.calculateGridPosition(3, 6, 1200);
   * // Returns { x: 300, width: 580 }
   * ```
   */
  calculateGridPosition(
    column: number,
    span: number,
    containerWidth: number,
    customGutter?: number
  ): { x: number; width: number } {
    // Validate inputs
    if (column < 0 || column >= this.gridColumns) {
      throw new Error(
        `Invalid column: ${column}. Column must be between 0 and ${this.gridColumns - 1}`
      );
    }
    if (span < 1 || span > this.gridColumns) {
      throw new Error(
        `Invalid span: ${span}. Span must be between 1 and ${this.gridColumns}`
      );
    }
    if (column + span > this.gridColumns) {
      throw new Error(
        `Invalid grid position: column ${column} + span ${span} = ${column + span} exceeds ${this.gridColumns} columns`
      );
    }
 
    const gutter = customGutter ?? this.gutterSize;
    const columnWidth = containerWidth / this.gridColumns;
 
    // Calculate x position
    const x = column * columnWidth;
 
    // Calculate width accounting for gutters
    // Width = (span * columnWidth) - gutter
    // The gutter is subtracted to create spacing between elements
    const width = span * columnWidth - gutter;
 
    return { x, width };
  }
 
  /**
   * Calculate responsive position based on screen size
   *
   * Scales position proportionally or uses specific overrides for tablet/mobile.
   *
   * @param config - Responsive position configuration
   * @param screenSize - Current screen dimensions and device type
   * @returns Calculated position for current screen size
   *
   * @example
   * ```typescript
   * const pos = layout.calculateResponsivePosition(
   *   {
   *     base: { x: 100, y: 50 },
   *     mobile: { x: 10, y: 20 },
   *     scaleProportionally: true
   *   },
   *   screenSize
   * );
   * ```
   */
  calculateResponsivePosition(
    config: ResponsivePosition,
    screenSize: ScreenSize
  ): Position {
    // Use specific override if available
    if (screenSize.isMobile && config.mobile) {
      return config.mobile;
    }
    if (screenSize.isTablet && config.tablet) {
      return config.tablet;
    }
 
    // Use base position for desktop
    if (screenSize.isDesktop || !config.scaleProportionally) {
      return config.base;
    }
 
    // Scale proportionally for mobile/tablet if no override
    const scale = screenSize.width / BASE_DESKTOP_WIDTH;
    return {
      x: config.base.x * scale,
      y: config.base.y * scale,
    };
  }
 
  /**
   * Calculate safe position accounting for device notches and home indicators
   *
   * Ensures UI elements don't overlap with system UI on mobile devices.
   *
   * @param position - Base position
   * @param edge - Which edge to apply safe area ('top' | 'bottom' | 'left' | 'right')
   * @returns Position adjusted for safe area
   *
   * @example
   * ```typescript
   * // Adjust top position for status bar/notch
   * const safePos = layout.calculateSafePosition({ x: 0, y: 10 }, 'top');
   * // Returns { x: 0, y: 54 } (10 + 44 for notch)
   * ```
   */
  calculateSafePosition(
    position: Position,
    edge: "top" | "bottom" | "left" | "right"
  ): Position {
    const inset = this.safeArea[edge];
    switch (edge) {
      case "top":
        return { ...position, y: position.y + inset };
      case "bottom":
        return { ...position, y: position.y - inset };
      case "left":
        return { ...position, x: position.x + inset };
      case "right":
        return { ...position, x: position.x - inset };
    }
  }
 
  /**
   * Align element horizontally within container
   *
   * @param elementWidth - Width of element to align
   * @param containerWidth - Width of container
   * @param alignment - Alignment type ('left' | 'center' | 'right')
   * @param margin - Optional margin from edges
   * @returns X position for alignment
   *
   * @example
   * ```typescript
   * const x = layout.alignHorizontal(200, 800, 'center', 10);
   * // Returns 300 (centered with margins)
   * ```
   */
  alignHorizontal(
    elementWidth: number,
    containerWidth: number,
    alignment: HorizontalAlignment,
    margin: number = 0
  ): number {
    switch (alignment) {
      case "left":
        return margin;
      case "center":
        return (containerWidth - elementWidth) / 2;
      case "right":
        return containerWidth - elementWidth - margin;
    }
  }
 
  /**
   * Align element vertically within container
   *
   * @param elementHeight - Height of element to align
   * @param containerHeight - Height of container
   * @param alignment - Alignment type ('top' | 'middle' | 'bottom')
   * @param margin - Optional margin from edges
   * @returns Y position for alignment
   *
   * @example
   * ```typescript
   * const y = layout.alignVertical(100, 600, 'middle', 10);
   * // Returns 250 (vertically centered)
   * ```
   */
  alignVertical(
    elementHeight: number,
    containerHeight: number,
    alignment: VerticalAlignment,
    margin: number = 0
  ): number {
    switch (alignment) {
      case "top":
        return margin;
      case "middle":
        return (containerHeight - elementHeight) / 2;
      case "bottom":
        return containerHeight - elementHeight - margin;
    }
  }
 
  /**
   * Create screen size information from dimensions
   *
   * Determines device type and orientation based on screen dimensions.
   *
   * @param width - Screen width in pixels
   * @param height - Screen height in pixels
   * @returns ScreenSize object with device type flags
   *
   * @example
   * ```typescript
   * const screenSize = layout.getScreenSize(375, 667);
   * // Returns { width: 375, height: 667, isMobile: true, ... }
   * ```
   */
  getScreenSize(width: number, height: number): ScreenSize {
    const isMobile = width < 768;
    const isTablet = width >= 768 && width < 1200;
    const isDesktop = width >= 1200;
    const isLandscape = width > height;
 
    return {
      width,
      height,
      isMobile,
      isTablet,
      isDesktop,
      isLandscape,
    };
  }
 
  /**
   * Calculate container bounds for arena or game area
   *
   * Accounts for HUD, controls, and safe areas to determine usable space.
   *
   * @param screenWidth - Total screen width
   * @param screenHeight - Total screen height
   * @param hudHeight - Height of top HUD
   * @param controlsHeight - Height of bottom controls
   * @param padding - Padding around content
   * @returns Container bounds for game content
   *
   * @example
   * ```typescript
   * const bounds = layout.calculateContainerBounds(1200, 800, 120, 0, 10);
   * // Returns bounds for desktop game area
   * ```
   */
  calculateContainerBounds(
    screenWidth: number,
    screenHeight: number,
    hudHeight: number = 0,
    controlsHeight: number = 0,
    padding: number = 10
  ): ContainerBounds {
    const screenSize = this.getScreenSize(screenWidth, screenHeight);
 
    // Calculate available height
    const topOffset = hudHeight + padding + (screenSize.isMobile ? this.safeArea.top : 0);
    const bottomOffset = controlsHeight + padding + (screenSize.isMobile ? this.safeArea.bottom : 0);
    const availableHeight = screenHeight - topOffset - bottomOffset;
 
    // Calculate width accounting for padding
    const availableWidth = screenWidth - padding * 2;
 
    // Calculate scale for mobile (arena should be smaller on mobile)
    const scale = screenSize.isMobile ? Math.min(availableWidth / MOBILE_ARENA_BASE_WIDTH, 1.0) : 1.0;
 
    return {
      x: padding,
      y: topOffset,
      width: availableWidth,
      height: availableHeight,
      scale,
    };
  }
}
 
/**
 * Default singleton instance for convenience
 *
 * @example
 * ```typescript
 * import { defaultLayoutSystem } from './systems/LayoutSystem';
 *
 * const pos = defaultLayoutSystem.alignHorizontal(200, 800, 'center');
 * ```
 */
export const defaultLayoutSystem = new LayoutSystem();
 
/**
 * Helper function to create grid-based position
 *
 * Convenience wrapper around LayoutSystem.calculateGridPosition
 *
 * @param column - Starting column (0-11)
 * @param span - Number of columns to span (1-12)
 * @param containerWidth - Total container width
 * @returns Position and width for grid cell
 */
export function calculateGridPosition(
  column: number,
  span: number,
  containerWidth: number
): { x: number; width: number } {
  return defaultLayoutSystem.calculateGridPosition(column, span, containerWidth);
}
 
/**
 * Helper function to align element horizontally
 *
 * @param elementWidth - Width of element
 * @param containerWidth - Width of container
 * @param alignment - Alignment type
 * @param margin - Optional margin
 * @returns X position
 */
export function alignHorizontal(
  elementWidth: number,
  containerWidth: number,
  alignment: HorizontalAlignment = "center",
  margin: number = 0
): number {
  return defaultLayoutSystem.alignHorizontal(elementWidth, containerWidth, alignment, margin);
}
 
/**
 * Helper function to align element vertically
 *
 * @param elementHeight - Height of element
 * @param containerHeight - Height of container
 * @param alignment - Alignment type
 * @param margin - Optional margin
 * @returns Y position
 */
export function alignVertical(
  elementHeight: number,
  containerHeight: number,
  alignment: VerticalAlignment = "middle",
  margin: number = 0
): number {
  return defaultLayoutSystem.alignVertical(elementHeight, containerHeight, alignment, margin);
}
 
/**
 * Helper function to center element in container
 *
 * @param elementWidth - Width of element
 * @param elementHeight - Height of element
 * @param containerWidth - Width of container
 * @param containerHeight - Height of container
 * @returns Centered position
 */
export function centerElement(
  elementWidth: number,
  elementHeight: number,
  containerWidth: number,
  containerHeight: number
): Position {
  return {
    x: alignHorizontal(elementWidth, containerWidth, "center"),
    y: alignVertical(elementHeight, containerHeight, "middle"),
  };
}