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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 8x 8x 10x 10x 10x 6x 6x 10x 2x 1x 1x 2x 2x 10x 6x 8x 36x 36x 36x 36x 36x 36x 36x 7x 7x 8x 8x 7x 7x 7x 8x 1x 1x 1x 8x 6x 7x 36x 36x 36x 36x 36x 36x 36x 34x 34x 34x 34x 34x 6x 6x 34x 28x 28x 28x 28x 28x 34x 2x 2x 28x 38x 1x 1x 2x 2x 2x 1x 1x 1x 38x 24x 37x 1x 13x 12x 11x 11x 2x 1x 1x 11x 9x 9x 9x 11x 28x 34x 34x 2x 2x 26x 34x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 4x 4x 1x 1x 1x 1x 3x 3x 35x 36x 7x 5x 33x 33x 36x 7x 6x 32x 32x 32x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 36x 2x 2x 2x 31x 36x 3x 3x 3x 1x 1x 1x 1x 1x 3x 31x 36x 3x 1x 1x 3x 3x 36x 36x 36x 36x 36x 36x 36x 2x 2x 2x 2x 36x 36x 36x 36x 36x 1x 1x 36x 36x 36x 36x 36x 36x 1x 1x 36x 36x 36x 36x 1x 1x 1x 36x 36x 36x 36x 36x 5x 5x 5x 5x 5x 5x 5x 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 36x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /** * @fileoverview Rendering Pipeline Hooks for Coherent.js * Provides customizable rendering pipeline with hooks and middleware * @module @coherentjs/core/rendering/render-pipeline */ /** * @typedef {Object} RenderPipelineOptions * @property {Array<Function>} [beforeRender] - Hooks called before rendering * @property {Array<Function>} [afterRender] - Hooks called after rendering * @property {Array<Function>} [middleware] - Middleware functions * @property {Object<string, Function>} [customRenderers] - Custom element renderers * @property {boolean} [escapeHTML=true] - Escape HTML by default * @property {Function} [escapeFunction] - Custom HTML escape function * @property {boolean} [enableCache=false] - Enable render result caching * @property {Function} [shouldCache] - Function to determine if result should be cached * @property {boolean} [debug=false] - Enable debug logging * @property {Object} [performance] - Performance monitoring options */ /** * @typedef {Object} RenderContext * @property {Object} component - Component being rendered * @property {Object} props - Component props * @property {Object} state - Component state * @property {string} path - Component path in tree * @property {number} depth - Nesting depth * @property {Object} metadata - Custom metadata */ /** * Default HTML escape function * @param {string} str - String to escape * @returns {string} Escaped string */ function defaultEscapeHTML(str) { if (typeof str !== 'string') return str; return str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /** * Create render pipeline * @param {RenderPipelineOptions} options - Pipeline options * @returns {Object} Render pipeline */ export function createRenderPipeline(options = {}) { const opts = { beforeRender: [], afterRender: [], middleware: [], customRenderers: {}, escapeHTML: true, escapeFunction: defaultEscapeHTML, enableCache: false, shouldCache: null, debug: false, performance: { enabled: false, logSlowRenders: false, threshold: 10 }, ...options }; const cache = new Map(); const stats = { renders: 0, cacheHits: 0, cacheMisses: 0, totalTime: 0, slowRenders: 0 }; /** * Execute hooks * @param {Array<Function>} hooks - Hooks to execute * @param {RenderContext} context - Render context * @returns {Promise<RenderContext>} Modified context */ async function executeHooks(hooks, context) { let ctx = { ...context }; for (const hook of hooks) { try { const result = await hook(ctx); if (result !== undefined) { ctx = { ...ctx, ...result }; } } catch (error) { if (opts.debug) { console.error('Hook execution error:', error); } throw error; } } return ctx; } /** * Execute middleware * @param {Object} component - Component to render * @param {RenderContext} context - Render context * @returns {Promise<Object>} Modified component */ async function executeMiddleware(component, context) { let comp = component; for (const middleware of opts.middleware) { try { const result = await middleware(comp, context); if (result !== undefined) { comp = result; } } catch (error) { if (opts.debug) { console.error('Middleware execution error:', error); } throw error; } } return comp; } /** * Render element * @param {Object} element - Element to render * @param {RenderContext} context - Render context * @returns {string} Rendered HTML */ function renderElement(element, context) { if (!element || typeof element !== 'object') { return opts.escapeHTML ? opts.escapeFunction(String(element || '')) : String(element || ''); } const tag = Object.keys(element)[0]; const props = element[tag]; // Use custom renderer if available if (opts.customRenderers[tag]) { return opts.customRenderers[tag](props, context, renderElement); } if (!props) { return `<${tag}></${tag}>`; } const attributes = []; let content = ''; let selfClosing = false; // Self-closing tags const selfClosingTags = ['img', 'br', 'hr', 'input', 'meta', 'link', 'area', 'base', 'col', 'embed', 'param', 'source', 'track', 'wbr']; if (selfClosingTags.includes(tag)) { selfClosing = true; } Object.entries(props).forEach(([key, value]) => { if (key === 'children') { content = Array.isArray(value) ? value.map((child, idx) => renderElement(child, { ...context, path: `${context.path}.children[${idx}]`, depth: context.depth + 1 })).join('') : renderElement(value, { ...context, path: `${context.path}.children`, depth: context.depth + 1 }); } else if (key === 'text') { content = opts.escapeHTML ? opts.escapeFunction(String(value)) : String(value); } else if (key === 'html') { content = String(value); } else if (key === 'dangerouslySetInnerHTML') { content = value.__html || ''; } else if (!key.startsWith('on') && key !== 'ref' && key !== 'key') { // Skip event handlers and special props if (typeof value === 'boolean') { if (value) { attributes.push(key); } } else if (value !== null && value !== undefined) { const escapedValue = opts.escapeHTML ? opts.escapeFunction(String(value)) : String(value); attributes.push(`${key}="${escapedValue}"`); } } }); const attrsStr = attributes.length > 0 ? ` ${ attributes.join(' ')}` : ''; if (selfClosing) { return `<${tag}${attrsStr} />`; } return `<${tag}${attrsStr}>${content}</${tag}>`; } /** * Render component * @param {Object} component - Component to render * @param {Object} initialContext - Initial context * @returns {Promise<string>} Rendered HTML */ async function render(component, initialContext = {}) { const startTime = opts.performance.enabled ? performance.now() : 0; stats.renders++; // Create render context let context = { component, props: initialContext.props || {}, state: initialContext.state || {}, path: initialContext.path || 'root', depth: initialContext.depth || 0, metadata: initialContext.metadata || {}, ...initialContext }; try { // Check cache if (opts.enableCache) { const cacheKey = JSON.stringify({ component, context }); if (cache.has(cacheKey)) { stats.cacheHits++; if (opts.debug) { console.log('[RenderPipeline] Cache hit:', context.path); } return cache.get(cacheKey); } stats.cacheMisses++; } // Execute beforeRender hooks if (opts.beforeRender.length > 0) { context = await executeHooks(opts.beforeRender, context); } // Execute middleware let processedComponent = component; if (opts.middleware.length > 0) { processedComponent = await executeMiddleware(component, context); } // Render const result = renderElement(processedComponent, context); // Execute afterRender hooks if (opts.afterRender.length > 0) { context.result = result; const afterContext = await executeHooks(opts.afterRender, context); if (afterContext.result !== undefined) { const finalResult = afterContext.result; // Cache result if (opts.enableCache && (!opts.shouldCache || opts.shouldCache(processedComponent, context))) { const cacheKey = JSON.stringify({ component, context }); cache.set(cacheKey, finalResult); } // Performance monitoring if (opts.performance.enabled) { const renderTime = performance.now() - startTime; stats.totalTime += renderTime; if (renderTime > opts.performance.threshold) { stats.slowRenders++; if (opts.performance.logSlowRenders) { console.warn(`[RenderPipeline] Slow render (${renderTime.toFixed(2)}ms):`, context.path); } } } return finalResult; } } // Cache result if (opts.enableCache && (!opts.shouldCache || opts.shouldCache(processedComponent, context))) { const cacheKey = JSON.stringify({ component, context }); cache.set(cacheKey, result); } // Performance monitoring if (opts.performance.enabled) { const renderTime = performance.now() - startTime; stats.totalTime += renderTime; if (renderTime > opts.performance.threshold) { stats.slowRenders++; if (opts.performance.logSlowRenders) { console.warn(`[RenderPipeline] Slow render (${renderTime.toFixed(2)}ms):`, context.path); } } } return result; } catch (error) { if (opts.debug) { console.error('[RenderPipeline] Render error:', error, 'at', context.path); } throw error; } } /** * Add hook * @param {string} type - Hook type ('before' or 'after') * @param {Function} hook - Hook function */ function addHook(type, hook) { if (type === 'before') { opts.beforeRender.push(hook); } else if (type === 'after') { opts.afterRender.push(hook); } } /** * Add middleware * @param {Function} middleware - Middleware function */ function addMiddleware(middleware) { opts.middleware.push(middleware); } /** * Register custom renderer * @param {string} tag - Element tag * @param {Function} renderer - Renderer function */ function registerRenderer(tag, renderer) { opts.customRenderers[tag] = renderer; } /** * Clear render cache */ function clearCache() { cache.clear(); if (opts.debug) { console.log('[RenderPipeline] Cache cleared'); } } /** * Get render statistics * @returns {Object} Render stats */ function getStats() { return { ...stats, averageRenderTime: stats.renders > 0 ? stats.totalTime / stats.renders : 0, cacheSize: cache.size, cacheHitRate: stats.renders > 0 ? (stats.cacheHits / stats.renders) * 100 : 0 }; } return { render, addHook, addMiddleware, registerRenderer, clearCache, getStats, get options() { return { ...opts }; } }; } /** * Common middleware functions */ export const middleware = { /** * Add class name middleware * @param {string|Function} className - Class name or function * @returns {Function} Middleware function */ addClassName: (className) => (component, context) => { const tag = Object.keys(component)[0]; const props = component[tag]; const additionalClass = typeof className === 'function' ? className(component, context) : className; if (!additionalClass) return component; return { [tag]: { ...props, className: props.className ? `${props.className} ${additionalClass}` : additionalClass } }; }, /** * Add data attributes middleware * @param {Object|Function} attributes - Data attributes * @returns {Function} Middleware function */ addDataAttributes: (attributes) => (component, context) => { const tag = Object.keys(component)[0]; const props = component[tag]; const attrs = typeof attributes === 'function' ? attributes(component, context) : attributes; return { [tag]: { ...props, ...attrs } }; }, /** * Wrap component middleware * @param {Function} wrapper - Wrapper function * @returns {Function} Middleware function */ wrap: (wrapper) => (component, context) => { return wrapper(component, context); }, /** * Conditional rendering middleware * @param {Function} condition - Condition function * @param {Function} transform - Transform function * @returns {Function} Middleware function */ conditional: (condition, transform) => (component, context) => { if (condition(component, context)) { return transform(component, context); } return component; } }; /** * Common hooks */ export const hooks = { /** * Performance monitoring hook * @returns {Function} Hook function */ performanceMonitor: () => (context) => { const start = performance.now(); context.metadata.renderStart = start; return { ...context, metadata: { ...context.metadata, renderStart: start } }; }, /** * Debug logging hook * @returns {Function} Hook function */ debugLog: () => (context) => { const indent = ' '.repeat(context.depth); console.log(`${indent}[Render] ${context.path}`, context.component); return context; }, /** * Metadata injection hook * @param {Object|Function} metadata - Metadata to inject * @returns {Function} Hook function */ injectMetadata: (metadata) => (context) => { const meta = typeof metadata === 'function' ? metadata(context) : metadata; return { ...context, metadata: { ...context.metadata, ...meta } }; } }; /** * Create custom renderer * @param {Function} renderFunction - Custom render function * @returns {Function} Renderer function */ export function createCustomRenderer(renderFunction) { return (props, context, renderElement) => { return renderFunction(props, context, renderElement); }; } /** * Common custom renderers */ export const customRenderers = { /** * Markdown renderer (basic) * @param {Object} props - Component props * @returns {string} Rendered HTML */ markdown: (props) => { let content = props.text || props.children || ''; // Basic markdown transformations content = content .replace(/^### (.*$)/gm, '<h3>$1</h3>') .replace(/^## (.*$)/gm, '<h2>$1</h2>') .replace(/^# (.*$)/gm, '<h1>$1</h1>') .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') .replace(/\*(.*?)\*/g, '<em>$1</em>') .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>'); return `<div class="markdown">${content}</div>`; }, /** * Code block renderer with syntax highlighting markers * @param {Object} props - Component props * @returns {string} Rendered HTML */ codeBlock: (props) => { const code = props.text || props.children || ''; const language = props.language || 'javascript'; return `<pre><code class="language-${language}">${defaultEscapeHTML(code)}</code></pre>`; }, /** * Icon renderer * @param {Object} props - Component props * @returns {string} Rendered HTML */ icon: (props) => { const name = props.name || ''; const size = props.size || '24'; const color = props.color || 'currentColor'; return `<svg class="icon icon-${name}" width="${size}" height="${size}" fill="${color}"><use href="#icon-${name}"></use></svg>`; } }; export default { createRenderPipeline, createCustomRenderer, middleware, hooks, customRenderers }; |