All files / client/src/hmr overlay.js

91.89% Statements 68/74
77.27% Branches 34/44
85.71% Functions 18/21
94.11% Lines 64/68

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                              26x                             7x   4x 4x 8x 8x 8x                   3x 3x 1x 1x 1x 1x 1x 1x           3x                                                                                                                                                                                                                                                                                       26x   26x   26x                 26x 26x   3x                 12x   11x 11x 11x   11x 11x 11x   11x 11x                           8x     8x 8x     8x 8x   8x 8x 8x                                                       8x     8x 8x 8x   8x 8x 8x               8x 2x   8x     8x 8x               28x 8x   28x 8x 8x     28x                 9x 9x 9x               9x 9x 9x                   3x  
/**
 * HMR Error Overlay
 *
 * Displays error information in a full-screen overlay with Shadow DOM isolation.
 * Provides click-to-open editor support and keyboard/click dismissal.
 *
 * @module @coherent.js/client/hmr/overlay
 */
 
/**
 * Escape HTML special characters to prevent XSS.
 * @param {string} str - String to escape
 * @returns {string} Escaped string
 */
export function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}
 
/**
 * Format code frame with line numbers and highlight.
 * @param {string} frame - Code frame content
 * @param {number} highlightLine - Line number to highlight (1-based)
 * @param {number} [startLine=1] - Starting line number for the frame
 * @returns {string} Formatted HTML string
 */
export function formatCodeFrame(frame, highlightLine, startLine = 1) {
  if (!frame) return '';
 
  const lines = frame.split('\n');
  return lines.map((content, i) => {
    const lineNum = startLine + i;
    const isHighlight = lineNum === highlightLine;
    return `<div class="line${isHighlight ? ' highlight' : ''}">
      <span class="line-number">${lineNum}</span>
      <span class="line-content">${escapeHtml(content)}</span>
    </div>`;
  }).join('');
}
 
/**
 * Editor URL scheme map for click-to-open functionality.
 */
const EDITOR_URLS = {
  vscode: (file, line) => `vscode://file/${file}:${line}`,
  cursor: (file, line) => `cursor://file/${file}:${line}`,
  'vscode-insiders': (file, line) => `vscode-insiders://file/${file}:${line}`,
  atom: (file, line) => `atom://core/open/file?filename=${file}&line=${line}`,
  sublime: (file, line) => `subl://open?url=file://${file}&line=${line}`,
  webstorm: (file, line) => `webstorm://open?file=${file}&line=${line}`,
  idea: (file, line) => `idea://open?file=${file}&line=${line}`
};
 
/**
 * CSS styles for the error overlay (Dracula-inspired color scheme).
 */
const OVERLAY_STYLES = `
  :host {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    --bg: #181818;
    --text: #f8f8f2;
    --red: #ff5555;
    --yellow: #f1fa8c;
    --purple: #bd93f9;
    --cyan: #8be9fd;
    --code-bg: #282a36;
    --line-num: #6272a4;
  }
  .backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.66);
  }
  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: min(800px, 90vw);
    max-height: 90vh;
    overflow: auto;
    background: var(--bg);
    border-radius: 8px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
    font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
  }
  .header {
    padding: 16px 20px;
    background: var(--red);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 8px 8px 0 0;
  }
  .title {
    font-weight: bold;
    font-size: 16px;
  }
  .close-btn {
    background: none;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
    padding: 0 8px;
    line-height: 1;
  }
  .close-btn:hover {
    opacity: 0.8;
  }
  .content {
    padding: 20px;
    color: var(--text);
  }
  .message {
    font-size: 18px;
    color: var(--red);
    margin-bottom: 20px;
    word-break: break-word;
  }
  .file {
    color: var(--cyan);
    margin-bottom: 16px;
    cursor: pointer;
    text-decoration: underline;
  }
  .file:hover {
    color: var(--purple);
  }
  .code-frame {
    background: var(--code-bg);
    padding: 16px;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 16px;
  }
  .line {
    display: flex;
  }
  .line-number {
    width: 50px;
    color: var(--line-num);
    text-align: right;
    padding-right: 16px;
    user-select: none;
    flex-shrink: 0;
  }
  .line-content {
    flex: 1;
    white-space: pre;
  }
  .line.highlight {
    background: rgba(255, 85, 85, 0.2);
  }
  .line.highlight .line-content {
    color: var(--red);
  }
  .stack {
    margin-top: 20px;
    font-size: 12px;
    color: var(--line-num);
    white-space: pre-wrap;
    max-height: 200px;
    overflow-y: auto;
  }
  .tip {
    margin-top: 16px;
    padding: 12px;
    background: rgba(189, 147, 249, 0.1);
    border-left: 3px solid var(--purple);
    font-size: 13px;
    color: var(--text);
  }
  .tip strong {
    color: var(--purple);
  }
`;
 
/**
 * Error overlay class for HMR error display.
 * Uses Shadow DOM for complete style isolation.
 */
