Struct WebUI

Source
pub struct WebUI { /* private fields */ }
Expand description

The main WebUI server instance.

This struct represents a configured web server that can handle UI events and serve static files. It maintains an event registry for mapping UI events to handler functions.

§Examples

use web_ui::{WebUI, WebUIConfig};

let config = WebUIConfig::default().with_port(3030);
let webui = WebUI::new(config);

// Register event handlers
webui.bind_click("button1", || {
    println!("Button 1 clicked!");
}).await;

// Start the server (commented out for doctest)
// webui.run().await

Implementations§

Source§

impl WebUI

Source

pub fn new(config: WebUIConfig) -> Self

Creates a new WebUI instance with the given configuration.

§Arguments
  • config - Configuration settings for the web server
§Examples
use web_ui::{WebUI, WebUIConfig};

let config = WebUIConfig::default().with_port(8080);
let webui = WebUI::new(config);
Examples found in repository?
examples/welcome.rs (line 10)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let config = WebUIConfig::default()
6        .with_port(3030)
7        .with_title("My Web App".to_string())
8        .with_static_dir("./static".to_string());
9
10    let web_ui = WebUI::new(config);
11    web_ui.run().await?;
12    
13    Ok(())
14}
More examples
Hide additional examples
examples/hello.rs (line 7)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let config = WebUIConfig::default()
6        .with_static_dir("./static/hello".to_string());
7    let web_ui = WebUI::new(config);
8    
9    // Simple button click handler
10    web_ui.bind_click("hello-btn", || {
11        println!("Hello, World!");
12    }).await;
13    
14    println!("Starting simple web UI on http://localhost:3030");
15    web_ui.run().await
16}
examples/event_binding.rs (line 14)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Create configuration
8    let config = WebUIConfig::default()
9        .with_port(3030)
10        .with_title("Event Binding Demo".to_string())
11        .with_static_dir("./static/event_binding".to_string());
12
13    // Create WebUI instance
14    let web_ui = WebUI::new(config);
15
16    // Shared counter for demonstrating state
17    let click_counter = Arc::new(AtomicU32::new(0));
18
19    // Bind a simple hello button
20    web_ui.bind_click("hello-btn", || {
21        println!("Hello button was clicked!");
22    }).await;
23
24    // Bind a counter button with state and response data
25    let counter_clone = click_counter.clone();
26    web_ui.bind_event("count-btn", "click", move |_event| {
27        let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28        println!("Count button clicked {} times", count);
29        
30        Ok(UIResponse {
31            success: true,
32            message: Some(format!("Button clicked {} times", count)),
33            data: Some(serde_json::json!({ "count": count })),
34            request_id: None,
35        })
36    }).await;
37
38    // Bind a greeting button that uses input data
39    web_ui.bind_event("greet-btn", "click", |event| {
40        println!("Greet button event data: {:?}", event.data);
41        
42        // Try to get the name from the input field
43        let name = if let Some(name_value) = event.data.get("name-input") {
44            name_value.as_str().unwrap_or("Anonymous")
45        } else {
46            // If not provided in event data, we'll need to handle it differently
47            "Friend"
48        };
49
50        let greeting = format!("Hello, {}! Nice to meet you.", name);
51        println!("Greeting: {}", greeting);
52
53        Ok(UIResponse {
54            success: true,
55            message: Some(greeting),
56            data: Some(serde_json::json!({ 
57                "greeting_sent": true,
58                "name": name 
59            })),
60            request_id: None,
61        })
62    }).await;
63
64    // Bind input change events for real-time updates
65    web_ui.bind_event("name-input", "change", |event| {
66        if let Some(value) = event.data.get("value") {
67            if let Some(name) = value.as_str() {
68                println!("Name input changed to: {}", name);
69                return Ok(UIResponse {
70                    success: true,
71                    message: Some(format!("Name updated to: {}", name)),
72                    data: None,
73                    request_id: None,
74                });
75            }
76        }
77        
78        Ok(UIResponse {
79            success: true,
80            message: Some("Name input changed".to_string()),
81            data: None,
82            request_id: None,
83        })
84    }).await;
85
86    println!("Starting Web UI server...");
87    println!("Visit http://localhost:3030 to see the demo");
88    println!("Try clicking the buttons to see the event binding in action!");
89
90    // Start the server
91    web_ui.run().await
92}
template/template.rs (line 14)
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}
Source

