All files / website/public performance.js

0% Statements 0/646
0% Branches 0/1
0% Functions 0/1
0% Lines 0/646

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
// Performance Testing JavaScript - Browser-compatible version
console.log('Loading performance testing functionality...');

// Browser-compatible performance components (adapted from examples/performance-test.js)
const HeavyComponent = ({ depth = 0, maxDepth = 3, label = 'Node' }) => {
    if (depth >= maxDepth) {
        return { 
            span: { 
                text: `${label} ${depth}`,
                className: 'leaf-node'
            } 
        };
    }

    return {
        div: {
            className: `level-${depth} heavy-component`,
            children: [
                { h5: { text: `Level ${depth}` } },
                ...Array.from({ length: 2 }, (_, i) =>
                    HeavyComponent({ depth: depth + 1, maxDepth, label: `${label}-${i}` })
                )
            ]
        }
    };
};

// Data table component for performance testing
const PerformanceDataTable = ({ rows = [], showMetrics = false }) => ({
    div: {
        className: 'data-table-container',
        children: [
            showMetrics && {
                div: {
                    className: 'table-metrics',
                    children: [
                        { p: { text: `Rendering ${rows.length} rows` } },
                        { small: { text: `Memory usage: ~${(rows.length * 0.1).toFixed(1)}KB` } }
                    ]
                }
            },
            {
                table: {
                    className: 'performance-table',
                    children: [
                        {
                            thead: {
                                children: [{
                                    tr: {
                                        children: [
                                            { th: { text: 'ID' } },
                                            { th: { text: 'Name' } },
                                            { th: { text: 'Score' } },
                                            { th: { text: 'Status' } }
                                        ]
                                    }
                                }]
                            }
                        },
                        {
                            tbody: {
                                children: rows.map(row => ({
                                    tr: {
                                        key: row.id,
                                        className: row.status === 'active' ? 'active-row' : '',
                                        children: [
                                            { td: { text: row.id } },
                                            { td: { text: row.name } },
                                            { td: { text: row.score } },
                                            { td: { text: row.status, className: `status-${row.status}` } }
                                        ]
                                    }
                                }))
                            }
                        }
                    ]
                }
            }
        ].filter(Boolean)
    }
});

// Browser-compatible render function
function renderComponent(component) {
    if (typeof component === 'string' || typeof component === 'number') {
        return component.toString();
    }
    
    if (Array.isArray(component)) {
        return component.map(renderComponent).join('');
    }
    
    if (!component || typeof component !== 'object') {
        return '';
    }
    
    const tagName = Object.keys(component)[0];
    const props = component[tagName];
    
    if (!props) return '';
    
    const { children, text, className, ...otherProps } = props;
    
    let html = `<${tagName}`;
    
    // Add className as class attribute
    if (className) {
        html += ` class="${className}"`;
    }
    
    // Add other attributes
    Object.entries(otherProps).forEach(([key, value]) => {
        if (key !== 'children' && key !== 'text') {
            html += ` ${key}="${value}"`;
        }
    });
    
    html += '>';
    
    // Add text content
    if (text) {
        html += text;
    }
    
    // Add children
    if (children) {
        if (Array.isArray(children)) {
            html += children.map(renderComponent).join('');
        } else {
            html += renderComponent(children);
        }
    }
    
    html += `</${tagName}>`;
    return html;
}

// Performance testing state
const perfState = {
    renderCache: new Map(),
    cacheHits: 0,
    cacheMisses: 0,
    metrics: {
        renderTimes: [],
        cacheStats: [],
        memoryUsage: []
    },
    isRunning: false
};

// Cache implementation
function fastHash(obj) {
    const str = JSON.stringify(obj);
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32-bit integer
    }
    return hash;
}

function cachedRender(component, useCache = false) {
    if (useCache) {
        const cacheKey = fastHash(component);
        
        if (perfState.renderCache.has(cacheKey)) {
            perfState.cacheHits++;
            return perfState.renderCache.get(cacheKey);
        }
        
        perfState.cacheMisses++;
        const result = renderComponent(component);
        perfState.renderCache.set(cacheKey, result);
        return result;
    } else {
        perfState.cacheMisses++;
        return renderComponent(component);
    }
}

