leptos_helios/
lib.rs

1//! Helios Core - High-performance visualization engine
2//!
3//! This crate provides the core visualization engine for Helios, including:
4//! - **Canvas2D Rendering**: Universal browser support with TDD implementation
5//! - **WebGPU Acceleration**: High-performance GPU rendering (816+ MB/s throughput)
6//! - **WebAssembly Integration**: Rust-powered data processing and function export
7//! - **Data Processing Pipeline**: Polars integration with efficient data handling
8//! - **Chart Specification System**: Compile-time validation and type safety
9//! - **Performance Optimization**: Sub-millisecond rendering and adaptive quality
10//! - **Test-Driven Development**: Complete TDD methodology with 100% test coverage
11//!
12//! ## Demo Suite
13//!
14//! Experience Helios in action with our comprehensive demo suite:
15//!
16//! ```bash
17//! python3 demo-server.py
18//! # Open http://localhost:8080 in your browser
19//! ```
20//!
21//! ### Available Demos
22//! - **Canvas2D TDD Demo** (`/`) - Test-Driven Development methodology
23//! - **WebGPU Demo** (`/webgpu`) - GPU acceleration testing
24//! - **WebGPU Charts Demo** (`/webgpu-charts`) - Visual GPU-rendered charts
25//! - **WASM Example** (`/example`) - Rust-WebAssembly integration
26//!
27//! ## Performance Highlights
28//!
29//! - **Canvas2D**: 100K points in <3ms render time
30//! - **WebGPU**: 816+ MB/s throughput, 1M points in 77ms
31//! - **WASM**: <1ms function execution
32//! - **Interactive**: Sub-millisecond hover detection
33
34pub mod accessibility;
35pub mod advanced_analytics;
36pub mod advanced_charts;
37pub mod advanced_memory;
38// pub mod algorithm_registry;
39// pub mod animation_engine;
40// pub mod anomaly_detection;
41pub mod advanced_chart_types;
42pub mod canvas2d_renderer;
43pub mod canvas_surface;
44pub mod chart;
45pub mod chart_config;
46pub mod cross_browser;
47pub mod graph_features;
48pub mod interactivity;
49pub mod performance_advanced;
50pub mod performance_optimizations;
51pub mod smooth_animations;
52// pub mod custom_components;
53// pub mod data; // Temporarily disabled due to Polars compatibility issues
54pub mod data_pipeline;
55pub mod data_processing;
56pub mod data_sources;
57pub mod debugger;
58pub mod dev_server;
59pub mod dev_tools;
60pub mod export_system;
61// pub mod forecasting_engine;
62pub mod gpu_accelerator;
63pub mod headless_renderer;
64pub mod helios_chart;
65pub mod interactions;
66pub mod line_chart_renderer;
67pub mod ml_intelligence;
68pub mod plugin_system;
69pub mod production;
70pub mod profiler;
71pub mod renderer;
72pub mod rendering;
73// pub mod responsive_design;
74pub mod security;
75pub mod streaming;
76pub mod styling;
77// pub mod theme_engine;
78pub mod wasm_optimizer;
79pub mod webgpu_real;
80pub mod webgpu_renderer;
81
82// pub use data; // Temporarily disabled due to Polars compatibility issues
83pub use rendering as render;
84pub mod gpu;
85pub mod intelligence;
86pub mod nl_processor;
87// pub mod realtime; // Temporarily disabled due to async issues
88// pub mod responsive; // Temporarily disabled due to async issues
89// pub mod performance_optimization; // Temporarily disabled due to async issues
90// pub mod offline_support; // Temporarily disabled due to async issues
91pub mod utils;
92
93// Core chart types
94pub use chart::{
95    BarWidth, ChartConfig, ChartSpec, ChartSpecBuilder, DataReference, Encoding, Interpolation,
96    MarkType,
97};
98pub use chart_config::{
99    ChartRenderResult, RenderResult as ChartConfigRenderResult, WebGpuRenderResult,
100};
101pub use data_pipeline::{DataPipeline, GpuBuffers, PipelineError, PipelineResult};
102pub use helios_chart::{create_helios_chart, HeliosChart, HeliosChartProps};
103pub use polars::prelude::DataFrame;
104pub use renderer::{
105    Canvas2DRenderer, RenderStatus, Renderer as ChartRenderer, RendererBackend, WebGl2Renderer,
106    WebGpuRenderer,
107};
108
109// Core modules with specific exports to avoid conflicts
110pub use accessibility::{
111    AltTextGenerator, AccessibilityError, AccessibilityConfig, AlternativeFormats,
112    KeyboardManager, ScreenReaderManager, WCAGChecker, WCAGLevel, ComplianceReport,
113    PerformanceConfig as AccessibilityPerformanceConfig, PerformanceMonitor as AccessibilityPerformanceMonitor,
114};
115pub use advanced_analytics::{
116    AnalyticsError, MLModel, MLPipeline, StatisticalAnalyzer, TimeSeriesAnalysis,
117    CorrelationAnalysis, DataPoint, DataSeries, ModelInfo, ModelType,
118};
119// pub use algorithm_registry::*;
120// pub use animation_engine::*;
121// pub use anomaly_detection::*;
122// pub use custom_components::*;
123pub use advanced_chart_types::*;
124pub use interactivity::{
125    Viewport as InteractivityViewport, Tooltip, TooltipStyle as InteractivityTooltipStyle,
126    TooltipData as InteractivityTooltipData, BrushSelection, CrossFilter, FilterEvent,
127    DataPoint as InteractivityDataPoint, InteractiveChart,
128};
129
130pub use performance_optimizations::{
131    VirtualScroller, DataSampler, WebGLRenderer, WebGPURenderer, Buffer as PerformanceBuffer,
132    RenderBatch, MemoryPool, PerformanceMonitor as PerformanceOptimizationsMonitor,
133    PerformanceMetric as PerformanceOptimizationsMetric, PerformanceReport,
134};
135
136pub use graph_features::{
137    GraphNode, GraphEdge, CentralityMeasures, NetworkMetrics, VisualizationMetrics,
138    ForceDirectedLayout, GraphAlgorithms, GraphClusterer, ClusteringAlgorithm as GraphClusteringAlgorithm,
139    NetworkAnalyzer, GraphManipulator,
140};
141
142pub use data_sources::{
143    DataSourceManager, DataSourceFactory, DataSourceConfigBuilder, DataSource as DataSourceTrait,
144    Connection, Transaction, DataStream, PostgresAdapter, ClickHouseAdapter, ConnectionConfig,
145    Credentials, TableInfo, ColumnInfo, QueryResult, DataSourceStats,
146};
147pub use debugger::*;
148pub use dev_tools::{
149    DevToolsError, ProfileData, CodeTemplate, LiveReloadConfig, HeliosDev, DevToolsConfig,
150    PerformanceProfiler as DevToolsPerformanceProfiler, ProfileScope, CodeGenerator,
151    CodeLinter, LintRule, LintResult,
152};
153pub use export_system::*;
154pub use smooth_animations::{
155    EasingFunctions, TweenAnimation, EasingType, StateTransition, AnimationOrchestrator,
156    AnimationRenderer, AnimationBatch, Color as AnimationColor, Point2D as AnimationPoint2D,
157    Size as AnimationSize, PerformanceMetrics as AnimationPerformanceMetrics,
158};
159// pub use forecasting_engine::*;
160pub use ml_intelligence::{
161    TimeSeriesPoint, ForecastResult, ChartRecommendation, MLForecaster, ChartRecommendationEngine,
162    DataAnalysis as MLDataAnalysis, DataType as MLDataType, TrendType as MLTrendType,
163    DataAnalyzer as MLDataAnalyzer, MLPerformanceMonitor, MLPerformanceStats,
164};
165pub use performance_advanced::{
166    PerformanceOptimizer, PerformanceOptimizerStats, PerformanceBenchmark, BenchmarkSummary,
167    RuntimePoolStats, MemoryPoolStats,
168};
169pub use plugin_system::{
170    ChartPlugin, DataSourcePlugin, ExportPlugin, MLPlugin, PluginError, PluginManager,
171    PluginMetadata, RenderResult as PluginRenderResult, ThemePlugin, TransformPlugin,
172};
173// pub use responsive_design::*;
174// pub use security::*; // Temporarily disabled due to async issues
175// pub use streaming::*; // Temporarily disabled due to async issues
176pub use styling::*;
177// pub use theme_engine::*;
178
179// Other modules (no conflicts)
180pub use advanced_memory::*;
181pub use cross_browser::*;
182pub use dev_server::*;
183pub use gpu::*;
184pub use gpu_accelerator::{
185    GpuMemoryUsage, BufferPoolStats, PerformanceMetrics as GpuPerformanceMetrics,
186    GpuBuffer, OptimizedGpuBuffer, OptimizedGpuRenderer, Point2D as GpuPoint2D,
187    GpuAccelerationEngine,
188};
189pub use intelligence::{
190    ClusterAnalyzer, ClusteringAlgorithm as IntelligenceClusteringAlgorithm, ClusteringResults,
191    ClusterStats, ClusteringConfig as IntelligenceClusteringConfig, AnomalyDetector, AnomalyMethod,
192    DataStatistics, AnomalyPoint, AnomalyReason, AnomalyResults, TimeSeriesForecaster,
193    TrendAnalysis as IntelligenceTrendAnalysis, TrendType as IntelligenceTrendType,
194    TrendDirection as IntelligenceTrendDirection, SeasonalityAnalysis, TimeSeriesDecomposition,
195    MLPipeline as IntelligenceMLPipeline, ModelType as IntelligenceModelType, MLConfig, MLResults,
196    MLError,
197};
198pub use interactions::*;
199pub use nl_processor::*;
200pub use profiler::*;
201// pub use realtime::*; // Temporarily disabled due to async issues
202pub use render::*;
203// pub use responsive::*; // Temporarily disabled due to async issues
204// pub use performance_optimization::*; // Temporarily disabled due to async issues
205// pub use offline_support::*; // Temporarily disabled due to async issues
206pub use utils::*;
207
208/// Core error types for Helios
209#[derive(Debug, thiserror::Error)]
210pub enum HeliosError {
211    #[error("Data processing error: {0}")]
212    DataProcessing(#[from] data_processing::DataError),
213
214    #[error("Rendering error: {0}")]
215    Rendering(#[from] rendering::RenderError),
216
217    #[error("Validation error: {0}")]
218    Validation(#[from] chart::ValidationError),
219
220    #[error("ML error: {0}")]
221    MachineLearning(#[from] intelligence::MLError),
222
223    #[error("Chart rendering error: {0}")]
224    ChartRendering(#[from] chart_config::ChartRenderError),
225
226    #[error("Configuration error: {0}")]
227    Configuration(String),
228
229    #[error("Performance budget exceeded: {details}")]
230    PerformanceBudget { details: String },
231    // #[error("Real-time error: {0}")]
232    // Realtime(#[from] realtime::WebSocketError),
233
234    // #[error("Message protocol error: {0}")]
235    // MessageProtocol(#[from] realtime::MessageProtocolError),
236}
237
238impl HeliosError {
239    pub fn is_recoverable(&self) -> bool {
240        matches!(
241            self,
242            HeliosError::Configuration(_) | HeliosError::PerformanceBudget { .. } // | HeliosError::Realtime(_)
243        )
244    }
245
246    pub fn user_message(&self) -> String {
247        match self {
248            HeliosError::DataProcessing(e) => format!("Data processing failed: {}", e),
249            HeliosError::Rendering(e) => format!("Rendering failed: {}", e),
250            HeliosError::Validation(e) => format!("Invalid configuration: {}", e),
251            HeliosError::MachineLearning(e) => format!("ML processing failed: {}", e),
252            HeliosError::ChartRendering(e) => format!("Chart rendering failed: {}", e),
253            HeliosError::Configuration(msg) => format!("Configuration error: {}", msg),
254            HeliosError::PerformanceBudget { details } => {
255                format!("Performance limit exceeded: {}", details)
256            } // HeliosError::Realtime(e) => format!("Real-time connection failed: {}", e),
257              // HeliosError::MessageProtocol(e) => format!("Message protocol error: {}", e),
258        }
259    }
260
261    pub fn suggested_actions(&self) -> Vec<String> {
262        match self {
263            HeliosError::DataProcessing(_) => vec![
264                "Check data format and structure".to_string(),
265                "Verify data types match chart requirements".to_string(),
266                "Consider reducing data size".to_string(),
267            ],
268            HeliosError::Rendering(_) => vec![
269                "Check WebGPU/WebGL support".to_string(),
270                "Reduce chart complexity".to_string(),
271                "Enable performance mode".to_string(),
272            ],
273            HeliosError::Validation(_) => vec![
274                "Review chart specification".to_string(),
275                "Check required fields are provided".to_string(),
276                "Validate data types".to_string(),
277            ],
278            HeliosError::MachineLearning(_) => vec![
279                "Check ML model availability".to_string(),
280                "Verify input data format".to_string(),
281                "Consider reducing data size".to_string(),
282            ],
283            HeliosError::ChartRendering(_) => vec![
284                "Check rendering backend support".to_string(),
285                "Verify chart configuration".to_string(),
286                "Try different renderer backend".to_string(),
287            ],
288            HeliosError::Configuration(_) => vec![
289                "Review configuration parameters".to_string(),
290                "Check for typos in field names".to_string(),
291                "Verify parameter ranges".to_string(),
292            ],
293            HeliosError::PerformanceBudget { .. } => vec![
294                "Reduce data size".to_string(),
295                "Enable performance mode".to_string(),
296                "Use streaming for large datasets".to_string(),
297            ],
298            // HeliosError::Realtime(_) => vec![
299            //     "Check network connection".to_string(),
300            //     "Verify WebSocket server is running".to_string(),
301            //     "Try reconnecting".to_string(),
302            // ],
303            // HeliosError::MessageProtocol(_) => vec![
304            //     "Check message format".to_string(),
305            //     "Verify protocol version".to_string(),
306            //     "Check message size limits".to_string(),
307            // ],
308        }
309    }
310}
311
312/// Result type for Helios operations
313pub type Result<T> = std::result::Result<T, HeliosError>;
314
315/// Common type aliases
316pub type LazyFrame = polars::prelude::LazyFrame;
317pub type Color = [f32; 4]; // RGBA
318pub type Point2D = [f32; 2];
319pub type Point3D = [f32; 3];
320pub type Rect = [f32; 4]; // x, y, width, height
321pub type Transform2D = [[f32; 3]; 2]; // 2D affine transform matrix
322
323/// Initialize Helios for the current platform
324pub async fn init() -> Result<()> {
325    #[cfg(target_arch = "wasm32")]
326    {
327        console_error_panic_hook::set_once();
328    }
329
330    // Initialize WebGPU/WebGL context
331    let _renderer = ChartRenderer::auto_detect()?;
332
333    // Initialize data processing pipeline
334    // let _data_processor = DataProcessor::new()?;
335
336    // Initialize ML pipeline if available
337    #[cfg(feature = "ml")]
338    let _ml_pipeline = MLPipeline::new().await?;
339
340    Ok(())
341}
342
343/// Get the current Helios version
344pub fn version() -> &'static str {
345    env!("CARGO_PKG_VERSION")
346}
347
348/// Get build information
349pub fn build_info() -> BuildInfo {
350    BuildInfo {
351        version: version().to_string(),
352        features: get_enabled_features(),
353        target: std::env::consts::ARCH.to_string(),
354        os: std::env::consts::OS.to_string(),
355    }
356}
357
358#[derive(Debug, Clone)]
359pub struct BuildInfo {
360    pub version: String,
361    pub features: Vec<String>,
362    pub target: String,
363    pub os: String,
364}
365
366fn get_enabled_features() -> Vec<String> {
367    let features = vec![
368        #[cfg(feature = "webgpu")]
369        "webgpu".to_string(),
370        #[cfg(feature = "webgl2")]
371        "webgl2".to_string(),
372        #[cfg(feature = "canvas2d")]
373        "canvas2d".to_string(),
374        #[cfg(feature = "simd")]
375        "simd".to_string(),
376        #[cfg(feature = "debug")]
377        "debug".to_string(),
378        #[cfg(feature = "ml")]
379        "ml".to_string(),
380    ];
381
382    features
383}
384
385// Re-export WASM optimization components
386pub use wasm_optimizer::*;