pub async fn bind_event<F>( &self, element_id: &str, event_type: &str, handler: F, )
where F: Fn(UIEvent) -> Result<UIResponse, String> + Send + Sync + 'static,

Register an event handler for a specific element and event type.

This method allows you to bind custom handler functions to UI events. The handler function receives a UIEvent and should return a UIResponse or an error message.

§Arguments
  • element_id - The ID of the HTML element to bind to
  • event_type - The type of event to handle (e.g., “click”, “change”)
  • handler - The function to call when the event occurs
§Examples
use web_ui::{WebUI, WebUIConfig, UIEvent, UIResponse};
use serde_json::json;

let webui = WebUI::new(WebUIConfig::default());

webui.bind_event("form1", "submit", |event| {
    println!("Form submitted with data: {:?}", event.data);
    Ok(UIResponse {
        success: true,
        message: Some("Form processed successfully".to_string()),
        data: Some(json!({"result": "ok"})),
        request_id: event.request_id,
    })
}).await;
Examples found in repository?
examples/event_binding.rs (lines 26-36)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Create configuration
8    let config = WebUIConfig::default()
9        .with_port(3030)
10        .with_title("Event Binding Demo".to_string())
11        .with_static_dir("./static/event_binding".to_string());
12
13    // Create WebUI instance
14    let web_ui = WebUI::new(config);
15
16    // Shared counter for demonstrating state
17    let click_counter = Arc::new(AtomicU32::new(0));
18
19    // Bind a simple hello button
20    web_ui.bind_click("hello-btn", || {
21        println!("Hello button was clicked!");
22    }).await;
23
24    // Bind a counter button with state and response data
25    let counter_clone = click_counter.clone();
26    web_ui.bind_event("count-btn", "click", move |_event| {
27        let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28        println!("Count button clicked {} times", count);
29        
30        Ok(UIResponse {
31            success: true,
32            message: Some(format!("Button clicked {} times", count)),
33            data: Some(serde_json::json!({ "count": count })),
34            request_id: None,
35        })
36    }).await;
37
38    // Bind a greeting button that uses input data
39    web_ui.bind_event("greet-btn", "click", |event| {
40        println!("Greet button event data: {:?}", event.data);
41        
42        // Try to get the name from the input field
43        let name = if let Some(name_value) = event.data.get("name-input") {
44            name_value.as_str().unwrap_or("Anonymous")
45        } else {
46            // If not provided in event data, we'll need to handle it differently
47            "Friend"
48        };
49
50        let greeting = format!("Hello, {}! Nice to meet you.", name);
51        println!("Greeting: {}", greeting);
52
53        Ok(UIResponse {
54            success: true,
55            message: Some(greeting),
56            data: Some(serde_json::json!({ 
57                "greeting_sent": true,
58                "name": name 
59            })),
60            request_id: None,
61        })
62    }).await;
63
64    // Bind input change events for real-time updates
65    web_ui.bind_event("name-input", "change", |event| {
66        if let Some(value) = event.data.get("value") {
67            if let Some(name) = value.as_str() {
68                println!("Name input changed to: {}", name);
69                return Ok(UIResponse {
70                    success: true,
71                    message: Some(format!("Name updated to: {}", name)),
72                    data: None,
73                    request_id: None,
74                });
75            }
76        }
77        
78        Ok(UIResponse {
79            success: true,
80            message: Some("Name input changed".to_string()),
81            data: None,
82            request_id: None,
83        })
84    }).await;
85
86    println!("Starting Web UI server...");
87    println!("Visit http://localhost:3030 to see the demo");
88    println!("Try clicking the buttons to see the event binding in action!");
89
90    // Start the server
91    web_ui.run().await
92}
More examples
Hide additional examples
template/template.rs (lines 27-40)
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}
Source