// UI Update functions
function updateStatus(message, progress = 0) {
    const statusDiv = document.getElementById('test-status');
    const statusMessage = document.getElementById('status-message');
    const progressFill = document.getElementById('progress-fill');
    
    if (statusDiv) statusDiv.style.display = 'block';
    if (statusMessage) statusMessage.textContent = message;
    if (progressFill) progressFill.style.width = `${progress}%`;
}

function showResults(results) {
    const resultsSection = document.getElementById('results-section');
    const testResults = document.getElementById('test-results');
    
    if (resultsSection) resultsSection.style.display = 'block';
    if (testResults) testResults.innerHTML = results;
    
    // Update metric cards
    updateMetricCards();
}

function updateMetricCards() {
    const renderMetrics = document.getElementById('render-metrics');
    const cacheMetrics = document.getElementById('cache-metrics');
    const memoryMetrics = document.getElementById('memory-metrics');
    
    const totalHits = perfState.cacheHits;
    const totalMisses = perfState.cacheMisses;
    const hitRate = totalHits > 0 ? ((totalHits / (totalHits + totalMisses)) * 100).toFixed(1) : 0;
    
    const avgRenderTime = perfState.metrics.renderTimes.length > 0 
        ? (perfState.metrics.renderTimes.reduce((a, b) => a + b, 0) / perfState.metrics.renderTimes.length).toFixed(2)
        : 0;
    
    if (renderMetrics) {
        renderMetrics.innerHTML = `
            <div class="metric-value">${avgRenderTime}ms</div>
            <div class="metric-detail">Average render time</div>
            <div class="metric-detail">${perfState.metrics.renderTimes.length} renders completed</div>
        `;
    }
    
    if (cacheMetrics) {
        cacheMetrics.innerHTML = `
            <div class="metric-value">${hitRate}%</div>
            <div class="metric-detail">Cache hit rate</div>
            <div class="metric-detail">${totalHits} hits, ${totalMisses} misses</div>
        `;
    }
    
    if (memoryMetrics) {
        memoryMetrics.innerHTML = `
            <div class="metric-value">${perfState.renderCache.size}</div>
            <div class="metric-detail">Cached components</div>
            <div class="metric-detail">Memory optimized</div>
        `;
    }
}

