cs-element
Version:
Advanced reactive data management library with state machines, blueprints, persistence, compression, networking, and multithreading support
772 lines (635 loc) • 21.2 kB
Markdown
Система визуализации CSElement предоставляет мощные инструменты для отображения структуры элементов в различных форматах с поддержкой интерактивности и настраиваемого стиля.
- **ASCII Engine** - текстовая визуализация для консоли
- **SVG Engine** - масштабируемая векторная графика
- **HTML Engine** - интерактивные веб-визуализации
- **Tree Layout** - древовидная структура
- **Circular Layout** - круговая компоновка
- **Force Layout** - физическое моделирование
- **Hierarchical Layout** - иерархическая структура
- Масштабирование и панорамирование
- Выделение и фокус на элементах
- Анимации и переходы
- Пользовательские события
```typescript
import { VisualizationManager, VisualizationFormat } from 'cs-element';
// Создание менеджера визуализации
const visualizer = new VisualizationManager();
// Создание элемента для визуализации
const root = CSElement.create('root');
const child1 = root.createChild('child1');
const child2 = root.createChild('child2');
child1.createChild('grandchild1');
child1.createChild('grandchild2');
// ASCII визуализация
const asciiResult = await visualizer.visualize(root, {
format: VisualizationFormat.ASCII,
showIds: true,
maxDepth: 3
});
console.log(asciiResult.content);
// root [root]
// ├── child1 [child1]
// │ ├── grandchild1 [grandchild1]
// │ └── grandchild2 [grandchild2]
// └── child2 [child2]
```
```typescript
// SVG визуализация с настройками стиля
const svgResult = await visualizer.visualize(root, {
format: VisualizationFormat.SVG,
layout: 'tree',
width: 800,
height: 600,
nodeStyle: {
backgroundColor: '#3498db',
textColor: '#ffffff',
borderRadius: 8,
padding: 10
},
edgeStyle: {
color: '#2c3e50',
thickness: 2,
style: 'solid'
}
});
// Сохранение в файл или отображение в браузере
document.body.innerHTML = svgResult.content;
```
```typescript
// Интерактивная HTML визуализация
const htmlResult = await visualizer.visualize(root, {
format: VisualizationFormat.HTML,
layout: 'force',
interactive: true,
animations: true,
showData: true,
width: 1200,
height: 800,
theme: 'dark'
});
// Встраивание в веб-страницу
const container = document.getElementById('visualization');
container.innerHTML = htmlResult.content;
```
```typescript
// Детальная настройка ASCII визуализации
const asciiOptions = {
format: VisualizationFormat.ASCII,
// Отображение информации
showIds: true,
showIndices: true,
showTypes: true,
showData: false,
// Ограничения
maxDepth: 5,
maxWidth: 120,
// Символы для рисования
symbols: {
branch: '├──',
lastBranch: '└──',
vertical: '│',
horizontal: '──',
space: ' '
},
// Цвета (если поддерживаются терминалом)
colors: {
node: '\x1b[36m', // cyan
edge: '\x1b[90m', // gray
data: '\x1b[33m', // yellow
reset: '\x1b[0m' // reset
}
};
const result = await visualizer.visualize(root, asciiOptions);
console.log(result.content);
```
```typescript
// Продвинутая SVG визуализация
const svgOptions = {
format: VisualizationFormat.SVG,
layout: 'hierarchical',
// Размеры
width: 1000,
height: 700,
padding: 50,
// Стиль узлов
nodeStyle: {
backgroundColor: '#ffffff',
borderColor: '#333333',
borderWidth: 2,
borderRadius: 12,
padding: 15,
fontSize: 14,
fontFamily: 'Arial, sans-serif',
textColor: '#333333',
shadowColor: 'rgba(0,0,0,0.1)',
shadowBlur: 4
},
// Стиль связей
edgeStyle: {
color: '#666666',
thickness: 1.5,
style: 'solid', // 'solid', 'dashed', 'dotted'
arrowSize: 8,
curvature: 0.3
},
// Компоновка
layoutOptions: {
nodeSpacing: 80,
levelSpacing: 120,
alignment: 'center'
}
};
const svgResult = await visualizer.visualize(root, svgOptions);
// Добавление интерактивности к SVG
const svgElement = document.createElement('div');
svgElement.innerHTML = svgResult.content;
// Обработка кликов по узлам
svgElement.addEventListener('click', (event) => {
const nodeId = event.target.getAttribute('data-node-id');
if (nodeId) {
console.log(`Clicked on node: ${nodeId}`);
// Дополнительная логика
}
});
```
```typescript
// Полнофункциональная HTML визуализация
const htmlOptions = {
format: VisualizationFormat.HTML,
layout: 'force',
// Интерактивность
interactive: true,
animations: true,
zoomable: true,
pannable: true,
// Данные
showData: true,
showMetadata: true,
dataFormat: 'json', // 'json', 'yaml', 'table'
// Размеры и стиль
width: 1400,
height: 900,
theme: 'light', // 'light', 'dark', 'custom'
// Настройки force layout
forceOptions: {
linkDistance: 100,
linkStrength: 0.8,
charge: -300,
gravity: 0.1,
friction: 0.9
},
// События
onNodeClick: (node) => {
console.log('Node clicked:', node);
},
onNodeHover: (node) => {
console.log('Node hovered:', node);
},
onEdgeClick: (edge) => {
console.log('Edge clicked:', edge);
}
};
const htmlResult = await visualizer.visualize(root, htmlOptions);
// Встраивание с дополнительными возможностями
const container = document.getElementById('visualization-container');
container.innerHTML = htmlResult.content;
// Получение API визуализации
const vizAPI = htmlResult.api;
// Программное управление
vizAPI.focusNode('child1');
vizAPI.highlightPath(['root', 'child1', 'grandchild1']);
vizAPI.setFilter((node) => node.type === 'important');
```
```typescript
// Настройка менеджера визуализации
const visualizer = new VisualizationManager({
// Кэширование результатов
enableCaching: true,
cacheSize: 100,
// Производительность
maxNodes: 1000,
maxDepth: 10,
// Параллельная обработка
useWorkers: true,
workerCount: 4,
// Настройки по умолчанию
defaultFormat: VisualizationFormat.HTML,
defaultTheme: 'light',
// Плагины
plugins: ['zoom', 'pan', 'export', 'search']
});
```
```typescript
// Создание пользовательской темы
const customTheme = {
name: 'corporate',
colors: {
primary: '#0066cc',
secondary: '#ff6600',
background: '#f8f9fa',
text: '#333333',
border: '#dee2e6',
accent: '#28a745'
},
fonts: {
primary: 'Roboto, sans-serif',
secondary: 'Roboto Mono, monospace',
sizes: {
small: 12,
medium: 14,
large: 16,
xlarge: 20
}
},
spacing: {
small: 8,
medium: 16,
large: 24,
xlarge: 32
},
animations: {
duration: 300,
easing: 'ease-in-out'
}
};
// Регистрация темы
visualizer.registerTheme(customTheme);
// Использование темы
const result = await visualizer.visualize(root, {
format: VisualizationFormat.HTML,
theme: 'corporate'
});
```
```typescript
// Элемент с данными
const dataElement = CSElement.create('user', {
name: 'John Doe',
email: 'john@example.com',
age: 30,
permissions: ['read', 'write']
});
// Визуализация с отображением данных
const dataViz = await visualizer.visualize(dataElement, {
format: VisualizationFormat.HTML,
showData: true,
dataStyle: {
format: 'table',
showTypes: true,
expandable: true,
maxDepth: 3
}
});
```
```typescript
// Элемент с состоянием
const statefulElement = CSElement.create('workflow');
statefulElement.addStateMachine({
initial: 'draft',
states: {
draft: { on: { submit: 'review' } },
review: { on: { approve: 'approved', reject: 'draft' } },
approved: { on: { archive: 'archived' } },
archived: {}
}
});
// Визуализация состояний
const stateViz = await visualizer.visualize(statefulElement, {
format: VisualizationFormat.SVG,
visualizationType: 'state-machine',
stateStyle: {
current: { backgroundColor: '#28a745', textColor: '#ffffff' },
possible: { backgroundColor: '#ffc107', textColor: '#000000' },
unreachable: { backgroundColor: '#6c757d', textColor: '#ffffff' }
}
});
```
```typescript
// Элемент с метриками
const elementWithMetrics = CSElement.create('api-endpoint');
elementWithMetrics.setMetrics({
requests: 1250,
errors: 23,
avgResponseTime: 150,
uptime: 99.8
});
// Визуализация метрик
const metricsViz = await visualizer.visualize(elementWithMetrics, {
format: VisualizationFormat.HTML,
visualizationType: 'metrics',
metricsStyle: {
showCharts: true,
chartType: 'bar', // 'bar', 'line', 'pie', 'gauge'
colorScheme: 'green-red',
animations: true
}
});
```
```typescript
// Создание пользовательского рендерера
class CustomNodeRenderer {
render(node, options) {
return {
element: this.createElement(node, options),
width: this.calculateWidth(node),
height: this.calculateHeight(node)
};
}
private createElement(node, options) {
const element = document.createElement('div');
element.className = 'custom-node';
element.setAttribute('data-node-id', node.id);
// Пользовательская логика рендеринга
element.innerHTML = `
<div class="node-header">${node.name}</div>
<div class="node-content">${this.renderContent(node)}</div>
<div class="node-footer">${this.renderFooter(node)}</div>
`;
return element;
}
private renderContent(node) {
// Пользовательская логика для содержимого
return JSON.stringify(node.data, null, 2);
}
private renderFooter(node) {
return `ID: ${node.id} | Type: ${node.type}`;
}
}
// Регистрация пользовательского рендерера
visualizer.registerRenderer('custom', new CustomNodeRenderer());
// Использование
const customViz = await visualizer.visualize(root, {
format: VisualizationFormat.HTML,
renderer: 'custom'
});
```
```typescript
// Создание плагина экспорта
class ExportPlugin {
constructor(visualizer) {
this.visualizer = visualizer;
}
exportToPNG(element, options = {}) {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Логика экспорта в PNG
this.renderToCanvas(element, canvas, ctx, options)
.then(() => {
canvas.toBlob(resolve, 'image/png');
});
});
}
exportToPDF(element, options = {}) {
// Логика экспорта в PDF
return this.generatePDF(element, options);
}
exportToJSON(element, options = {}) {
return {
structure: this.serializeStructure(element),
metadata: this.extractMetadata(element),
timestamp: new Date().toISOString()
};
}
}
// Регистрация плагина
const exportPlugin = new ExportPlugin(visualizer);
visualizer.registerPlugin('export', exportPlugin);
// Использование плагина
const pngBlob = await visualizer.plugins.export.exportToPNG(root);
const jsonData = visualizer.plugins.export.exportToJSON(root);
```
```typescript
import React, { useEffect, useRef, useState } from 'react';
function VisualizationComponent({ element, options }) {
const containerRef = useRef(null);
const [visualizer] = useState(() => new VisualizationManager());
useEffect(() => {
if (element && containerRef.current) {
visualizeElement();
}
}, [element, options]);
const visualizeElement = async () => {
const result = await visualizer.visualize(element, {
format: VisualizationFormat.HTML,
interactive: true,
...options
});
containerRef.current.innerHTML = result.content;
// Настройка обработчиков событий
if (result.api) {
result.api.onNodeClick = (node) => {
console.log('Node clicked in React:', node);
};
}
};
return (
<div
ref={containerRef}
className="visualization-container"
style={{ width: '100%', height: '600px' }}
/>
);
}
// Использование
function App() {
const [element] = useState(() => {
const root = CSElement.create('app');
root.createChild('component1');
root.createChild('component2');
return root;
});
return (
<VisualizationComponent
element={element}
options={{
theme: 'light',
layout: 'tree',
animations: true
}}
/>
);
}
```
```typescript
// Серверная визуализация
import { VisualizationManager, VisualizationFormat } from 'cs-element';
import fs from 'fs';
class ServerVisualizationService {
private visualizer: VisualizationManager;
constructor() {
this.visualizer = new VisualizationManager({
useWorkers: false, // Отключаем workers на сервере
enableCaching: true
});
}
async generateReport(element, format = 'html') {
const options = {
format: format === 'svg' ? VisualizationFormat.SVG : VisualizationFormat.HTML,
width: 1200,
height: 800,
theme: 'light'
};
const result = await this.visualizer.visualize(element, options);
return {
content: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
};
}
async saveToFile(element, filename, format = 'html') {
const report = await this.generateReport(element, format);
const fullContent = format === 'html'
? this.wrapInHTML(report.content)
: report.content;
fs.writeFileSync(filename, fullContent, 'utf8');
return filename;
}
private wrapInHTML(content) {
return `
<!DOCTYPE html>
<html>
<head>
<title>CSElement Visualization</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
.visualization-container { width: 100%; height: 100vh; }
</style>
</head>
<body>
<div class="visualization-container">
${content}
</div>
</body>
</html>
`;
}
}
// Использование
const vizService = new ServerVisualizationService();
const element = CSElement.create('server-data');
// Генерация отчета
const report = await vizService.generateReport(element);
// Сохранение в файл
await vizService.saveToFile(element, 'report.html', 'html');
```
```typescript
// Настройки для больших структур данных
const optimizedOptions = {
format: VisualizationFormat.HTML,
// Ограничения производительности
maxNodes: 500,
maxDepth: 8,
// Виртуализация
enableVirtualization: true,
virtualChunkSize: 50,
// Ленивая загрузка
lazyLoading: true,
loadOnDemand: true,
// Упрощение рендеринга
simplifiedRendering: true,
reduceAnimations: true,
// Кэширование
enableCaching: true,
cacheStrategy: 'aggressive'
};
// Визуализация с прогрессом
const result = await visualizer.visualize(largeElement, {
...optimizedOptions,
onProgress: (progress) => {
console.log(`Visualization progress: ${progress.percentage}%`);
}
});
```
```typescript
// Включение мониторинга
visualizer.enablePerformanceMonitoring(true);
// Визуализация с метриками
const startTime = performance.now();
const result = await visualizer.visualize(element, options);
const endTime = performance.now();
// Получение метрик
const metrics = visualizer.getPerformanceMetrics();
console.log('Метрики визуализации:', {
renderTime: endTime - startTime,
nodeCount: metrics.nodeCount,
edgeCount: metrics.edgeCount,
memoryUsage: metrics.memoryUsage,
cacheHitRate: metrics.cacheHitRate
});
```
**Проблема:** Медленная визуализация больших структур
```typescript
// ❌ Неправильно - без ограничений
const result = await visualizer.visualize(hugeElement, {
format: VisualizationFormat.HTML,
showData: true // Показывает все данные
});
// ✅ Правильно - с оптимизацией
const result = await visualizer.visualize(hugeElement, {
format: VisualizationFormat.HTML,
maxNodes: 200,
maxDepth: 5,
simplifiedRendering: true,
showData: false
});
```
**Проблема:** Интерактивность не работает
```typescript
// ❌ Неправильно - неправильная инициализация
container.innerHTML = result.content;
// ✅ Правильно - правильная инициализация
container.innerHTML = result.content;
if (result.api) {
result.api.initialize();
result.api.bindEvents();
}
```
```typescript
// Включение режима отладки
const debugVisualizer = new VisualizationManager({
debug: true,
logLevel: 'verbose'
});
// Диагностическая информация
const diagnostics = await debugVisualizer.diagnose(element);
console.log('Диагностика визуализации:', {
nodeCount: diagnostics.nodeCount,
complexity: diagnostics.complexity,
recommendations: diagnostics.recommendations,
warnings: diagnostics.warnings
});
```
Система визуализации CSElement предоставляет мощные и гибкие инструменты для отображения сложных структур данных в различных форматах с полной поддержкой интерактивности и настройки.