pub async fn bind_click<F>(&self, element_id: &str, handler: F)
where F: Fn() + Send + Sync + 'static,

Register a simple click handler that doesn’t return data.

This is a convenience method for registering click event handlers that don’t need to process event data or return responses. The handler function is called when the specified element is clicked.

§Arguments
  • element_id - The ID of the HTML element to bind to
  • handler - The function to call when the element is clicked
§Examples
use web_ui::{WebUI, WebUIConfig};

let webui = WebUI::new(WebUIConfig::default());

webui.bind_click("logout-button", || {
    println!("User logged out");
    // Perform logout logic here
}).await;
Examples found in repository?
examples/hello.rs (lines 10-12)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let config = WebUIConfig::default()
6        .with_static_dir("./static/hello".to_string());
7    let web_ui = WebUI::new(config);
8    
9    // Simple button click handler
10    web_ui.bind_click("hello-btn", || {
11        println!("Hello, World!");
12    }).await;
13    
14    println!("Starting simple web UI on http://localhost:3030");
15    web_ui.run().await
16}
More examples
Hide additional examples
examples/event_binding.rs (lines 20-22)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Create configuration
8    let config = WebUIConfig::default()
9        .with_port(3030)
10        .with_title("Event Binding Demo".to_string())
11        .with_static_dir("./static/event_binding".to_string());
12
13    // Create WebUI instance
14    let web_ui = WebUI::new(config);
15
16    // Shared counter for demonstrating state
17    let click_counter = Arc::new(AtomicU32::new(0));
18
19    // Bind a simple hello button
20    web_ui.bind_click("hello-btn", || {
21        println!("Hello button was clicked!");
22    }).await;
23
24    // Bind a counter button with state and response data
25    let counter_clone = click_counter.clone();
26    web_ui.bind_event("count-btn", "click", move |_event| {
27        let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28        println!("Count button clicked {} times", count);
29        
30        Ok(UIResponse {
31            success: true,
32            message: Some(format!("Button clicked {} times", count)),
33            data: Some(serde_json::json!({ "count": count })),
34            request_id: None,
35        })
36    }).await;
37
38    // Bind a greeting button that uses input data
39    web_ui.bind_event("greet-btn", "click", |event| {
40        println!("Greet button event data: {:?}", event.data);
41        
42        // Try to get the name from the input field
43        let name = if let Some(name_value) = event.data.get("name-input") {
44            name_value.as_str().unwrap_or("Anonymous")
45        } else {
46            // If not provided in event data, we'll need to handle it differently
47            "Friend"
48        };
49
50        let greeting = format!("Hello, {}! Nice to meet you.", name);
51        println!("Greeting: {}", greeting);
52
53        Ok(UIResponse {
54            success: true,
55            message: Some(greeting),
56            data: Some(serde_json::json!({ 
57                "greeting_sent": true,
58                "name": name 
59            })),
60            request_id: None,
61        })
62    }).await;
63
64    // Bind input change events for real-time updates
65    web_ui.bind_event("name-input", "change", |event| {
66        if let Some(value) = event.data.get("value") {
67            if let Some(name) = value.as_str() {
68                println!("Name input changed to: {}", name);
69                return Ok(UIResponse {
70                    success: true,
71                    message: Some(format!("Name updated to: {}", name)),
72                    data: None,
73                    request_id: None,
74                });
75            }
76        }
77        
78        Ok(UIResponse {
79            success: true,
80            message: Some("Name input changed".to_string()),
81            data: None,
82            request_id: None,
83        })
84    }).await;
85
86    println!("Starting Web UI server...");
87    println!("Visit http://localhost:3030 to see the demo");
88    println!("Try clicking the buttons to see the event binding in action!");
89
90    // Start the server
91    web_ui.run().await
92}
template/template.rs (lines 20-23)
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}
Source

pub async fn run(self) -> Result<(), Box<dyn Error>>

Starts the web server and begins listening for connections.

This method consumes the WebUI instance and starts the web server on the configured host and port. The server will continue running until the process is terminated or an error occurs.

§Returns

Ok(()) if the server shuts down gracefully, or an error if the server fails to start or encounters a fatal error.