// Performance test implementations
async function runPerformanceTests() {
    if (perfState.isRunning) return;
    
    perfState.isRunning = true;
    updateStatus('Starting performance tests...', 0);
    
    try {
        let results = '<div class="test-results-container">';
        
        // Test 1: Basic vs Optimized Rendering
        updateStatus('Running rendering performance test...', 20);
        await new Promise(resolve => setTimeout(resolve, 100));
        
        const testComponent = HeavyComponent({ maxDepth: 4 });
        
        // Clear caches
        perfState.renderCache.clear();
        perfState.cacheHits = 0;
        perfState.cacheMisses = 0;
        
        // Basic rendering (no cache)
        const basicStart = performance.now();
        for (let i = 0; i < 50; i++) {
            cachedRender(testComponent, false);
        }
        const basicEnd = performance.now();
        const basicTime = basicEnd - basicStart;
        const basicCacheStats = { hits: perfState.cacheHits, misses: perfState.cacheMisses };
        
        perfState.metrics.renderTimes.push(basicTime);
        
        // Reset counters for optimized test
        perfState.cacheHits = 0;
        perfState.cacheMisses = 0;
        
        // Optimized rendering (with cache)
        const optimizedStart = performance.now();
        for (let i = 0; i < 50; i++) {
            cachedRender(testComponent, true);
        }
        const optimizedEnd = performance.now();
        const optimizedTime = optimizedEnd - optimizedStart;
        const optimizedCacheStats = { hits: perfState.cacheHits, misses: perfState.cacheMisses };
        
        perfState.metrics.renderTimes.push(optimizedTime);
        
        results += `
            <div class="test-result">
                <h3>📊 Test 1: Rendering Performance</h3>
                <div class="result-grid">
                    <div class="result-item">
                        <strong>Basic rendering (50x):</strong> ${basicTime.toFixed(2)}ms<br>
                        <small>Cache hits: ${basicCacheStats.hits}, misses: ${basicCacheStats.misses}</small>
                    </div>
                    <div class="result-item">
                        <strong>Optimized rendering (50x):</strong> ${optimizedTime.toFixed(2)}ms<br>
                        <small>Cache hits: ${optimizedCacheStats.hits}, misses: ${optimizedCacheStats.misses}</small>
                    </div>
                    <div class="result-highlight">
                        <strong>Performance improvement:</strong> ${((basicTime - optimizedTime) / basicTime * 100).toFixed(2)}%<br>
                        <strong>Cache effectiveness:</strong> ${optimizedCacheStats.hits > 0 ? (optimizedCacheStats.hits / (optimizedCacheStats.hits + optimizedCacheStats.misses) * 100).toFixed(1) : 0}%
                    </div>
                </div>
            </div>
        `;
        
        // Test 2: Data Table Performance
        updateStatus('Running data table performance test...', 60);
        await new Promise(resolve => setTimeout(resolve, 100));
        
        const generateLargeDataset = (size) => Array.from({ length: size }, (_, i) => ({
            id: i + 1,
            name: `User ${i}`,
            score: Math.floor(Math.random() * 1000),
            status: i % 3 === 0 ? 'active' : i % 3 === 1 ? 'pending' : 'inactive'
        }));
        
        const tableData = generateLargeDataset(100);
        const tableComponent = PerformanceDataTable({ rows: tableData, showMetrics: true });
        
        // Cold cache test
        perfState.renderCache.clear();
        const coldStart = performance.now();
        const coldResult = cachedRender(tableComponent, false);
        const coldEnd = performance.now();
        const coldTime = coldEnd - coldStart;
        
        // Warm cache test
        let warmTotalTime = 0;
        const warmRuns = 10;
        for (let i = 0; i < warmRuns; i++) {
            const warmStart = performance.now();
            cachedRender(tableComponent, true);
            const warmEnd = performance.now();
            warmTotalTime += warmEnd - warmStart;
        }
        const warmAvgTime = warmTotalTime / warmRuns;
        
        results += `
            <div class="test-result">
                <h3>💾 Test 2: Data Table Performance</h3>
                <div class="result-grid">
                    <div class="result-item">
                        <strong>Cold cache render:</strong> ${coldTime.toFixed(2)}ms<br>
                        <small>Rendering ${tableData.length} rows</small>
                    </div>
                    <div class="result-item">
                        <strong>Warm cache render (avg):</strong> ${warmAvgTime.toFixed(2)}ms<br>
                        <small>Average of ${warmRuns} renders</small>
                    </div>
                    <div class="result-highlight">
                        <strong>Cache speedup:</strong> ${(coldTime / warmAvgTime).toFixed(2)}x
                    </div>
                </div>
            </div>
        `;
        
        // Test 3: Memory Usage
        updateStatus('Analyzing memory usage...', 90);
        await new Promise(resolve => setTimeout(resolve, 100));
        
        const memoryComponents = Array.from({ length: 20 }, (_, i) => 
            HeavyComponent({ maxDepth: 2, label: `Mem-${i}` })
        );
        
        const memStartTime = performance.now();
        memoryComponents.forEach(comp => {
            cachedRender(comp, true);
        });
        const memEndTime = performance.now();
        const memoryTime = memEndTime - memStartTime;
        
        results += `
            <div class="test-result">
                <h3>🧠 Test 3: Memory & Cache Analysis</h3>
                <div class="result-grid">
                    <div class="result-item">
                        <strong>Components rendered:</strong> ${memoryComponents.length}<br>
                        <strong>Total time:</strong> ${memoryTime.toFixed(2)}ms
                    </div>
                    <div class="result-item">
                        <strong>Cache entries:</strong> ${perfState.renderCache.size}<br>
                        <strong>Hit rate:</strong> ${perfState.cacheHits > 0 ? ((perfState.cacheHits / (perfState.cacheHits + perfState.cacheMisses)) * 100).toFixed(1) : 0}%
                    </div>
                    <div class="result-highlight">
                        <strong>Average per component:</strong> ${(memoryTime / memoryComponents.length).toFixed(2)}ms
                    </div>
                </div>
            </div>
        `;
        
        // Final summary
        const totalHits = perfState.cacheHits;
        const totalMisses = perfState.cacheMisses;
        const overallHitRate = totalHits > 0 ? ((totalHits / (totalHits + totalMisses)) * 100).toFixed(1) : 0;
        
        results += `
            <div class="test-result final-summary">
                <h3>📊 Final Performance Summary</h3>
                <div class="result-grid">
                    <div class="result-item">
                        <strong>Total cache hits:</strong> ${totalHits}<br>
                        <strong>Total cache misses:</strong> ${totalMisses}
                    </div>
                    <div class="result-item">
                        <strong>Overall hit rate:</strong> ${overallHitRate}%<br>
                        <strong>Cached components:</strong> ${perfState.renderCache.size}
                    </div>
                    <div class="result-highlight">
                        <strong>Performance Status:</strong> ${overallHitRate > 70 ? '🟢 Excellent' : overallHitRate > 40 ? '🟡 Good' : '🔴 Needs Optimization'}
                    </div>
                </div>
            </div>
        `;
        
        results += '</div>';
        
        updateStatus('Performance tests completed!', 100);
        showResults(results);
        
    } catch (error) {
        console.error('Performance test error:', error);
        updateStatus('Test failed: ' + error.message, 0);
    } finally {
        perfState.isRunning = false;
        setTimeout(() => {
            const statusDiv = document.getElementById('test-status');
            if (statusDiv) statusDiv.style.display = 'none';
        }, 3000);
    }
}

