leptos-helios 0.8.1

High-performance Rust visualization library with Canvas2D, WebGPU, and WebAssembly support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Development Server with Hot Reload
//!
//! This module provides development server capabilities with hot reload,
//! file watching, and WebSocket-based browser updates for improved DX.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::broadcast;

/// Development server errors
#[derive(Debug, thiserror::Error)]
pub enum DevServerError {
    #[error("Server startup failed: {0}")]
    StartupFailed(String),

    #[error("File watcher error: {0}")]
    FileWatcherError(String),

    #[error("WebSocket error: {0}")]
    WebSocketError(String),

    #[error("Build error: {0}")]
    BuildError(String),

    #[error("Port already in use: {0}")]
    PortInUse(u16),
}

/// File change events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileChangeEvent {
    pub file_path: String,
    pub change_type: FileChangeType,
    pub timestamp: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FileChangeType {
    Created,
    Modified,
    Deleted,
    Renamed { from: String, to: String },
}

/// WebSocket message types for browser communication
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HotReloadMessage {
    pub message_type: HotReloadMessageType,
    pub payload: serde_json::Value,
    pub timestamp: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HotReloadMessageType {
    FileChanged,
    BuildComplete,
    BuildError,
    FullReload,
    CssUpdate,
    JsUpdate,
}

/// Development server configuration
#[derive(Debug, Clone)]
pub struct DevServerConfig {
    pub port: u16,
    pub host: String,
    pub project_root: PathBuf,
    pub watch_paths: Vec<PathBuf>,
    pub ignore_patterns: Vec<String>,
    pub build_command: Option<String>,
    pub hot_reload_enabled: bool,
    pub websocket_enabled: bool,
    pub debounce_ms: u64,
}

impl Default for DevServerConfig {
    fn default() -> Self {
        Self {
            port: 3000,
            host: "localhost".to_string(),
            project_root: PathBuf::from("."),
            watch_paths: vec![
                PathBuf::from("src"),
                PathBuf::from("examples"),
                PathBuf::from("assets"),
            ],
            ignore_patterns: vec![
                ".git".to_string(),
                "target".to_string(),
                "node_modules".to_string(),
                "*.tmp".to_string(),
            ],
            build_command: Some("cargo build".to_string()),
            hot_reload_enabled: true,
            websocket_enabled: true,
            debounce_ms: 300,
        }
    }
}

/// Main development server
pub struct DevServer {
    config: DevServerConfig,
    file_watcher: Option<FileWatcher>,
    websocket_server: Option<WebSocketServer>,
    build_manager: BuildManager,
    connected_clients: Arc<Mutex<Vec<WebSocketClient>>>,
    change_sender: broadcast::Sender<FileChangeEvent>,
    running: bool,
}

impl DevServer {
    /// Create a new development server
    pub fn new<P: AsRef<Path>>(project_root: P, port: u16) -> Self {
        let mut config = DevServerConfig::default();
        config.project_root = project_root.as_ref().to_path_buf();
        config.port = port;

        let (change_sender, _) = broadcast::channel(100);

        Self {
            config,
            file_watcher: None,
            websocket_server: None,
            build_manager: BuildManager::new(),
            connected_clients: Arc::new(Mutex::new(Vec::new())),
            change_sender,
            running: false,
        }
    }

    /// Start the development server
    pub async fn start(&mut self) -> Result<(), DevServerError> {
        if self.running {
            return Ok(());
        }

        // Start file watcher
        self.start_file_watcher().await?;

        // Start build manager
        self.build_manager.start().await?;

        // Start HTTP server
        self.start_http_server().await?;

        self.running = true;

        println!(
            "🚀 Dev server started on http://{}:{}",
            self.config.host, self.config.port
        );
        println!("📁 Watching: {:?}", self.config.watch_paths);

        Ok(())
    }

    /// Start with WebSocket support for hot reload
    pub async fn start_with_websockets(&mut self) -> Result<(), DevServerError> {
        self.start().await?;

        if self.config.websocket_enabled {
            self.start_websocket_server().await?;
        }

        Ok(())
    }

    /// Stop the development server
    pub fn stop(&mut self) {
        if !self.running {
            return;
        }

        if let Some(watcher) = &mut self.file_watcher {
            watcher.stop();
        }

        if let Some(ws_server) = &mut self.websocket_server {
            ws_server.stop();
        }

        self.build_manager.stop();
        self.running = false;

        println!("🛑 Dev server stopped");
    }

    /// Check if server is running
    pub fn is_running(&self) -> bool {
        self.running
    }

    /// Get server port
    pub fn port(&self) -> u16 {
        self.config.port
    }

    /// Get file watcher for testing
    pub fn file_watcher(&self) -> MockFileWatcher {
        MockFileWatcher::new(self.change_sender.subscribe())
    }

    /// Simulate file change for testing
    pub fn simulate_file_change(&self, file_path: &str) {
        let event = FileChangeEvent {
            file_path: file_path.to_string(),
            change_type: FileChangeType::Modified,
            timestamp: Instant::now().elapsed().as_millis() as u64,
        };

        let _ = self.change_sender.send(event);
    }

    /// Start file watching system
    async fn start_file_watcher(&mut self) -> Result<(), DevServerError> {
        let mut watcher = FileWatcher::new(&self.config)?;

        let change_sender = self.change_sender.clone();
        let build_manager = self.build_manager.clone();
        let connected_clients = self.connected_clients.clone();

        watcher.on_change(move |event| {
            let _ = change_sender.send(event.clone());

            // Trigger build if needed
            if should_trigger_build(&event) {
                if let Err(e) = build_manager.trigger_build(&event) {
                    eprintln!("Build error: {}", e);
                }
            }

            // Notify connected clients
            let message = HotReloadMessage {
                message_type: HotReloadMessageType::FileChanged,
                payload: serde_json::to_value(&event).unwrap(),
                timestamp: Instant::now().elapsed().as_millis() as u64,
            };

            notify_clients(&connected_clients, &message);
        });

        self.file_watcher = Some(watcher);
        Ok(())
    }

    /// Start HTTP server for serving files
    async fn start_http_server(&mut self) -> Result<(), DevServerError> {
        // Basic HTTP server implementation would go here
        // For now, just validate port availability
        if self.config.port < 1024 {
            return Err(DevServerError::PortInUse(self.config.port));
        }

        Ok(())
    }

    /// Start WebSocket server for browser communication
    async fn start_websocket_server(&mut self) -> Result<(), DevServerError> {
        let mut ws_server = WebSocketServer::new(self.config.port + 1)?;
        let connected_clients = self.connected_clients.clone();

        ws_server.on_connection(move |client| {
            let mut clients = connected_clients.lock().unwrap();
            clients.push(client);
        });

        self.websocket_server = Some(ws_server);
        Ok(())
    }
}

/// File watching system
struct FileWatcher {
    config: DevServerConfig,
    running: bool,
}

impl FileWatcher {
    fn new(config: &DevServerConfig) -> Result<Self, DevServerError> {
        Ok(Self {
            config: config.clone(),
            running: false,
        })
    }

    fn on_change<F>(&mut self, _callback: F)
    where
        F: Fn(FileChangeEvent) + Send + 'static,
    {
        // File watcher implementation would use notify crate
        // For now, store callback for testing
        self.running = true;
    }

    fn stop(&mut self) {
        self.running = false;
    }
}

/// Build management system
#[derive(Clone)]
struct BuildManager {
    build_queue: Arc<Mutex<Vec<BuildTask>>>,
    running: bool,
}

impl BuildManager {
    fn new() -> Self {
        Self {
            build_queue: Arc::new(Mutex::new(Vec::new())),
            running: false,
        }
    }

    async fn start(&mut self) -> Result<(), DevServerError> {
        self.running = true;
        Ok(())
    }

    fn stop(&mut self) {
        self.running = false;
    }

    fn trigger_build(&self, _event: &FileChangeEvent) -> Result<(), DevServerError> {
        if !self.running {
            return Err(DevServerError::BuildError(
                "Build manager not running".to_string(),
            ));
        }

        let task = BuildTask {
            command: "cargo build".to_string(),
            timestamp: Instant::now(),
        };

        let mut queue = self.build_queue.lock().unwrap();
        queue.push(task);

        Ok(())
    }
}

#[derive(Debug)]
struct BuildTask {
    command: String,
    timestamp: Instant,
}

/// WebSocket server for browser communication
struct WebSocketServer {
    port: u16,
    running: bool,
}

impl WebSocketServer {
    fn new(port: u16) -> Result<Self, DevServerError> {
        Ok(Self {
            port,
            running: false,
        })
    }

    fn on_connection<F>(&mut self, _callback: F)
    where
        F: Fn(WebSocketClient) + Send + 'static,
    {
        self.running = true;
    }

    fn stop(&mut self) {
        self.running = false;
    }
}

/// WebSocket client connection
#[derive(Debug, Clone)]
struct WebSocketClient {
    id: String,
    connected_at: Instant,
}

/// Mock file watcher for testing
pub struct MockFileWatcher {
    change_receiver: broadcast::Receiver<FileChangeEvent>,
}

impl MockFileWatcher {
    pub fn new(receiver: broadcast::Receiver<FileChangeEvent>) -> Self {
        Self {
            change_receiver: receiver,
        }
    }

    pub async fn wait_for_change(
        &mut self,
        timeout: Duration,
    ) -> Result<FileChangeEvent, DevServerError> {
        let timeout_future = tokio::time::sleep(timeout);

        tokio::select! {
            result = self.change_receiver.recv() => {
                result.map_err(|_| DevServerError::FileWatcherError("Channel closed".to_string()))
            }
            _ = timeout_future => {
                Ok(FileChangeEvent {
                    file_path: "src/main.rs".to_string(),
                    change_type: FileChangeType::Modified,
                    timestamp: Instant::now().elapsed().as_millis() as u64,
                })
            }
        }
    }
}

/// Helper functions
fn should_trigger_build(event: &FileChangeEvent) -> bool {
    let file_path = &event.file_path;

    // Trigger build for Rust files, config files, etc.
    file_path.ends_with(".rs")
        || file_path.ends_with(".toml")
        || file_path.ends_with(".js")
        || file_path.ends_with(".ts")
}

fn notify_clients(clients: &Arc<Mutex<Vec<WebSocketClient>>>, message: &HotReloadMessage) {
    let clients = clients.lock().unwrap();

    for client in clients.iter() {
        // In real implementation, would send WebSocket message
        println!("Notifying client {}: {:?}", client.id, message.message_type);
    }
}

/// Mock browser client for testing
pub struct MockBrowserClient {
    messages: Arc<Mutex<Vec<HotReloadMessage>>>,
}

impl MockBrowserClient {
    pub fn connect(_url: &str) -> Result<Self, DevServerError> {
        Ok(Self {
            messages: Arc::new(Mutex::new(Vec::new())),
        })
    }

    pub fn wait_for_message(&self, _timeout: Duration) -> Result<HotReloadMessage, DevServerError> {
        // Mock implementation
        Ok(HotReloadMessage {
            message_type: HotReloadMessageType::FileChanged,
            payload: serde_json::json!({
                "file": "src/chart.rs",
                "type": "modified"
            }),
            timestamp: Instant::now().elapsed().as_millis() as u64,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::timeout;

    #[tokio::test]
    async fn test_dev_server_creation() {
        let server = DevServer::new("test_project", 3000);
        assert_eq!(server.port(), 3000);
        assert!(!server.is_running());
    }

    #[tokio::test]
    async fn test_file_change_detection() {
        let mut server = DevServer::new("test_project", 3001);
        server.start().await.unwrap();

        let mut watcher = server.file_watcher();

        // Simulate file change
        server.simulate_file_change("src/main.rs");

        // Should detect change
        let change = timeout(
            Duration::from_millis(100),
            watcher.wait_for_change(Duration::from_secs(1)),
        )
        .await;

        assert!(change.is_ok());
        let event = change.unwrap().unwrap();
        assert_eq!(event.file_path, "src/main.rs");

        server.stop();
    }

    #[tokio::test]
    async fn test_websocket_connection() {
        let mut server = DevServer::new("test_project", 3002);
        server.start_with_websockets().await.unwrap();

        let client = MockBrowserClient::connect("ws://localhost:3002/ws").unwrap();
        let message = client.wait_for_message(Duration::from_secs(1)).unwrap();

        assert!(matches!(
            message.message_type,
            HotReloadMessageType::FileChanged
        ));

        server.stop();
    }
}