export class ErrorOverlay {
  constructor() {
    /** @type {{ host: HTMLElement, shadow: ShadowRoot } | null} */
    this.overlay = null;
    /** @type {string} */
    this.editor = this._getStoredEditor();
    /** @type {((e: KeyboardEvent) => void) | null} */
    this.escapeHandler = null;
  }
 
  /**
   * Get stored editor preference from localStorage.
   * @returns {string} Editor name
   * @private
   */
  _getStoredEditor() {
    try {
      return localStorage.getItem('coherent-editor') || 'vscode';
    } catch {
      return 'vscode';
    }
  }
 
  /**
   * Create the overlay element with Shadow DOM.
   * @returns {{ host: HTMLElement, shadow: ShadowRoot }} Overlay elements
   */
  createOverlay() {
    if (this.overlay) return this.overlay;
 
    const host = document.createElement('div');
    host.id = 'coherent-error-overlay';
    const shadow = host.attachShadow({ mode: 'open' });
 
    const style = document.createElement('style');
    style.textContent = OVERLAY_STYLES;
    shadow.appendChild(style);
 
    this.overlay = { host, shadow };
    return this.overlay;
  }
 
  /**
   * Show the error overlay with error details.
   * @param {Object} error - Error details
   * @param {string} error.message - Error message
   * @param {string} [error.file] - File path
   * @param {number} [error.line] - Line number
   * @param {number} [error.column] - Column number
   * @param {string} [error.frame] - Code frame with context
   * @param {string} [error.stack] - Stack trace
   */
  show(error) {
    const { host, shadow } = this.createOverlay();
 
    // Clear previous content (but keep styles)
    const existingWrapper = shadow.querySelector('.wrapper');
    if (existingWrapper) existingWrapper.remove();
 
    // Calculate start line for code frame (center on error line)
    const frameLines = error.frame ? error.frame.split('\n').length : 0;
    const startLine = error.line ? Math.max(1, error.line - Math.floor(frameLines / 2)) : 1;
 
    const wrapper = document.createElement('div');
    wrapper.className = 'wrapper';
    wrapper.innerHTML = `
      <div class="backdrop"></div>
      <div class="container">
        <div class="header">
          <span class="title">HMR Error</span>
          <button class="close-btn" title="Close (Escape)">&times;</button>
        </div>
        <div class="content">
          <div class="message">${escapeHtml(error.message || 'Unknown error')}</div>
          ${error.file ? `
            <div class="file" data-file="${escapeHtml(error.file)}" data-line="${error.line || 1}">
              ${escapeHtml(error.file)}${error.line ? `:${error.line}` : ''}${error.column ? `:${error.column}` : ''}
            </div>
          ` : ''}
          ${error.frame ? `
            <div class="code-frame">${formatCodeFrame(error.frame, error.line, startLine)}</div>
          ` : ''}
          ${error.stack ? `
            <div class="stack">${escapeHtml(error.stack)}</div>
          ` : ''}
          <div class="tip">
            Press <strong>Escape</strong> or click the X to dismiss.
            ${error.file ? ` Click the file path to open in ${this.editor}.` : ''}
          </div>
        </div>
      </div>
    `;
 
    shadow.appendChild(wrapper);
 
    // Event handlers
    const closeBtn = wrapper.querySelector('.close-btn');
    const backdrop = wrapper.querySelector('.backdrop');
    const fileLink = wrapper.querySelector('.file');
 
    closeBtn?.addEventListener('click', () => this.hide());
    backdrop?.addEventListener('click', () => this.hide());
    fileLink?.addEventListener('click', (e) => {
      const target = e.target;
      const file = target.dataset.file;
      const line = parseInt(target.dataset.line, 10) || 1;
      this.openInEditor(file, line);
    });
 
    // Escape key handler
    this.escapeHandler = (e) => {
      if (e.key === 'Escape') this.hide();
    };
    document.addEventListener('keydown', this.escapeHandler);
 
    // Add to DOM if not already
    Eif (!host.parentNode) {
      document.body.appendChild(host);
    }
  }
 
  /**
   * Hide and remove the error overlay.
   */
  hide() {
    if (this.overlay?.host.parentNode) {
      this.overlay.host.parentNode.removeChild(this.overlay.host);
    }
    if (this.escapeHandler) {
      document.removeEventListener('keydown', this.escapeHandler);
      this.escapeHandler = null;
    }
    // Reset overlay reference so it can be recreated
    this.overlay = null;
  }
 
  /**
   * Open file in configured editor.
   * @param {string} file - File path
   * @param {number} [line=1] - Line number
   */
  openInEditor(file, line = 1) {
    const urlGenerator = EDITOR_URLS[this.editor] || EDITOR_URLS.vscode;
    const url = urlGenerator(file, line);
    window.open(url, '_self');
  }
 
  /**
   * Set preferred editor and store in localStorage.
   * @param {string} editor - Editor name (vscode, cursor, vscode-insiders, atom, sublime, webstorm, idea)
   */
  setEditor(editor) {
    this.editor = editor;
    try {
      localStorage.setItem('coherent-editor', editor);
    } catch {
      // Ignore localStorage errors
    }
  }
}
 
/**
 * Singleton instance of ErrorOverlay.
 */
export const errorOverlay = new ErrorOverlay();