async function runRenderingTest() {
    if (perfState.isRunning) return;
    
    updateStatus('Running rendering test only...', 0);
    
    const testComponent = HeavyComponent({ maxDepth: 3 });
    const iterations = 100;
    
    const start = performance.now();
    for (let i = 0; i < iterations; i++) {
        cachedRender(testComponent, true);
        updateStatus(`Rendering test: ${i + 1}/${iterations}`, (i + 1) / iterations * 100);
        if (i % 10 === 0) {
            await new Promise(resolve => setTimeout(resolve, 1));
        }
    }
    const end = performance.now();
    
    const results = `
        <div class="test-results-container">
            <div class="test-result">
                <h3>📊 Rendering Performance Test</h3>
                <div class="result-highlight">
                    <strong>Time:</strong> ${(end - start).toFixed(2)}ms for ${iterations} renders<br>
                    <strong>Average:</strong> ${((end - start) / iterations).toFixed(3)}ms per render<br>
                    <strong>Cache hits:</strong> ${perfState.cacheHits}, <strong>misses:</strong> ${perfState.cacheMisses}
                </div>
            </div>
        </div>
    `;
    
    showResults(results);
    updateStatus('Rendering test completed!', 100);
    
    setTimeout(() => {
        const statusDiv = document.getElementById('test-status');
        if (statusDiv) statusDiv.style.display = 'none';
    }, 2000);
}

async function runCacheTest() {
    if (perfState.isRunning) return;
    
    updateStatus('Running cache performance test...', 0);
    
    const testComponent = HeavyComponent({ maxDepth: 2 });
    
    // Test without cache
    perfState.renderCache.clear();
    perfState.cacheHits = 0;
    perfState.cacheMisses = 0;
    
    const noCacheStart = performance.now();
    for (let i = 0; i < 50; i++) {
        cachedRender(testComponent, false);
    }
    const noCacheEnd = performance.now();
    const noCacheTime = noCacheEnd - noCacheStart;
    const noCacheStats = { hits: perfState.cacheHits, misses: perfState.cacheMisses };
    
    updateStatus('Testing with cache...', 50);
    
    // Test with cache
    perfState.cacheHits = 0;
    perfState.cacheMisses = 0;
    
    const withCacheStart = performance.now();
    for (let i = 0; i < 50; i++) {
        cachedRender(testComponent, true);
    }
    const withCacheEnd = performance.now();
    const withCacheTime = withCacheEnd - withCacheStart;
    const withCacheStats = { hits: perfState.cacheHits, misses: perfState.cacheMisses };
    
    const results = `
        <div class="test-results-container">
            <div class="test-result">
                <h3>💾 Cache Performance Test</h3>
                <div class="result-grid">
                    <div class="result-item">
                        <strong>Without cache:</strong> ${noCacheTime.toFixed(2)}ms<br>
                        <small>Hits: ${noCacheStats.hits}, Misses: ${noCacheStats.misses}</small>
                    </div>
                    <div class="result-item">
                        <strong>With cache:</strong> ${withCacheTime.toFixed(2)}ms<br>
                        <small>Hits: ${withCacheStats.hits}, Misses: ${withCacheStats.misses}</small>
                    </div>
                    <div class="result-highlight">
                        <strong>Improvement:</strong> ${((noCacheTime - withCacheTime) / noCacheTime * 100).toFixed(1)}%<br>
                        <strong>Speedup:</strong> ${(noCacheTime / withCacheTime).toFixed(1)}x faster
                    </div>
                </div>
            </div>
        </div>
    `;
    
    showResults(results);
    updateStatus('Cache test completed!', 100);
    
    setTimeout(() => {
        const statusDiv = document.getElementById('test-status');
        if (statusDiv) statusDiv.style.display = 'none';
    }, 2000);
}