§Examples
use web_ui::{WebUI, WebUIConfig};

let config = WebUIConfig::default().with_port(3030);
let webui = WebUI::new(config);
 
println!("Starting server...");
// webui.run().await // This would start the server
Examples found in repository?
examples/welcome.rs (line 11)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let config = WebUIConfig::default()
6        .with_port(3030)
7        .with_title("My Web App".to_string())
8        .with_static_dir("./static".to_string());
9
10    let web_ui = WebUI::new(config);
11    web_ui.run().await?;
12    
13    Ok(())
14}
More examples
Hide additional examples
examples/hello.rs (line 15)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    let config = WebUIConfig::default()
6        .with_static_dir("./static/hello".to_string());
7    let web_ui = WebUI::new(config);
8    
9    // Simple button click handler
10    web_ui.bind_click("hello-btn", || {
11        println!("Hello, World!");
12    }).await;
13    
14    println!("Starting simple web UI on http://localhost:3030");
15    web_ui.run().await
16}
examples/event_binding.rs (line 91)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // Create configuration
8    let config = WebUIConfig::default()
9        .with_port(3030)
10        .with_title("Event Binding Demo".to_string())
11        .with_static_dir("./static/event_binding".to_string());
12
13    // Create WebUI instance
14    let web_ui = WebUI::new(config);
15
16    // Shared counter for demonstrating state
17    let click_counter = Arc::new(AtomicU32::new(0));
18
19    // Bind a simple hello button
20    web_ui.bind_click("hello-btn", || {
21        println!("Hello button was clicked!");
22    }).await;
23
24    // Bind a counter button with state and response data
25    let counter_clone = click_counter.clone();
26    web_ui.bind_event("count-btn", "click", move |_event| {
27        let count = counter_clone.fetch_add(1, Ordering::SeqCst) + 1;
28        println!("Count button clicked {} times", count);
29        
30        Ok(UIResponse {
31            success: true,
32            message: Some(format!("Button clicked {} times", count)),
33            data: Some(serde_json::json!({ "count": count })),
34            request_id: None,
35        })
36    }).await;
37
38    // Bind a greeting button that uses input data
39    web_ui.bind_event("greet-btn", "click", |event| {
40        println!("Greet button event data: {:?}", event.data);
41        
42        // Try to get the name from the input field
43        let name = if let Some(name_value) = event.data.get("name-input") {
44            name_value.as_str().unwrap_or("Anonymous")
45        } else {
46            // If not provided in event data, we'll need to handle it differently
47            "Friend"
48        };
49
50        let greeting = format!("Hello, {}! Nice to meet you.", name);
51        println!("Greeting: {}", greeting);
52
53        Ok(UIResponse {
54            success: true,
55            message: Some(greeting),
56            data: Some(serde_json::json!({ 
57                "greeting_sent": true,
58                "name": name 
59            })),
60            request_id: None,
61        })
62    }).await;
63
64    // Bind input change events for real-time updates
65    web_ui.bind_event("name-input", "change", |event| {
66        if let Some(value) = event.data.get("value") {
67            if let Some(name) = value.as_str() {
68                println!("Name input changed to: {}", name);
69                return Ok(UIResponse {
70                    success: true,
71                    message: Some(format!("Name updated to: {}", name)),
72                    data: None,
73                    request_id: None,
74                });
75            }
76        }
77        
78        Ok(UIResponse {
79            success: true,
80            message: Some("Name input changed".to_string()),
81            data: None,
82            request_id: None,
83        })
84    }).await;
85
86    println!("Starting Web UI server...");
87    println!("Visit http://localhost:3030 to see the demo");
88    println!("Try clicking the buttons to see the event binding in action!");
89
90    // Start the server
91    web_ui.run().await
92}
template/template.rs (line 119)
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}

Auto Trait Implementations§

§

impl Freeze for WebUI

§

impl !RefUnwindSafe for WebUI

§

impl Send for WebUI

§

impl Sync for WebUI

§

impl Unpin for WebUI

§

impl !UnwindSafe for WebUI

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,