template/
template.rs

1use web_ui::{WebUI, WebUIConfig, UIResponse};
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::sync::Arc;
4
5#[tokio::main]
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Create configuration for your web UI
8    let config = WebUIConfig::default()
9        .with_port(3030)  // Change this port if needed
10        .with_title("Your Web UI Component".to_string())  // Customize your title
11        .with_static_dir("./template/static".to_string());  // Point to your static files directory
12
13    // Create WebUI instance
14    let web_ui = WebUI::new(config);
15
16    // Example: Shared state (optional)
17    let counter = Arc::new(AtomicU32::new(0));
18
19    // Example 1: Simple button click handler
20    web_ui.bind_click("your-button-id", || {
21        println!("Button was clicked!");
22        // Add your custom logic here
23    }).await;
24
25    // Example 2: Event handler with response data
26    let counter_clone = counter.clone();
27    web_ui.bind_event("your-button-id", "click", move |event| {
28        let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
29        println!("Event received: {:?}", event);
30        
31        // Return a response to the client
32        Ok(UIResponse {
33            success: true,
34            message: Some(format!("Action completed successfully! Count: {}", count)),
35            data: Some(serde_json::json!({ 
36                "count": count,
37            })),
38            request_id: event.request_id,
39        }) 
40    }).await;
41
42    // Example 3: Input field handler
43    web_ui.bind_event("your-input-id", "change", |event| {
44        println!("Input changed: {:?}", event.data);
45        
46        // Process input data
47        let input_value = event.data.get("value")
48            .and_then(|v| v.as_str())
49            .unwrap_or("");
50
51        Ok(UIResponse {
52            success: true,
53            message: Some(format!("Input received: {}", input_value)),
54            data: Some(serde_json::json!({ "processed_input": input_value.to_uppercase() })),
55            request_id: event.request_id,
56        })
57    }).await;
58
59    // Example 4: Form submission handler
60    web_ui.bind_event("your-form-id", "submit", |event| {
61        println!("Form submitted: {:?}", event.data);
62        
63        // Extract form data from the formData object
64        let form_data = event.data.get("formData")
65            .and_then(|v| v.as_object());
66            
67        let name = form_data
68            .and_then(|fd| fd.get("name"))
69            .and_then(|v| v.as_str())
70            .unwrap_or("Unknown");
71        
72        let email = form_data
73            .and_then(|fd| fd.get("email"))
74            .and_then(|v| v.as_str())
75            .unwrap_or("No email provided");
76
77        // Process form data here
78        // You can validate, save to database, send emails, etc.
79
80        Ok(UIResponse {
81            success: true,
82            message: Some(format!("Thank you, {}! Form submitted successfully.", name)),
83            data: Some(serde_json::json!({ 
84                "user_name": name,
85                "user_email": email,
86            })),
87            request_id: event.request_id,
88        })
89    }).await;
90
91    // Example 5: Custom event with error handling
92    web_ui.bind_event("custom-action", "custom", |event| {
93        println!("Custom event received: {:?}", event);
94        
95        // Simulate some processing that might fail
96        let data = event.data.get("required_field");
97        
98        if data.is_none() {
99            return Ok(UIResponse {
100                success: false,
101                message: Some("Required field is missing".to_string()),
102                data: None,
103                request_id: event.request_id,
104            });
105        }
106
107        // Process the data...
108        
109        Ok(UIResponse {
110            success: true,
111            message: Some("Custom action completed".to_string()),
112            data: Some(serde_json::json!({ "result": "success" })),
113            request_id: event.request_id,
114        })
115    }).await;
116
117    // Start the web server
118    println!("Starting web UI server on http://localhost:3030");
119    web_ui.run().await?;
120    
121    Ok(())
122}
123
124// Helper functions (optional)
125
126/// Example helper function for data validation
127fn validate_email(email: &str) -> bool {
128    email.contains('@') && email.contains('.')
129}
130
131/// Example helper function for data processing
132fn process_user_data(name: &str, email: &str) -> Result<String, String> {
133    if name.is_empty() {
134        return Err("Name cannot be empty".to_string());
135    }
136    
137    if !validate_email(email) {
138        return Err("Invalid email format".to_string());
139    }
140    
141    Ok(format!("User {} with email {} processed successfully", name, email))
142}
143
144/// Example helper function for generating responses
145fn create_success_response(message: &str, data: serde_json::Value, request_id: Option<u32>) -> UIResponse {
146    UIResponse {
147        success: true,
148        message: Some(message.to_string()),
149        data: Some(data),
150        request_id,
151    }
152}
153
154fn create_error_response(error: &str, request_id: Option<u32>) -> UIResponse {
155    UIResponse {
156        success: false,
157        message: Some(error.to_string()),
158        data: None,
159        request_id,
160    }
161}