function clearResults() {
    const resultsSection = document.getElementById('results-section');
    const testResults = document.getElementById('test-results');
    
    if (resultsSection) resultsSection.style.display = 'none';
    if (testResults) testResults.innerHTML = '';
    
    // Reset metrics
    perfState.renderCache.clear();
    perfState.cacheHits = 0;
    perfState.cacheMisses = 0;
    perfState.metrics = {
        renderTimes: [],
        cacheStats: [],
        memoryUsage: []
    };
    
    // Reset metric cards
    const renderMetrics = document.getElementById('render-metrics');
    const cacheMetrics = document.getElementById('cache-metrics');
    const memoryMetrics = document.getElementById('memory-metrics');
    
    if (renderMetrics) renderMetrics.textContent = 'No data yet - run tests to see results';
    if (cacheMetrics) cacheMetrics.textContent = 'No data yet - run tests to see results';
    if (memoryMetrics) memoryMetrics.textContent = 'No data yet - run tests to see results';
}

// Interactive demo functions
function updateDepthValue(value) {
    const depthValue = document.getElementById('depth-value');
    if (depthValue) depthValue.textContent = value;
}

function updateRowsValue(value) {
    const rowsValue = document.getElementById('rows-value');
    if (rowsValue) rowsValue.textContent = value;
}

async function testHeavyComponent() {
    const depthSlider = document.getElementById('depth-slider');
    const resultDiv = document.getElementById('heavy-component-result');
    
    if (!depthSlider || !resultDiv) return;
    
    const depth = parseInt(depthSlider.value);
    const testComp = HeavyComponent({ maxDepth: depth });
    
    const start = performance.now();
    const html = renderComponent(testComp);
    const end = performance.now();
    const renderTime = end - start;
    
    resultDiv.innerHTML = `
        <div class="demo-result-content">
            <strong>Rendered in ${renderTime.toFixed(2)}ms</strong><br>
            <small>Depth: ${depth}, HTML length: ${html.length} characters</small>
            <details style="margin-top: 10px;">
                <summary>View rendered HTML</summary>
                <div style="max-height: 200px; overflow-y: auto; background: #f5f5f5; padding: 10px; margin-top: 5px; font-family: monospace; font-size: 12px;">
                    ${html.substring(0, 500)}${html.length > 500 ? '...' : ''}
                </div>
            </details>
        </div>
    `;
}

async function testDataTable() {
    const rowsSlider = document.getElementById('rows-slider');
    const resultDiv = document.getElementById('data-table-result');
    
    if (!rowsSlider || !resultDiv) return;
    
    const rowCount = parseInt(rowsSlider.value);
    const tableData = Array.from({ length: rowCount }, (_, i) => ({
        id: i + 1,
        name: `User ${i}`,
        score: Math.floor(Math.random() * 1000),
        status: i % 3 === 0 ? 'active' : i % 3 === 1 ? 'pending' : 'inactive'
    }));
    
    const tableComp = PerformanceDataTable({ rows: tableData, showMetrics: true });
    
    const start = performance.now();
    const html = renderComponent(tableComp);
    const end = performance.now();
    const renderTime = end - start;
    
    resultDiv.innerHTML = `
        <div class="demo-result-content">
            <strong>Rendered ${rowCount} rows in ${renderTime.toFixed(2)}ms</strong><br>
            <small>Average: ${(renderTime / rowCount).toFixed(3)}ms per row</small><br>
            <small>HTML length: ${html.length} characters</small>
        </div>
    `;
}

// Make functions globally available
window.runPerformanceTests = runPerformanceTests;
window.runRenderingTest = runRenderingTest;
window.runCacheTest = runCacheTest;
window.clearResults = clearResults;
window.updateDepthValue = updateDepthValue;
window.updateRowsValue = updateRowsValue;
window.testHeavyComponent = testHeavyComponent;
window.testDataTable = testDataTable;

console.log('✅ Performance testing functionality loaded!');