Initial commit: Performance Trace Analyzer with comprehensive features
🚀 Features implemented: - IndexedDB local database for trace storage and management - Drag & drop trace file upload with validation - HTTP Request viewer with advanced filtering and analysis - CDN provider detection (Cloudflare, Akamai, CloudFront, etc.) - Queue time analysis with bottleneck detection - Visual highlighting for file sizes and request durations - Priority-based request analysis - Phase event viewer with detailed trace exploration - Filmstrip screenshot integration (with debugging) - 3D Babylon.js viewer component 📊 Analysis capabilities: - HTTP/1.1 vs HTTP/2 performance comparison - CDN edge vs origin detection - Connection limit bottleneck identification - Priority queue analysis - Visual correlation with network requests - Performance bottleneck identification 🛠️ Technical stack: - React 19.1.0 + TypeScript 5.8.3 - Vite build system - IndexedDB for local storage - Babylon.js 8+ for 3D visualization - Chrome DevTools trace format support 🎨 User experience: - Clean, professional interface design - Color-coded performance indicators - Expandable detailed views - Search and filtering capabilities - Responsive grid layouts - Intuitive navigation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
1f12b143ef
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
68
CLAUDE.md
Normal file
68
CLAUDE.md
Normal file
@ -0,0 +1,68 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
This is a React + TypeScript + Vite project called "perfviz" - a modern web application built with the latest versions of React (19.1.0), TypeScript (5.8.3), and Vite (7.0.4).
|
||||
|
||||
## Development Commands
|
||||
|
||||
- **Start development server**: `npm run dev` - Runs Vite dev server with HMR on http://localhost:5173/
|
||||
- **Build for production**: `npm run build` - TypeScript compilation followed by Vite build
|
||||
- **Lint code**: `npm run lint` - Run ESLint on the entire codebase
|
||||
- **Preview production build**: `npm run preview` - Preview the production build locally
|
||||
|
||||
## Architecture
|
||||
|
||||
### Build System
|
||||
- **Vite** as the build tool with React plugin for Fast Refresh
|
||||
- **ES modules** configuration (`"type": "module"` in package.json)
|
||||
- **Bundler module resolution** with TypeScript extensions allowed in imports
|
||||
|
||||
### TypeScript Configuration
|
||||
- **Dual TypeScript configs**:
|
||||
- `tsconfig.app.json` for application code (`src/` directory)
|
||||
- `tsconfig.node.json` for build tooling (Vite config)
|
||||
- **Strict TypeScript** with unused locals/parameters checking enabled
|
||||
- **React JSX transform** (`react-jsx`) for React 19+ compatibility
|
||||
|
||||
### Code Quality
|
||||
- **ESLint** with TypeScript support and React-specific rules:
|
||||
- React Hooks rules for proper hooks usage
|
||||
- React Refresh rules for HMR compatibility
|
||||
- TypeScript recommended rules
|
||||
- **Globals configured** for browser environment
|
||||
|
||||
### Application Structure
|
||||
- **Entry point**: `src/main.tsx` renders the App component in React 19 StrictMode
|
||||
- **Root component**: `src/App.tsx` contains the main application logic
|
||||
- **3D Viewer**: `src/BabylonViewer.tsx` React component wrapping Babylon.js 3D scene
|
||||
- **Styling**: CSS modules with `src/index.css` and `src/App.css`
|
||||
- **Assets**: Static assets in `public/` and component assets in `src/assets/`
|
||||
|
||||
## Key Dependencies
|
||||
|
||||
- **React 19.1.0** with modern features and concurrent rendering
|
||||
- **TypeScript 5.8.3** with latest language features
|
||||
- **Vite 7.0.4** for fast development and optimized builds
|
||||
- **ESLint 9.30.1** with typescript-eslint for code quality
|
||||
- **BabylonJS 8.21.1** for 3D graphics and visualization
|
||||
|
||||
## Development Notes
|
||||
|
||||
- The project uses **React 19's new JSX transform** and concurrent features
|
||||
- **HMR (Hot Module Replacement)** is enabled through Vite's React plugin
|
||||
- **Strict mode** is enabled in development for better debugging
|
||||
- **Browser targets** are ES2022+ for modern JavaScript features
|
||||
|
||||
## Babylon.js Integration
|
||||
|
||||
- **Version**: Using Babylon.js 8.21.1 (modern version 8+)
|
||||
- **Camera Management**: Use `scene.activeCamera` instead of deprecated `camera.attachToCanvas()`
|
||||
- **ArcRotateCamera Controls**: Use `camera.attachControl(canvas, true)` for mouse interaction
|
||||
- **Scene Setup**: Cameras, lights, and meshes are added directly to the scene object
|
||||
- **Engine Integration**: Engine handles canvas interaction and render loop
|
||||
- **React Integration**: Proper cleanup with engine disposal in useEffect return function
|
||||
- **Version-Specific Documentation**: ALWAYS check Babylon.js documentation for version 8.21.1 specifically to avoid deprecated methods and ensure current API usage
|
||||
- **API Verification**: Before suggesting any Babylon.js code, verify method signatures and availability in the current version
|
69
README.md
Normal file
69
README.md
Normal file
@ -0,0 +1,69 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default tseslint.config([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
...tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
...tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default tseslint.config([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
23
eslint.config.js
Normal file
23
eslint.config.js
Normal file
@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { globalIgnores } from 'eslint/config'
|
||||
|
||||
export default tseslint.config([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs['recommended-latest'],
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
12
index.html
Normal file
12
index.html
Normal file
@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Perf Viz</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
3383
package-lock.json
generated
Normal file
3383
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
30
package.json
Normal file
30
package.json
Normal file
@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "perfviz",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"babylonjs": "^8.21.1",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.30.1",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"eslint": "^9.30.1",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.20",
|
||||
"globals": "^16.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.35.1",
|
||||
"vite": "^7.0.4"
|
||||
}
|
||||
}
|
1
public/vite.svg
Normal file
1
public/vite.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
After Width: | Height: | Size: 1.5 KiB |
1
src/App.css
Normal file
1
src/App.css
Normal file
@ -0,0 +1 @@
|
||||
|
207
src/App.tsx
Normal file
207
src/App.tsx
Normal file
@ -0,0 +1,207 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import './App.css'
|
||||
import BabylonViewer from './BabylonViewer'
|
||||
import TraceViewer from './components/TraceViewer'
|
||||
import PhaseViewer from './components/PhaseViewer'
|
||||
import HTTPRequestViewer from './components/HTTPRequestViewer'
|
||||
import TraceUpload from './components/TraceUpload'
|
||||
import TraceSelector from './components/TraceSelector'
|
||||
import { traceDatabase } from './utils/traceDatabase'
|
||||
|
||||
type AppView = '3d' | 'trace' | 'phases' | 'http'
|
||||
type AppMode = 'selector' | 'upload' | 'analysis'
|
||||
|
||||
function App() {
|
||||
const [mode, setMode] = useState<AppMode>('selector')
|
||||
const [currentView, setCurrentView] = useState<AppView>('http')
|
||||
const [selectedTraceId, setSelectedTraceId] = useState<string | null>(null)
|
||||
const [hasTraces, setHasTraces] = useState<boolean>(false)
|
||||
const [dbInitialized, setDbInitialized] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
initializeApp()
|
||||
}, [])
|
||||
|
||||
const initializeApp = async () => {
|
||||
try {
|
||||
// Initialize the database
|
||||
await traceDatabase.init()
|
||||
setDbInitialized(true)
|
||||
|
||||
// Check if we have any traces
|
||||
const traces = await traceDatabase.getAllTraces()
|
||||
setHasTraces(traces.length > 0)
|
||||
|
||||
// If no traces, show upload screen
|
||||
if (traces.length === 0) {
|
||||
setMode('upload')
|
||||
} else {
|
||||
setMode('selector')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize database:', error)
|
||||
setMode('upload') // Fallback to upload mode
|
||||
setDbInitialized(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleTraceSelect = (traceId: string) => {
|
||||
setSelectedTraceId(traceId)
|
||||
setMode('analysis')
|
||||
}
|
||||
|
||||
const handleUploadSuccess = (traceId: string) => {
|
||||
setSelectedTraceId(traceId)
|
||||
setMode('analysis')
|
||||
setHasTraces(true)
|
||||
}
|
||||
|
||||
const handleBackToSelector = () => {
|
||||
setSelectedTraceId(null)
|
||||
setMode('selector')
|
||||
}
|
||||
|
||||
const handleUploadNew = () => {
|
||||
setMode('upload')
|
||||
}
|
||||
|
||||
if (!dbInitialized) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '100vh',
|
||||
fontFamily: 'system-ui, sans-serif'
|
||||
}}>
|
||||
<div>Initializing database...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (mode === 'upload') {
|
||||
return <TraceUpload onUploadSuccess={handleUploadSuccess} />
|
||||
}
|
||||
|
||||
if (mode === 'selector') {
|
||||
return (
|
||||
<TraceSelector
|
||||
onTraceSelect={handleTraceSelect}
|
||||
onUploadNew={handleUploadNew}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Analysis mode - show the main interface
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<div style={{
|
||||
padding: '10px 20px',
|
||||
background: '#f8f9fa',
|
||||
borderBottom: '1px solid #dee2e6',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
|
||||
<button
|
||||
onClick={handleBackToSelector}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: '1px solid #6c757d',
|
||||
color: '#6c757d',
|
||||
padding: '6px 12px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '12px'
|
||||
}}
|
||||
>
|
||||
← Back to Traces
|
||||
</button>
|
||||
<h1 style={{ margin: '0', color: '#495057' }}>Perf Viz</h1>
|
||||
</div>
|
||||
|
||||
<nav style={{ display: 'flex', gap: '10px' }}>
|
||||
<button
|
||||
onClick={() => setCurrentView('3d')}
|
||||
style={{
|
||||
background: currentView === '3d' ? '#007bff' : '#6c757d',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 16px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
3D Viewer
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrentView('trace')}
|
||||
style={{
|
||||
background: currentView === 'trace' ? '#007bff' : '#6c757d',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 16px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Trace Stats
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrentView('phases')}
|
||||
style={{
|
||||
background: currentView === 'phases' ? '#007bff' : '#6c757d',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 16px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Phase Events
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setCurrentView('http')}
|
||||
style={{
|
||||
background: currentView === 'http' ? '#007bff' : '#6c757d',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 16px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
HTTP Requests
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{currentView === '3d' && (
|
||||
<div style={{ width: '100%', height: '600px' }}>
|
||||
<BabylonViewer />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentView === 'trace' && (
|
||||
<TraceViewer traceId={selectedTraceId} />
|
||||
)}
|
||||
|
||||
{currentView === 'phases' && (
|
||||
<PhaseViewer traceId={selectedTraceId} />
|
||||
)}
|
||||
|
||||
{currentView === 'http' && (
|
||||
<HTTPRequestViewer traceId={selectedTraceId} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
77
src/BabylonViewer.tsx
Normal file
77
src/BabylonViewer.tsx
Normal file
@ -0,0 +1,77 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import {
|
||||
Engine,
|
||||
Scene,
|
||||
ArcRotateCamera,
|
||||
Vector3,
|
||||
HemisphericLight,
|
||||
MeshBuilder,
|
||||
StandardMaterial,
|
||||
Color3
|
||||
} from 'babylonjs'
|
||||
|
||||
interface BabylonViewerProps {
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
export default function BabylonViewer({ width = 800, height = 600 }: BabylonViewerProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const engineRef = useRef<Engine | null>(null)
|
||||
const sceneRef = useRef<Scene | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!canvasRef.current) return
|
||||
|
||||
const canvas = canvasRef.current
|
||||
const engine = new Engine(canvas, true)
|
||||
engineRef.current = engine
|
||||
|
||||
const scene = new Scene(engine)
|
||||
sceneRef.current = scene
|
||||
|
||||
const camera = new ArcRotateCamera('camera1', -Math.PI / 2, Math.PI / 2.5, 10, Vector3.Zero(), scene)
|
||||
camera.attachControl(canvas, true)
|
||||
scene.activeCamera = camera
|
||||
|
||||
const light = new HemisphericLight('light', new Vector3(0, 1, 0), scene)
|
||||
light.intensity = 0.7
|
||||
|
||||
const sphere = MeshBuilder.CreateSphere('sphere', { diameter: 2 }, scene)
|
||||
sphere.position.y = 1
|
||||
|
||||
const ground = MeshBuilder.CreateGround('ground', { width: 6, height: 6 }, scene)
|
||||
|
||||
const sphereMaterial = new StandardMaterial('sphereMaterial', scene)
|
||||
sphereMaterial.diffuseColor = new Color3(1, 0, 1)
|
||||
sphere.material = sphereMaterial
|
||||
|
||||
const groundMaterial = new StandardMaterial('groundMaterial', scene)
|
||||
groundMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5)
|
||||
ground.material = groundMaterial
|
||||
|
||||
engine.runRenderLoop(() => {
|
||||
scene.render()
|
||||
})
|
||||
|
||||
const handleResize = () => {
|
||||
engine.resize()
|
||||
}
|
||||
|
||||
window.addEventListener('resize', handleResize)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
engine.dispose()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={width}
|
||||
height={height}
|
||||
style={{ width: '100%', height: '100%', display: 'block' }}
|
||||
/>
|
||||
)
|
||||
}
|
1
src/assets/react.svg
Normal file
1
src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
After Width: | Height: | Size: 4.0 KiB |
1518
src/components/HTTPRequestViewer.tsx
Normal file
1518
src/components/HTTPRequestViewer.tsx
Normal file
File diff suppressed because it is too large
Load Diff
537
src/components/PhaseViewer.tsx
Normal file
537
src/components/PhaseViewer.tsx
Normal file
@ -0,0 +1,537 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useDatabaseTraceData } from '../hooks/useDatabaseTraceData'
|
||||
import type { TraceEvent, TraceEventPhase } from '../../types/trace'
|
||||
|
||||
interface ExtendedTraceEvent extends TraceEvent {
|
||||
dur?: number
|
||||
tdur?: number
|
||||
tts?: number
|
||||
}
|
||||
|
||||
const PHASE_DESCRIPTIONS: Record<string, string> = {
|
||||
'M': 'Metadata',
|
||||
'X': 'Complete Events',
|
||||
'I': 'Instant Events',
|
||||
'B': 'Begin Events',
|
||||
'E': 'End Events',
|
||||
'D': 'Deprecated',
|
||||
'b': 'Nestable Start',
|
||||
'e': 'Nestable End',
|
||||
'n': 'Nestable Instant',
|
||||
'S': 'Async Start',
|
||||
'T': 'Async Instant',
|
||||
'F': 'Async End',
|
||||
'P': 'Sample',
|
||||
'C': 'Counter',
|
||||
'R': 'Mark'
|
||||
}
|
||||
|
||||
const ITEMS_PER_PAGE = 50
|
||||
|
||||
// Helper functions to extract valuable fields
|
||||
const getURL = (event: ExtendedTraceEvent): string | null => {
|
||||
const args = event.args as any
|
||||
return args?.url || args?.beginData?.url || args?.data?.frames?.[0]?.url || null
|
||||
}
|
||||
|
||||
const getStackTrace = (event: ExtendedTraceEvent): any[] | null => {
|
||||
const args = event.args as any
|
||||
return args?.beginData?.stackTrace || null
|
||||
}
|
||||
|
||||
const getFrameInfo = (event: ExtendedTraceEvent): string | null => {
|
||||
const args = event.args as any
|
||||
return args?.beginData?.frame || args?.data?.frameTreeNodeId || null
|
||||
}
|
||||
|
||||
const getScriptInfo = (event: ExtendedTraceEvent): { contextId?: number, scriptId?: number } => {
|
||||
const args = event.args as any
|
||||
return {
|
||||
contextId: args?.data?.executionContextId,
|
||||
scriptId: args?.data?.scriptId
|
||||
}
|
||||
}
|
||||
|
||||
const getLayoutInfo = (event: ExtendedTraceEvent): { dirtyObjects?: number, totalObjects?: number, elementCount?: number } => {
|
||||
const args = event.args as any
|
||||
return {
|
||||
dirtyObjects: args?.beginData?.dirtyObjects,
|
||||
totalObjects: args?.beginData?.totalObjects,
|
||||
elementCount: args?.elementCount
|
||||
}
|
||||
}
|
||||
|
||||
const getSampleTraceId = (event: ExtendedTraceEvent): number | null => {
|
||||
const args = event.args as any
|
||||
return args?.beginData?.sampleTraceId || null
|
||||
}
|
||||
|
||||
interface PhaseViewerProps {
|
||||
traceId: string | null
|
||||
}
|
||||
|
||||
export default function PhaseViewer({ traceId }: PhaseViewerProps) {
|
||||
const { traceData, loading, error, stats } = useDatabaseTraceData(traceId)
|
||||
const [selectedPhase, setSelectedPhase] = useState<string>('all')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set())
|
||||
|
||||
const filteredEvents = useMemo(() => {
|
||||
if (!traceData) return []
|
||||
|
||||
let events = traceData.traceEvents
|
||||
|
||||
// Filter by phase
|
||||
if (selectedPhase !== 'all') {
|
||||
events = events.filter(event => event.ph === selectedPhase)
|
||||
}
|
||||
|
||||
// Filter by search term
|
||||
if (searchTerm) {
|
||||
const term = searchTerm.toLowerCase()
|
||||
events = events.filter(event =>
|
||||
event.name.toLowerCase().includes(term) ||
|
||||
event.cat.toLowerCase().includes(term) ||
|
||||
event.pid.toString().includes(term) ||
|
||||
event.tid.toString().includes(term)
|
||||
)
|
||||
}
|
||||
|
||||
return events
|
||||
}, [traceData, selectedPhase, searchTerm])
|
||||
|
||||
const paginatedEvents = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
|
||||
const endIndex = startIndex + ITEMS_PER_PAGE
|
||||
return filteredEvents.slice(startIndex, endIndex)
|
||||
}, [filteredEvents, currentPage])
|
||||
|
||||
const totalPages = Math.ceil(filteredEvents.length / ITEMS_PER_PAGE)
|
||||
|
||||
const formatTimestamp = (ts: number) => {
|
||||
return (ts / 1000).toFixed(3) + 'ms'
|
||||
}
|
||||
|
||||
const formatDuration = (dur?: number) => {
|
||||
if (!dur) return '-'
|
||||
return (dur / 1000).toFixed(3) + 'ms'
|
||||
}
|
||||
|
||||
const formatThreadTime = (tts?: number) => {
|
||||
if (!tts) return '-'
|
||||
return (tts / 1000).toFixed(3) + 'ms'
|
||||
}
|
||||
|
||||
const toggleRowExpansion = (eventKey: string) => {
|
||||
const newExpanded = new Set(expandedRows)
|
||||
if (newExpanded.has(eventKey)) {
|
||||
newExpanded.delete(eventKey)
|
||||
} else {
|
||||
newExpanded.add(eventKey)
|
||||
}
|
||||
setExpandedRows(newExpanded)
|
||||
}
|
||||
|
||||
const truncateText = (text: string, maxLength: number = 50) => {
|
||||
if (text.length <= maxLength) return text
|
||||
return text.substring(0, maxLength) + '...'
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '400px',
|
||||
fontSize: '18px',
|
||||
color: '#6c757d'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '50px',
|
||||
height: '50px',
|
||||
border: '4px solid #f3f3f3',
|
||||
borderTop: '4px solid #007bff',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
marginBottom: '20px'
|
||||
}} />
|
||||
<div>Loading trace events...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div style={{ padding: '20px', textAlign: 'center' }}>
|
||||
<div style={{
|
||||
background: '#f8d7da',
|
||||
color: '#721c24',
|
||||
padding: '15px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #f5c6cb'
|
||||
}}>
|
||||
<h3>Error Loading Trace Data</h3>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!traceData || !stats) {
|
||||
return <div style={{ padding: '20px', textAlign: 'center' }}>No trace data available</div>
|
||||
}
|
||||
|
||||
const phaseOptions = Object.keys(stats.eventsByPhase).sort()
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px', fontFamily: 'system-ui, sans-serif' }}>
|
||||
<h2>Phase Event Viewer</h2>
|
||||
|
||||
{/* Controls */}
|
||||
<div style={{
|
||||
background: '#f8f9fa',
|
||||
padding: '20px',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '20px',
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '15px',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
{/* Phase Filter */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ fontWeight: 'bold', fontSize: '14px' }}>Filter by Phase:</label>
|
||||
<select
|
||||
value={selectedPhase}
|
||||
onChange={(e) => {
|
||||
setSelectedPhase(e.target.value)
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '4px',
|
||||
fontSize: '14px',
|
||||
minWidth: '200px'
|
||||
}}
|
||||
>
|
||||
<option value="all">All Phases ({stats.totalEvents.toLocaleString()})</option>
|
||||
{phaseOptions.map(phase => (
|
||||
<option key={phase} value={phase}>
|
||||
{phase} - {PHASE_DESCRIPTIONS[phase] || 'Unknown'} ({stats.eventsByPhase[phase].toLocaleString()})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ fontWeight: 'bold', fontSize: '14px' }}>Search:</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name, category, PID, or TID..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value)
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '4px',
|
||||
fontSize: '14px',
|
||||
minWidth: '300px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Results count */}
|
||||
<div style={{
|
||||
marginLeft: 'auto',
|
||||
fontSize: '14px',
|
||||
color: '#6c757d',
|
||||
fontWeight: 'bold'
|
||||
}}>
|
||||
{filteredEvents.length.toLocaleString()} events found
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pagination Controls */}
|
||||
{totalPages > 1 && (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
gap: '10px',
|
||||
marginBottom: '20px'
|
||||
}}>
|
||||
<button
|
||||
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
|
||||
disabled={currentPage === 1}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '4px',
|
||||
background: currentPage === 1 ? '#e9ecef' : '#fff',
|
||||
cursor: currentPage === 1 ? 'not-allowed' : 'pointer'
|
||||
}}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
|
||||
<span style={{ margin: '0 15px', fontSize: '14px' }}>
|
||||
Page {currentPage} of {totalPages}
|
||||
</span>
|
||||
|
||||
<button
|
||||
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
|
||||
disabled={currentPage === totalPages}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
border: '1px solid #ced4da',
|
||||
borderRadius: '4px',
|
||||
background: currentPage === totalPages ? '#e9ecef' : '#fff',
|
||||
cursor: currentPage === totalPages ? 'not-allowed' : 'pointer'
|
||||
}}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Events Table */}
|
||||
<div style={{
|
||||
background: 'white',
|
||||
border: '1px solid #dee2e6',
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#f8f9fa' }}>
|
||||
<th style={{ padding: '8px', textAlign: 'center', borderBottom: '1px solid #dee2e6', fontSize: '12px', width: '30px' }}>Expand</th>
|
||||
<th style={{ padding: '8px', textAlign: 'center', borderBottom: '1px solid #dee2e6', fontSize: '12px', width: '50px' }}>Phase</th>
|
||||
<th style={{ padding: '8px', textAlign: 'left', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>Name</th>
|
||||
<th style={{ padding: '8px', textAlign: 'left', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>Category</th>
|
||||
<th style={{ padding: '8px', textAlign: 'right', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>Duration</th>
|
||||
<th style={{ padding: '8px', textAlign: 'right', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>Thread Time</th>
|
||||
<th style={{ padding: '8px', textAlign: 'left', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>URL</th>
|
||||
<th style={{ padding: '8px', textAlign: 'right', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>PID</th>
|
||||
<th style={{ padding: '8px', textAlign: 'right', borderBottom: '1px solid #dee2e6', fontSize: '12px' }}>TID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{paginatedEvents.map((event, index) => {
|
||||
const eventKey = `${event.pid}-${event.tid}-${event.ts}-${index}`
|
||||
const isExpanded = expandedRows.has(eventKey)
|
||||
const url = getURL(event as ExtendedTraceEvent)
|
||||
const stackTrace = getStackTrace(event as ExtendedTraceEvent)
|
||||
const layoutInfo = getLayoutInfo(event as ExtendedTraceEvent)
|
||||
const scriptInfo = getScriptInfo(event as ExtendedTraceEvent)
|
||||
const sampleTraceId = getSampleTraceId(event as ExtendedTraceEvent)
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr key={eventKey} style={{
|
||||
borderBottom: '1px solid #f1f3f4',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
onClick={() => toggleRowExpansion(eventKey)}
|
||||
>
|
||||
<td style={{
|
||||
padding: '8px',
|
||||
textAlign: 'center',
|
||||
fontSize: '12px',
|
||||
color: '#007bff',
|
||||
fontWeight: 'bold'
|
||||
}}>
|
||||
{isExpanded ? '−' : '+'}
|
||||
</td>
|
||||
<td style={{
|
||||
padding: '8px',
|
||||
fontSize: '12px',
|
||||
fontFamily: 'monospace',
|
||||
background: getPhaseColor(event.ph),
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
{event.ph}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{event.name}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', color: '#6c757d', maxWidth: '120px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{event.cat}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', textAlign: 'right', fontFamily: 'monospace' }}>
|
||||
{formatDuration((event as ExtendedTraceEvent).dur)}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', textAlign: 'right', fontFamily: 'monospace' }}>
|
||||
{formatThreadTime((event as ExtendedTraceEvent).tts)}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '11px', color: '#007bff', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{url ? (
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#007bff', textDecoration: 'none' }}>
|
||||
{truncateText(url, 40)}
|
||||
</a>
|
||||
) : '-'}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', textAlign: 'right', fontFamily: 'monospace' }}>
|
||||
{event.pid}
|
||||
</td>
|
||||
<td style={{ padding: '8px', fontSize: '12px', textAlign: 'right', fontFamily: 'monospace' }}>
|
||||
{event.tid}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
{/* Expanded Row Details */}
|
||||
{isExpanded && (
|
||||
<tr key={`${eventKey}-expanded`}>
|
||||
<td colSpan={9} style={{
|
||||
padding: '15px',
|
||||
background: '#f8f9fa',
|
||||
border: '1px solid #e9ecef'
|
||||
}}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '15px' }}>
|
||||
|
||||
{/* Timing Information */}
|
||||
<div style={{ background: 'white', padding: '10px', borderRadius: '4px', border: '1px solid #dee2e6' }}>
|
||||
<h4 style={{ margin: '0 0 8px 0', color: '#495057', fontSize: '14px' }}>Timing</h4>
|
||||
<div style={{ fontSize: '12px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
<div><strong>Timestamp:</strong> {formatTimestamp(event.ts)}</div>
|
||||
<div><strong>Duration:</strong> {formatDuration((event as ExtendedTraceEvent).dur)}</div>
|
||||
<div><strong>Thread Duration:</strong> {formatDuration((event as ExtendedTraceEvent).tdur)}</div>
|
||||
<div><strong>Thread Time:</strong> {formatThreadTime((event as ExtendedTraceEvent).tts)}</div>
|
||||
{sampleTraceId && <div><strong>Sample Trace ID:</strong> {sampleTraceId}</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Script/Context Information */}
|
||||
{(scriptInfo.contextId || scriptInfo.scriptId) && (
|
||||
<div style={{ background: 'white', padding: '10px', borderRadius: '4px', border: '1px solid #dee2e6' }}>
|
||||
<h4 style={{ margin: '0 0 8px 0', color: '#495057', fontSize: '14px' }}>Script Context</h4>
|
||||
<div style={{ fontSize: '12px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
{scriptInfo.contextId && <div><strong>Execution Context:</strong> {scriptInfo.contextId}</div>}
|
||||
{scriptInfo.scriptId && <div><strong>Script ID:</strong> {scriptInfo.scriptId}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Layout Information */}
|
||||
{(layoutInfo.dirtyObjects || layoutInfo.totalObjects || layoutInfo.elementCount) && (
|
||||
<div style={{ background: 'white', padding: '10px', borderRadius: '4px', border: '1px solid #dee2e6' }}>
|
||||
<h4 style={{ margin: '0 0 8px 0', color: '#495057', fontSize: '14px' }}>Layout Metrics</h4>
|
||||
<div style={{ fontSize: '12px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
{layoutInfo.dirtyObjects && <div><strong>Dirty Objects:</strong> {layoutInfo.dirtyObjects}</div>}
|
||||
{layoutInfo.totalObjects && <div><strong>Total Objects:</strong> {layoutInfo.totalObjects}</div>}
|
||||
{layoutInfo.elementCount && <div><strong>Element Count:</strong> {layoutInfo.elementCount}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stack Trace */}
|
||||
{stackTrace && stackTrace.length > 0 && (
|
||||
<div style={{
|
||||
background: 'white',
|
||||
padding: '10px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #dee2e6',
|
||||
gridColumn: '1 / -1'
|
||||
}}>
|
||||
<h4 style={{ margin: '0 0 8px 0', color: '#495057', fontSize: '14px' }}>
|
||||
Stack Trace ({stackTrace.length} frames)
|
||||
</h4>
|
||||
<div style={{
|
||||
maxHeight: '200px',
|
||||
overflowY: 'auto',
|
||||
fontSize: '11px',
|
||||
fontFamily: 'monospace',
|
||||
background: '#f8f9fa',
|
||||
padding: '8px',
|
||||
borderRadius: '3px'
|
||||
}}>
|
||||
{stackTrace.slice(0, 10).map((frame: any, frameIndex: number) => (
|
||||
<div key={frameIndex} style={{
|
||||
marginBottom: '4px',
|
||||
paddingBottom: '4px',
|
||||
borderBottom: frameIndex < Math.min(stackTrace.length, 10) - 1 ? '1px solid #e9ecef' : 'none'
|
||||
}}>
|
||||
<div style={{ color: '#007bff', fontWeight: 'bold' }}>
|
||||
{frame.functionName || '(anonymous)'}
|
||||
</div>
|
||||
<div style={{ color: '#6c757d' }}>
|
||||
{frame.url ? truncateText(frame.url, 80) : 'unknown'}
|
||||
{frame.lineNumber && `:${frame.lineNumber}`}
|
||||
{frame.columnNumber && `:${frame.columnNumber}`}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{stackTrace.length > 10 && (
|
||||
<div style={{ color: '#6c757d', fontStyle: 'italic', marginTop: '8px' }}>
|
||||
... and {stackTrace.length - 10} more frames
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{paginatedEvents.length === 0 && (
|
||||
<div style={{
|
||||
textAlign: 'center',
|
||||
padding: '40px',
|
||||
color: '#6c757d',
|
||||
fontSize: '16px'
|
||||
}}>
|
||||
No events found matching the current filters
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background: #f8f9fa !important;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function getPhaseColor(phase: TraceEventPhase): string {
|
||||
const colors: Record<string, string> = {
|
||||
'M': '#6c757d', // Metadata - gray
|
||||
'X': '#007bff', // Complete - blue
|
||||
'I': '#28a745', // Instant - green
|
||||
'B': '#ffc107', // Begin - yellow
|
||||
'E': '#fd7e14', // End - orange
|
||||
'D': '#6f42c1', // Deprecated - purple
|
||||
'b': '#20c997', // Nestable start - teal
|
||||
'e': '#e83e8c', // Nestable end - pink
|
||||
'n': '#17a2b8', // Nestable instant - cyan
|
||||
'S': '#dc3545', // Async start - red
|
||||
'T': '#ffc107', // Async instant - warning
|
||||
'F': '#fd7e14', // Async end - orange
|
||||
'P': '#6f42c1', // Sample - purple
|
||||
'C': '#20c997', // Counter - teal
|
||||
'R': '#e83e8c' // Mark - pink
|
||||
}
|
||||
return colors[phase] || '#6c757d'
|
||||
}
|
331
src/components/TraceSelector.tsx
Normal file
331
src/components/TraceSelector.tsx
Normal file
@ -0,0 +1,331 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { traceDatabase, type TraceRecord } from '../utils/traceDatabase'
|
||||
|
||||
interface TraceSelectorProps {
|
||||
onTraceSelect: (traceId: string) => void
|
||||
onUploadNew: () => void
|
||||
}
|
||||
|
||||
export default function TraceSelector({ onTraceSelect, onUploadNew }: TraceSelectorProps) {
|
||||
const [traces, setTraces] = useState<TraceRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editingName, setEditingName] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
loadTraces()
|
||||
}, [])
|
||||
|
||||
const loadTraces = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const allTraces = await traceDatabase.getAllTraces()
|
||||
// Sort by upload date (newest first)
|
||||
allTraces.sort((a, b) => b.uploadedAt.getTime() - a.uploadedAt.getTime())
|
||||
setTraces(allTraces)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load traces')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (confirm('Are you sure you want to delete this trace? This action cannot be undone.')) {
|
||||
try {
|
||||
await traceDatabase.deleteTrace(id)
|
||||
setTraces(traces.filter(t => t.id !== id))
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete trace')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRename = async (id: string, newName: string) => {
|
||||
if (!newName.trim()) return
|
||||
|
||||
try {
|
||||
await traceDatabase.updateTraceName(id, newName.trim())
|
||||
setTraces(traces.map(t => t.id === id ? { ...t, name: newName.trim() } : t))
|
||||
setEditingId(null)
|
||||
setEditingName('')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to rename trace')
|
||||
}
|
||||
}
|
||||
|
||||
const startEdit = (trace: TraceRecord) => {
|
||||
setEditingId(trace.id)
|
||||
setEditingName(trace.name)
|
||||
}
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null)
|
||||
setEditingName('')
|
||||
}
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const formatDuration = (microseconds: number) => {
|
||||
const seconds = microseconds / 1000000
|
||||
if (seconds < 60) return `${seconds.toFixed(1)}s`
|
||||
const minutes = seconds / 60
|
||||
return `${minutes.toFixed(1)}m`
|
||||
}
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '200px',
|
||||
fontFamily: 'system-ui, sans-serif'
|
||||
}}>
|
||||
<div>Loading traces...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
padding: '20px',
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
maxWidth: '1000px',
|
||||
margin: '0 auto'
|
||||
}}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: '24px'
|
||||
}}>
|
||||
<h1 style={{
|
||||
fontSize: '24px',
|
||||
color: '#495057',
|
||||
margin: '0',
|
||||
fontWeight: '600'
|
||||
}}>
|
||||
Performance Traces ({traces.length})
|
||||
</h1>
|
||||
|
||||
<button
|
||||
onClick={onUploadNew}
|
||||
style={{
|
||||
background: '#007bff',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '10px 20px',
|
||||
borderRadius: '6px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: '500'
|
||||
}}
|
||||
>
|
||||
+ Upload New Trace
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
marginBottom: '20px',
|
||||
padding: '12px 16px',
|
||||
backgroundColor: '#f8d7da',
|
||||
color: '#721c24',
|
||||
border: '1px solid #f5c6cb',
|
||||
borderRadius: '6px',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{traces.length === 0 ? (
|
||||
<div style={{
|
||||
textAlign: 'center',
|
||||
padding: '60px 20px',
|
||||
backgroundColor: '#f8f9fa',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #dee2e6'
|
||||
}}>
|
||||
<div style={{ fontSize: '48px', marginBottom: '16px' }}>📊</div>
|
||||
<h3 style={{
|
||||
color: '#495057',
|
||||
marginBottom: '8px',
|
||||
fontSize: '18px',
|
||||
fontWeight: '600'
|
||||
}}>
|
||||
No traces found
|
||||
</h3>
|
||||
<p style={{
|
||||
color: '#6c757d',
|
||||
marginBottom: '20px',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
Upload your first Chrome DevTools Performance trace to get started.
|
||||
</p>
|
||||
<button
|
||||
onClick={onUploadNew}
|
||||
style={{
|
||||
background: '#007bff',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '12px 24px',
|
||||
borderRadius: '6px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: '500'
|
||||
}}
|
||||
>
|
||||
Upload Trace File
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{
|
||||
display: 'grid',
|
||||
gap: '16px',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))'
|
||||
}}>
|
||||
{traces.map((trace) => (
|
||||
<div
|
||||
key={trace.id}
|
||||
style={{
|
||||
background: 'white',
|
||||
border: '1px solid #dee2e6',
|
||||
borderRadius: '8px',
|
||||
padding: '20px',
|
||||
cursor: 'pointer',
|
||||
transition: 'all 0.2s ease',
|
||||
boxShadow: '0 2px 4px rgba(0,0,0,0.05)'
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.borderColor = '#007bff'
|
||||
e.currentTarget.style.boxShadow = '0 4px 8px rgba(0,123,255,0.15)'
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.borderColor = '#dee2e6'
|
||||
e.currentTarget.style.boxShadow = '0 2px 4px rgba(0,0,0,0.05)'
|
||||
}}
|
||||
onClick={() => onTraceSelect(trace.id)}
|
||||
>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: '12px'
|
||||
}}>
|
||||
{editingId === trace.id ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editingName}
|
||||
onChange={(e) => setEditingName(e.target.value)}
|
||||
onBlur={() => handleRename(trace.id, editingName)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleRename(trace.id, editingName)
|
||||
if (e.key === 'Escape') cancelEdit()
|
||||
e.stopPropagation()
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
autoFocus
|
||||
style={{
|
||||
fontSize: '16px',
|
||||
fontWeight: '600',
|
||||
border: '1px solid #007bff',
|
||||
borderRadius: '4px',
|
||||
padding: '4px 8px',
|
||||
background: 'white',
|
||||
outline: 'none'
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<h3
|
||||
style={{
|
||||
fontSize: '16px',
|
||||
fontWeight: '600',
|
||||
color: '#495057',
|
||||
margin: '0',
|
||||
wordBreak: 'break-word'
|
||||
}}
|
||||
>
|
||||
{trace.name}
|
||||
</h3>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
startEdit(trace)
|
||||
}}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
color: '#6c757d',
|
||||
padding: '4px'
|
||||
}}
|
||||
title="Rename"
|
||||
>
|
||||
✏️
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDelete(trace.id)
|
||||
}}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
color: '#dc3545',
|
||||
padding: '4px'
|
||||
}}
|
||||
title="Delete"
|
||||
>
|
||||
🗑️
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '1fr 1fr',
|
||||
gap: '8px',
|
||||
fontSize: '13px',
|
||||
color: '#6c757d'
|
||||
}}>
|
||||
<div><strong>Events:</strong> {trace.eventCount.toLocaleString()}</div>
|
||||
<div><strong>Size:</strong> {formatFileSize(trace.fileSize)}</div>
|
||||
<div><strong>Duration:</strong> {formatDuration(trace.duration)}</div>
|
||||
<div><strong>Uploaded:</strong> {formatDate(trace.uploadedAt)}</div>
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
marginTop: '12px',
|
||||
fontSize: '12px',
|
||||
color: '#868e96',
|
||||
textAlign: 'right'
|
||||
}}>
|
||||
Click to analyze →
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
165
src/components/TraceStats.tsx
Normal file
165
src/components/TraceStats.tsx
Normal file
@ -0,0 +1,165 @@
|
||||
import { getTraceStats } from '../utils/traceLoader'
|
||||
|
||||
interface TraceStatsProps {
|
||||
stats: ReturnType<typeof getTraceStats>
|
||||
}
|
||||
|
||||
export default function TraceStats({ stats }: TraceStatsProps) {
|
||||
const formatNumber = (num: number) => {
|
||||
return new Intl.NumberFormat().format(num)
|
||||
}
|
||||
|
||||
const formatDuration = (microseconds: number) => {
|
||||
const milliseconds = microseconds / 1000
|
||||
if (milliseconds < 1000) {
|
||||
return `${milliseconds.toFixed(2)}ms`
|
||||
}
|
||||
const seconds = milliseconds / 1000
|
||||
return `${seconds.toFixed(2)}s`
|
||||
}
|
||||
|
||||
const formatTimestamp = (timestamp: number) => {
|
||||
return new Date(timestamp / 1000).toLocaleString()
|
||||
}
|
||||
|
||||
const getPhaseDescription = (phase: string) => {
|
||||
const descriptions: Record<string, string> = {
|
||||
'M': 'Metadata',
|
||||
'X': 'Complete Events',
|
||||
'I': 'Instant Events',
|
||||
'B': 'Begin Events',
|
||||
'E': 'End Events',
|
||||
'D': 'Deprecated',
|
||||
'b': 'Nestable Start',
|
||||
'e': 'Nestable End',
|
||||
'n': 'Nestable Instant',
|
||||
'S': 'Async Start',
|
||||
'T': 'Async Instant',
|
||||
'F': 'Async End',
|
||||
'P': 'Sample',
|
||||
'C': 'Counter',
|
||||
'R': 'Mark'
|
||||
}
|
||||
return descriptions[phase] || `Unknown (${phase})`
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
padding: '20px',
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
maxWidth: '800px',
|
||||
margin: '0 auto'
|
||||
}}>
|
||||
<h2 style={{ marginBottom: '20px', color: '#333' }}>Trace Statistics</h2>
|
||||
|
||||
<div style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
|
||||
gap: '20px',
|
||||
marginBottom: '30px'
|
||||
}}>
|
||||
{/* Overview Section */}
|
||||
<div style={{
|
||||
background: '#f8f9fa',
|
||||
padding: '15px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e9ecef'
|
||||
}}>
|
||||
<h3 style={{ marginTop: '0', color: '#495057' }}>Overview</h3>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
<div><strong>Total Events:</strong> {formatNumber(stats.totalEvents)}</div>
|
||||
<div><strong>Processes:</strong> {stats.processCount}</div>
|
||||
<div><strong>Threads:</strong> {stats.threadCount}</div>
|
||||
<div><strong>Duration:</strong> {formatDuration(stats.timeRange.duration)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Metadata Section */}
|
||||
<div style={{
|
||||
background: '#f8f9fa',
|
||||
padding: '15px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e9ecef'
|
||||
}}>
|
||||
<h3 style={{ marginTop: '0', color: '#495057' }}>Metadata</h3>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
<div><strong>Source:</strong> {stats.metadata.source}</div>
|
||||
<div><strong>Hardware Threads:</strong> {stats.metadata.hardwareConcurrency}</div>
|
||||
<div><strong>Start Time:</strong> {new Date(stats.metadata.startTime).toLocaleString()}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Time Range Section */}
|
||||
<div style={{
|
||||
background: '#f8f9fa',
|
||||
padding: '15px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e9ecef'
|
||||
}}>
|
||||
<h3 style={{ marginTop: '0', color: '#495057' }}>Time Range</h3>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '12px' }}>
|
||||
<div><strong>Start:</strong> {formatTimestamp(stats.timeRange.start)}</div>
|
||||
<div><strong>End:</strong> {formatTimestamp(stats.timeRange.end)}</div>
|
||||
<div><strong>Duration:</strong> {formatDuration(stats.timeRange.duration)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Event Types Section */}
|
||||
<div style={{
|
||||
background: '#f8f9fa',
|
||||
padding: '20px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e9ecef'
|
||||
}}>
|
||||
<h3 style={{ marginTop: '0', color: '#495057' }}>Events by Type</h3>
|
||||
<div style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
|
||||
gap: '10px'
|
||||
}}>
|
||||
{Object.entries(stats.eventsByPhase)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([phase, count]) => (
|
||||
<div key={phase} style={{
|
||||
background: 'white',
|
||||
padding: '10px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #dee2e6',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '4px'
|
||||
}}>
|
||||
<div style={{
|
||||
fontWeight: 'bold',
|
||||
color: '#495057',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
{getPhaseDescription(phase)}
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
color: '#6c757d'
|
||||
}}>
|
||||
Phase: {phase}
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '16px',
|
||||
fontWeight: 'bold',
|
||||
color: '#007bff'
|
||||
}}>
|
||||
{formatNumber(count)}
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '11px',
|
||||
color: '#6c757d'
|
||||
}}>
|
||||
{((count / stats.totalEvents) * 100).toFixed(1)}%
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
247
src/components/TraceUpload.tsx
Normal file
247
src/components/TraceUpload.tsx
Normal file
@ -0,0 +1,247 @@
|
||||
import { useState } from 'react'
|
||||
import type { TraceFile } from '../../types/trace'
|
||||
import { traceDatabase } from '../utils/traceDatabase'
|
||||
|
||||
interface TraceUploadProps {
|
||||
onUploadSuccess: (traceId: string) => void
|
||||
}
|
||||
|
||||
export default function TraceUpload({ onUploadSuccess }: TraceUploadProps) {
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const validateTraceFile = (data: any): data is TraceFile => {
|
||||
return data &&
|
||||
data.metadata &&
|
||||
Array.isArray(data.traceEvents) &&
|
||||
data.traceEvents.length > 0
|
||||
}
|
||||
|
||||
const processFile = async (file: File) => {
|
||||
setUploading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
// Validate file type
|
||||
if (!file.name.toLowerCase().endsWith('.json')) {
|
||||
throw new Error('Please upload a JSON trace file')
|
||||
}
|
||||
|
||||
// Validate file size (max 200MB)
|
||||
if (file.size > 200 * 1024 * 1024) {
|
||||
throw new Error('Trace file too large (max 200MB)')
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const text = await file.text()
|
||||
|
||||
// Parse JSON
|
||||
let traceData: TraceFile
|
||||
try {
|
||||
traceData = JSON.parse(text)
|
||||
} catch (parseError) {
|
||||
throw new Error('Invalid JSON format')
|
||||
}
|
||||
|
||||
// Validate trace structure
|
||||
if (!validateTraceFile(traceData)) {
|
||||
throw new Error('Invalid trace file format. Expected Chrome DevTools Performance trace.')
|
||||
}
|
||||
|
||||
// Store in database
|
||||
const traceId = await traceDatabase.addTrace(traceData, file.name, file.size)
|
||||
|
||||
onUploadSuccess(traceId)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
processFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDrop = (event: React.DragEvent) => {
|
||||
event.preventDefault()
|
||||
setDragOver(false)
|
||||
|
||||
const file = event.dataTransfer.files[0]
|
||||
if (file) {
|
||||
processFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (event: React.DragEvent) => {
|
||||
event.preventDefault()
|
||||
setDragOver(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (event: React.DragEvent) => {
|
||||
event.preventDefault()
|
||||
setDragOver(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: '400px',
|
||||
padding: '40px',
|
||||
fontFamily: 'system-ui, sans-serif'
|
||||
}}>
|
||||
<div style={{
|
||||
maxWidth: '600px',
|
||||
textAlign: 'center',
|
||||
marginBottom: '30px'
|
||||
}}>
|
||||
<h1 style={{
|
||||
fontSize: '28px',
|
||||
color: '#495057',
|
||||
marginBottom: '16px',
|
||||
fontWeight: '600'
|
||||
}}>
|
||||
Performance Trace Analyzer
|
||||
</h1>
|
||||
<p style={{
|
||||
fontSize: '16px',
|
||||
color: '#6c757d',
|
||||
lineHeight: '1.5',
|
||||
marginBottom: '24px'
|
||||
}}>
|
||||
Upload Chrome DevTools Performance trace files to analyze network requests,
|
||||
queue times, CDN usage, and performance bottlenecks.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
border: dragOver ? '2px dashed #007bff' : '2px dashed #dee2e6',
|
||||
borderRadius: '12px',
|
||||
padding: '40px',
|
||||
backgroundColor: dragOver ? '#f8f9ff' : '#f8f9fa',
|
||||
transition: 'all 0.2s ease',
|
||||
cursor: 'pointer',
|
||||
minWidth: '400px',
|
||||
textAlign: 'center'
|
||||
}}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onClick={() => document.getElementById('trace-upload')?.click()}
|
||||
>
|
||||
{uploading ? (
|
||||
<div>
|
||||
<div style={{
|
||||
width: '40px',
|
||||
height: '40px',
|
||||
border: '4px solid #f3f3f3',
|
||||
borderTop: '4px solid #007bff',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
margin: '0 auto 20px'
|
||||
}} />
|
||||
<div style={{ fontSize: '16px', color: '#495057' }}>
|
||||
Processing trace file...
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div style={{ fontSize: '48px', marginBottom: '16px' }}>📊</div>
|
||||
<div style={{
|
||||
fontSize: '18px',
|
||||
fontWeight: '600',
|
||||
color: '#495057',
|
||||
marginBottom: '8px'
|
||||
}}>
|
||||
Drop your trace file here
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
color: '#6c757d',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
or click to browse files
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
color: '#868e96',
|
||||
marginTop: '16px'
|
||||
}}>
|
||||
Supports JSON trace files up to 200MB
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
id="trace-upload"
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleFileSelect}
|
||||
style={{ display: 'none' }}
|
||||
disabled={uploading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
marginTop: '20px',
|
||||
padding: '12px 20px',
|
||||
backgroundColor: '#f8d7da',
|
||||
color: '#721c24',
|
||||
border: '1px solid #f5c6cb',
|
||||
borderRadius: '8px',
|
||||
fontSize: '14px',
|
||||
maxWidth: '400px',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{
|
||||
marginTop: '40px',
|
||||
padding: '20px',
|
||||
backgroundColor: '#e9ecef',
|
||||
borderRadius: '8px',
|
||||
maxWidth: '500px'
|
||||
}}>
|
||||
<h3 style={{
|
||||
fontSize: '16px',
|
||||
color: '#495057',
|
||||
marginBottom: '12px',
|
||||
marginTop: '0'
|
||||
}}>
|
||||
How to capture a trace:
|
||||
</h3>
|
||||
<ol style={{
|
||||
fontSize: '14px',
|
||||
color: '#6c757d',
|
||||
lineHeight: '1.6',
|
||||
paddingLeft: '20px',
|
||||
margin: '0'
|
||||
}}>
|
||||
<li>Open Chrome DevTools (F12)</li>
|
||||
<li>Go to the Performance tab</li>
|
||||
<li>Click the record button and reload your page</li>
|
||||
<li>Stop recording and click "Save profile"</li>
|
||||
<li>Upload the saved .json file here</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
128
src/components/TraceViewer.tsx
Normal file
128
src/components/TraceViewer.tsx
Normal file
@ -0,0 +1,128 @@
|
||||
import { useDatabaseTraceData } from '../hooks/useDatabaseTraceData'
|
||||
import TraceStats from './TraceStats'
|
||||
|
||||
interface TraceViewerProps {
|
||||
traceId: string | null
|
||||
}
|
||||
|
||||
export default function TraceViewer({ traceId }: TraceViewerProps) {
|
||||
const { traceData, loading, error, stats, reload } = useDatabaseTraceData(traceId)
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '400px',
|
||||
fontSize: '18px',
|
||||
color: '#6c757d',
|
||||
padding: '40px'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '50px',
|
||||
height: '50px',
|
||||
border: '4px solid #f3f3f3',
|
||||
borderTop: '4px solid #007bff',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
marginBottom: '20px'
|
||||
}} />
|
||||
<div>Loading trace data...</div>
|
||||
<div style={{ fontSize: '14px', marginTop: '10px', textAlign: 'center' }}>
|
||||
This may take a moment for large trace files (90.9MB)
|
||||
</div>
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div style={{
|
||||
padding: '20px',
|
||||
maxWidth: '600px',
|
||||
margin: '0 auto',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
<div style={{
|
||||
background: '#f8d7da',
|
||||
color: '#721c24',
|
||||
padding: '15px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #f5c6cb',
|
||||
marginBottom: '15px'
|
||||
}}>
|
||||
<h3 style={{ margin: '0 0 10px 0' }}>Error Loading Trace Data</h3>
|
||||
<p style={{ margin: '0' }}>{error}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={reload}
|
||||
style={{
|
||||
background: '#007bff',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '10px 20px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!traceData || !stats) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
minHeight: '200px',
|
||||
fontSize: '18px',
|
||||
color: '#6c757d'
|
||||
}}>
|
||||
No trace data available
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{
|
||||
padding: '10px 20px',
|
||||
background: '#e9ecef',
|
||||
borderBottom: '1px solid #dee2e6',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<h1 style={{ margin: '0', color: '#495057' }}>Performance Trace Viewer</h1>
|
||||
<button
|
||||
onClick={reload}
|
||||
style={{
|
||||
background: '#28a745',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 16px',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '12px'
|
||||
}}
|
||||
>
|
||||
Reload Data
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<TraceStats stats={stats} />
|
||||
</div>
|
||||
)
|
||||
}
|
79
src/hooks/useDatabaseTraceData.ts
Normal file
79
src/hooks/useDatabaseTraceData.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import type { TraceFile } from '../../types/trace'
|
||||
import { traceDatabase } from '../utils/traceDatabase'
|
||||
import { getTraceStats } from '../utils/traceLoader'
|
||||
|
||||
interface UseDatabaseTraceDataResult {
|
||||
traceData: TraceFile | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
stats: ReturnType<typeof getTraceStats> | null
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* React hook for loading and managing trace data from IndexedDB
|
||||
* @param traceId - The ID of the trace to load, or null to load none
|
||||
* @returns Object containing trace data, loading state, error, and statistics
|
||||
*/
|
||||
export function useDatabaseTraceData(traceId: string | null): UseDatabaseTraceDataResult {
|
||||
const [traceData, setTraceData] = useState<TraceFile | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [stats, setStats] = useState<ReturnType<typeof getTraceStats> | null>(null)
|
||||
|
||||
const loadData = async () => {
|
||||
if (!traceId) {
|
||||
setTraceData(null)
|
||||
setStats(null)
|
||||
setError(null)
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
// Initialize database if needed
|
||||
await traceDatabase.init()
|
||||
|
||||
// Load trace from database
|
||||
const traceRecord = await traceDatabase.getTrace(traceId)
|
||||
|
||||
if (!traceRecord) {
|
||||
throw new Error('Trace not found in database')
|
||||
}
|
||||
|
||||
setTraceData(traceRecord.traceData)
|
||||
|
||||
// Calculate statistics
|
||||
const traceStats = getTraceStats(traceRecord.traceData)
|
||||
setStats(traceStats)
|
||||
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'
|
||||
setError(errorMessage)
|
||||
setTraceData(null)
|
||||
setStats(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const reload = () => {
|
||||
loadData()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
}, [traceId])
|
||||
|
||||
return {
|
||||
traceData,
|
||||
loading,
|
||||
error,
|
||||
stats,
|
||||
reload
|
||||
}
|
||||
}
|
60
src/hooks/useTraceData.ts
Normal file
60
src/hooks/useTraceData.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import type { TraceFile } from '../../types/trace'
|
||||
import { loadTraceFile, getTraceStats } from '../utils/traceLoader'
|
||||
|
||||
interface UseTraceDataResult {
|
||||
traceData: TraceFile | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
stats: ReturnType<typeof getTraceStats> | null
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* React hook for loading and managing trace data
|
||||
* @returns Object containing trace data, loading state, error, and statistics
|
||||
*/
|
||||
export function useTraceData(): UseTraceDataResult {
|
||||
const [traceData, setTraceData] = useState<TraceFile | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [stats, setStats] = useState<ReturnType<typeof getTraceStats> | null>(null)
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
const data = await loadTraceFile()
|
||||
setTraceData(data)
|
||||
|
||||
// Calculate statistics
|
||||
const traceStats = getTraceStats(data)
|
||||
setStats(traceStats)
|
||||
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'
|
||||
setError(errorMessage)
|
||||
setTraceData(null)
|
||||
setStats(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const reload = () => {
|
||||
loadData()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
}, [])
|
||||
|
||||
return {
|
||||
traceData,
|
||||
loading,
|
||||
error,
|
||||
stats,
|
||||
reload
|
||||
}
|
||||
}
|
1
src/index.css
Normal file
1
src/index.css
Normal file
@ -0,0 +1 @@
|
||||
|
10
src/main.tsx
Normal file
10
src/main.tsx
Normal file
@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
159
src/utils/traceDatabase.ts
Normal file
159
src/utils/traceDatabase.ts
Normal file
@ -0,0 +1,159 @@
|
||||
import type { TraceFile } from '../../types/trace'
|
||||
|
||||
export interface TraceRecord {
|
||||
id: string
|
||||
name: string
|
||||
uploadedAt: Date
|
||||
fileSize: number
|
||||
eventCount: number
|
||||
duration: number
|
||||
traceData: TraceFile
|
||||
}
|
||||
|
||||
const DB_NAME = 'PerfVizTraces'
|
||||
const DB_VERSION = 1
|
||||
const STORE_NAME = 'traces'
|
||||
|
||||
class TraceDatabase {
|
||||
private db: IDBDatabase | null = null
|
||||
|
||||
async init(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION)
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => {
|
||||
this.db = request.result
|
||||
resolve()
|
||||
}
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result
|
||||
|
||||
// Create traces object store
|
||||
const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' })
|
||||
store.createIndex('name', 'name', { unique: false })
|
||||
store.createIndex('uploadedAt', 'uploadedAt', { unique: false })
|
||||
store.createIndex('fileSize', 'fileSize', { unique: false })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async addTrace(traceData: TraceFile, filename: string, fileSize: number): Promise<string> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
const id = `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
||||
|
||||
// Calculate basic stats
|
||||
const eventCount = traceData.traceEvents.length
|
||||
let minTs = Infinity
|
||||
let maxTs = -Infinity
|
||||
|
||||
for (const event of traceData.traceEvents) {
|
||||
if (event.ts > 0) {
|
||||
minTs = Math.min(minTs, event.ts)
|
||||
maxTs = Math.max(maxTs, event.ts)
|
||||
}
|
||||
}
|
||||
|
||||
const duration = maxTs - minTs
|
||||
|
||||
const record: TraceRecord = {
|
||||
id,
|
||||
name: filename,
|
||||
uploadedAt: new Date(),
|
||||
fileSize,
|
||||
eventCount,
|
||||
duration,
|
||||
traceData
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readwrite')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const request = store.add(record)
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => resolve(id)
|
||||
})
|
||||
}
|
||||
|
||||
async getAllTraces(): Promise<TraceRecord[]> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readonly')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const request = store.getAll()
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => resolve(request.result)
|
||||
})
|
||||
}
|
||||
|
||||
async getTrace(id: string): Promise<TraceRecord | null> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readonly')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const request = store.get(id)
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => resolve(request.result || null)
|
||||
})
|
||||
}
|
||||
|
||||
async deleteTrace(id: string): Promise<void> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readwrite')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const request = store.delete(id)
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => resolve()
|
||||
})
|
||||
}
|
||||
|
||||
async updateTraceName(id: string, newName: string): Promise<void> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readwrite')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const getRequest = store.get(id)
|
||||
|
||||
getRequest.onsuccess = () => {
|
||||
const record = getRequest.result
|
||||
if (record) {
|
||||
record.name = newName
|
||||
const updateRequest = store.put(record)
|
||||
updateRequest.onsuccess = () => resolve()
|
||||
updateRequest.onerror = () => reject(updateRequest.error)
|
||||
} else {
|
||||
reject(new Error('Trace not found'))
|
||||
}
|
||||
}
|
||||
|
||||
getRequest.onerror = () => reject(getRequest.error)
|
||||
})
|
||||
}
|
||||
|
||||
async clearAllTraces(): Promise<void> {
|
||||
if (!this.db) throw new Error('Database not initialized')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.db!.transaction([STORE_NAME], 'readwrite')
|
||||
const store = transaction.objectStore(STORE_NAME)
|
||||
const request = store.clear()
|
||||
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onsuccess = () => resolve()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
export const traceDatabase = new TraceDatabase()
|
136
src/utils/traceLoader.ts
Normal file
136
src/utils/traceLoader.ts
Normal file
@ -0,0 +1,136 @@
|
||||
import type { TraceFile } from '../../types/trace'
|
||||
|
||||
/**
|
||||
* Loads and parses the trace.json file from the public directory with streaming support
|
||||
* @returns Promise that resolves to the parsed trace data
|
||||
*/
|
||||
export async function loadTraceFile(): Promise<TraceFile> {
|
||||
try {
|
||||
const response = await fetch('/trace.json')
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load trace.json: ${response.status} ${response.statusText}`)
|
||||
}
|
||||
|
||||
// Get the response as text first to avoid JSON.parse call stack issues
|
||||
const textData = await response.text()
|
||||
|
||||
// Parse JSON with error handling for large files
|
||||
let traceData: TraceFile
|
||||
try {
|
||||
// Use a timeout to prevent blocking the main thread too long
|
||||
traceData = await parseJSONSafely(textData)
|
||||
} catch (parseError) {
|
||||
throw new Error(`Failed to parse trace JSON: ${parseError}`)
|
||||
}
|
||||
|
||||
// Basic validation to ensure the structure matches our expected format
|
||||
if (!traceData.metadata || !Array.isArray(traceData.traceEvents)) {
|
||||
throw new Error('Invalid trace file format: missing metadata or traceEvents array')
|
||||
}
|
||||
|
||||
return traceData
|
||||
} catch (error) {
|
||||
console.error('Error loading trace file:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely parse JSON with chunked processing to avoid call stack issues
|
||||
*/
|
||||
async function parseJSONSafely(jsonString: string): Promise<TraceFile> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Use setTimeout to prevent blocking the main thread
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString)
|
||||
resolve(parsed)
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads trace file with error handling and loading state management
|
||||
* Useful for React components that need loading states
|
||||
*/
|
||||
export async function loadTraceFileWithStatus(): Promise<{
|
||||
data: TraceFile | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
}> {
|
||||
try {
|
||||
const data = await loadTraceFile()
|
||||
return {
|
||||
data,
|
||||
loading: false,
|
||||
error: null
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
data: null,
|
||||
loading: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error occurred'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function to get basic trace statistics with optimized processing for large datasets
|
||||
* @param traceData - The loaded trace data
|
||||
* @returns Object containing basic statistics about the trace
|
||||
*/
|
||||
export function getTraceStats(traceData: TraceFile) {
|
||||
const { traceEvents, metadata } = traceData
|
||||
|
||||
// Initialize counters
|
||||
const eventsByPhase: Record<string, number> = {}
|
||||
const processes = new Set<number>()
|
||||
const threads = new Set<string>()
|
||||
let minTimestamp = Infinity
|
||||
let maxTimestamp = -Infinity
|
||||
|
||||
// Single pass through events to calculate all stats efficiently
|
||||
for (const event of traceEvents) {
|
||||
// Count phase types
|
||||
eventsByPhase[event.ph] = (eventsByPhase[event.ph] || 0) + 1
|
||||
|
||||
// Track processes and threads
|
||||
processes.add(event.pid)
|
||||
threads.add(`${event.pid}:${event.tid}`)
|
||||
|
||||
// Track time range (only for events with valid timestamps)
|
||||
if (event.ts > 0) {
|
||||
minTimestamp = Math.min(minTimestamp, event.ts)
|
||||
maxTimestamp = Math.max(maxTimestamp, event.ts)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle case where no valid timestamps were found
|
||||
if (minTimestamp === Infinity) {
|
||||
minTimestamp = 0
|
||||
maxTimestamp = 0
|
||||
}
|
||||
|
||||
const duration = maxTimestamp - minTimestamp
|
||||
|
||||
return {
|
||||
totalEvents: traceEvents.length,
|
||||
eventsByPhase,
|
||||
timeRange: {
|
||||
start: minTimestamp,
|
||||
end: maxTimestamp,
|
||||
duration: duration
|
||||
},
|
||||
processCount: processes.size,
|
||||
threadCount: threads.size,
|
||||
metadata: {
|
||||
source: metadata.source,
|
||||
startTime: metadata.startTime,
|
||||
hardwareConcurrency: metadata.hardwareConcurrency
|
||||
}
|
||||
}
|
||||
}
|
1
src/vite-env.d.ts
vendored
Normal file
1
src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
27
tsconfig.app.json
Normal file
27
tsconfig.app.json
Normal file
@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
7
tsconfig.json
Normal file
7
tsconfig.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
25
tsconfig.node.json
Normal file
25
tsconfig.node.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
161
types/trace.ts
Normal file
161
types/trace.ts
Normal file
@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Chrome DevTools Performance Trace Format
|
||||
* Based on the Trace Event Format specification
|
||||
*/
|
||||
|
||||
// Main trace file structure
|
||||
export interface TraceFile {
|
||||
metadata: TraceMetadata
|
||||
traceEvents: TraceEvent[]
|
||||
}
|
||||
|
||||
// Metadata section
|
||||
export interface TraceMetadata {
|
||||
source: string
|
||||
startTime: string
|
||||
hardwareConcurrency: number
|
||||
dataOrigin: string
|
||||
modifications: TraceModifications
|
||||
}
|
||||
|
||||
export interface TraceModifications {
|
||||
entriesModifications: {
|
||||
hiddenEntries: unknown[]
|
||||
expandableEntries: unknown[]
|
||||
}
|
||||
initialBreadcrumb: {
|
||||
window: {
|
||||
min: number
|
||||
max: number
|
||||
range: number
|
||||
}
|
||||
child: null | unknown
|
||||
}
|
||||
annotations: {
|
||||
entryLabels: unknown[]
|
||||
labelledTimeRanges: unknown[]
|
||||
linksBetweenEntries: unknown[]
|
||||
}
|
||||
}
|
||||
|
||||
// Base trace event structure
|
||||
export interface BaseTraceEvent {
|
||||
/** Event arguments - varies by event type */
|
||||
args: Record<string, unknown>
|
||||
/** Category */
|
||||
cat: string
|
||||
/** Event name */
|
||||
name: string
|
||||
/** Phase type */
|
||||
ph: TraceEventPhase
|
||||
/** Process ID */
|
||||
pid: number
|
||||
/** Thread ID */
|
||||
tid: number
|
||||
/** Timestamp in microseconds */
|
||||
ts: number
|
||||
/** Thread timestamp in microseconds (optional) */
|
||||
tts?: number
|
||||
}
|
||||
|
||||
// Specific event types
|
||||
export interface MetadataEvent extends BaseTraceEvent {
|
||||
ph: 'M'
|
||||
args: {
|
||||
name?: string
|
||||
uptime?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export interface DurationEvent extends BaseTraceEvent {
|
||||
ph: 'X'
|
||||
/** Duration in microseconds */
|
||||
dur: number
|
||||
/** Thread duration in microseconds (optional) */
|
||||
tdur?: number
|
||||
}
|
||||
|
||||
export interface InstantEvent extends BaseTraceEvent {
|
||||
ph: 'I'
|
||||
/** Scope (optional) */
|
||||
s?: 't' | 'p' | 'g'
|
||||
/** Layer tree ID (optional) */
|
||||
layerTreeId?: number
|
||||
/** Layer ID (optional) */
|
||||
layerId?: number
|
||||
}
|
||||
|
||||
export interface BeginEvent extends BaseTraceEvent {
|
||||
ph: 'B'
|
||||
}
|
||||
|
||||
export interface EndEvent extends BaseTraceEvent {
|
||||
ph: 'E'
|
||||
}
|
||||
|
||||
// Union type for all trace events
|
||||
export type TraceEvent = MetadataEvent | DurationEvent | InstantEvent | BeginEvent | EndEvent
|
||||
|
||||
// Phase type enumeration
|
||||
export type TraceEventPhase =
|
||||
| 'M' // Metadata
|
||||
| 'X' // Complete (duration)
|
||||
| 'I' // Instant
|
||||
| 'B' // Begin
|
||||
| 'E' // End
|
||||
| 'D' // Deprecated
|
||||
| 'b' // Nestable start
|
||||
| 'e' // Nestable end
|
||||
| 'n' // Nestable instant
|
||||
| 'S' // Async start
|
||||
| 'T' // Async instant
|
||||
| 'F' // Async end
|
||||
| 'P' // Sample
|
||||
| 'C' // Counter
|
||||
| 'R' // Mark
|
||||
|
||||
// Common argument types found in trace events
|
||||
export interface TracingStartedArgs {
|
||||
data: {
|
||||
frameTreeNodeId: number
|
||||
frames: Array<{
|
||||
frame: string
|
||||
isInPrimaryMainFrame: boolean
|
||||
isOutermostMainFrame: boolean
|
||||
name: string
|
||||
processId: number
|
||||
url: string
|
||||
}>
|
||||
persistentIds: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export interface UpdateLayerArgs {
|
||||
layerId: number
|
||||
layerTreeId: number
|
||||
}
|
||||
|
||||
export interface NeedsBeginFrameChangedArgs {
|
||||
data: {
|
||||
needsBeginFrame: number
|
||||
}
|
||||
layerTreeId: number
|
||||
}
|
||||
|
||||
export interface RunTaskArgs {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
// Thread and process name arguments
|
||||
export interface ThreadNameArgs {
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ProcessNameArgs {
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ProcessUptimeArgs {
|
||||
uptime: string
|
||||
}
|
7
vite.config.ts
Normal file
7
vite.config.ts
Normal file
@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
})
|
Loading…
Reference in New Issue
Block a user