euv-example 0.3.5

An example application demonstrating the euv UI framework with reactive signals, custom components, and WebAssembly.
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use crate::*;

/// Reactive state for the browser API demo page.
///
/// Aggregates all signals needed for the localStorage, sessionStorage,
/// clipboard, window, navigator, location, and console sections.
#[derive(Clone, Copy, Data)]
pub struct UseBrowserApi {
    /// The localStorage key input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub local_key: Signal<String>,
    /// The localStorage value input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub local_value: Signal<String>,
    /// The localStorage operation result.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub local_result: Signal<String>,
    /// The sessionStorage key input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub session_key: Signal<String>,
    /// The sessionStorage value input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub session_value: Signal<String>,
    /// The sessionStorage operation result.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub session_result: Signal<String>,
    /// The clipboard text input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub clipboard_text: Signal<String>,
    /// The clipboard operation result.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub clipboard_result: Signal<String>,
    /// The window size display.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub window_size: Signal<String>,
    /// The user agent string.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub user_agent: Signal<String>,
    /// The navigator language.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub language: Signal<String>,
    /// The location href.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub location_url: Signal<String>,
    /// The location origin.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub location_origin_val: Signal<String>,
    /// The location pathname.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub location_pathname_val: Signal<String>,
    /// The console message input.
    #[get(pub, type(copy))]
    #[set(pub)]
    pub console_input: Signal<String>,
}

/// Provides a default empty browser API state with placeholder signals.
impl Default for UseBrowserApi {
    fn default() -> Self {
        UseBrowserApi {
            local_key: Signal::new("".to_string()),
            local_value: Signal::new("".to_string()),
            local_result: Signal::new("".to_string()),
            session_key: Signal::new("".to_string()),
            session_value: Signal::new("".to_string()),
            session_result: Signal::new("".to_string()),
            clipboard_text: Signal::new("".to_string()),
            clipboard_result: Signal::new("".to_string()),
            window_size: Signal::new("".to_string()),
            user_agent: Signal::new("".to_string()),
            language: Signal::new("".to_string()),
            location_url: Signal::new("".to_string()),
            location_origin_val: Signal::new("".to_string()),
            location_pathname_val: Signal::new("".to_string()),
            console_input: Signal::new("".to_string()),
        }
    }
}

/// Creates browser API demo state signals wrapped in a `UseBrowserApi` struct.
///
/// # Returns
///
/// - `UseBrowserApi`: The browser API demo state.
pub fn use_browser_api() -> UseBrowserApi {
    let mut state: UseBrowserApi = UseBrowserApi::default();
    state.set_local_key(use_signal(|| "euv-demo-key".to_string()));
    state.set_local_value(use_signal(|| "".to_string()));
    state.set_local_result(use_signal(|| "No data yet".to_string()));
    state.set_session_key(use_signal(|| "euv-session-key".to_string()));
    state.set_session_value(use_signal(|| "".to_string()));
    state.set_session_result(use_signal(|| "No data yet".to_string()));
    state.set_clipboard_text(use_signal(|| "".to_string()));
    state.set_clipboard_result(use_signal(|| "".to_string()));
    state.set_window_size(use_signal(|| {
        let (width, height): (i32, i32) = window_inner_size();
        format!("{} x {}", width, height)
    }));
    state.set_user_agent(use_signal(navigator_user_agent));
    state.set_language(use_signal(navigator_language));
    state.set_location_url(use_signal(location_href));
    state.set_location_origin_val(use_signal(location_origin));
    state.set_location_pathname_val(use_signal(location_pathname));
    state.set_console_input(use_signal(|| "".to_string()));
    state
}

/// Reads a value from the browser localStorage.
///
/// # Arguments
///
/// - `&str`: The key to look up.
///
/// # Returns
///
/// - `Option<String>`: The stored value if found, or None.
pub fn local_storage_get(key: &str) -> Option<String> {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = window.local_storage().ok()??;
    storage.get_item(key).ok()?
}

/// Writes a key-value pair to the browser localStorage.
///
/// # Arguments
///
/// - `&str`: The key to store.
/// - `&str`: The value to store.
pub fn local_storage_set(key: &str, value: &str) {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = match window.local_storage() {
        Ok(Some(s)) => s,
        _ => return,
    };
    let _ = storage.set_item(key, value);
}

/// Removes a key from the browser localStorage.
///
/// # Arguments
///
/// - `&str`: The key to remove.
pub fn local_storage_remove(key: &str) {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = match window.local_storage() {
        Ok(Some(s)) => s,
        _ => return,
    };
    let _ = storage.remove_item(key);
}

/// Reads a value from the browser sessionStorage.
///
/// # Arguments
///
/// - `&str`: The key to look up.
///
/// # Returns
///
/// - `Option<String>`: The stored value if found, or None.
pub fn session_storage_get(key: &str) -> Option<String> {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = window.session_storage().ok()??;
    storage.get_item(key).ok()?
}

/// Writes a key-value pair to the browser sessionStorage.
///
/// # Arguments
///
/// - `&str`: The key to store.
/// - `&str`: The value to store.
pub fn session_storage_set(key: &str, value: &str) {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = match window.session_storage() {
        Ok(Some(s)) => s,
        _ => return,
    };
    let _ = storage.set_item(key, value);
}

/// Removes a key from the browser sessionStorage.
///
/// # Arguments
///
/// - `&str`: The key to remove.
pub fn session_storage_remove(key: &str) {
    let window: Window = window().expect("no global window exists");
    let storage: Storage = match window.session_storage() {
        Ok(Some(s)) => s,
        _ => return,
    };
    let _ = storage.remove_item(key);
}

/// Reads text from the system clipboard asynchronously.
///
/// # Returns
///
/// - `String`: The clipboard text content, or an error message.
pub async fn clipboard_read_text() -> String {
    let window: Window = window().expect("no global window exists");
    let navigator: Navigator = window.navigator();
    let clipboard: Clipboard = navigator.clipboard();
    let promise: js_sys::Promise = clipboard.read_text();
    let future: wasm_bindgen_futures::JsFuture = wasm_bindgen_futures::JsFuture::from(promise);
    match future.await {
        Ok(value) => value
            .as_string()
            .unwrap_or_else(|| "No text content".to_string()),
        Err(_) => "Failed to read clipboard".to_string(),
    }
}

/// Writes text to the system clipboard asynchronously.
///
/// # Arguments
///
/// - `&str`: The text to write.
///
/// # Returns
///
/// - `bool`: Whether the write succeeded.
pub async fn clipboard_write_text(text: &str) -> bool {
    let window: Window = window().expect("no global window exists");
    let navigator: Navigator = window.navigator();
    let clipboard: Clipboard = navigator.clipboard();
    let promise: js_sys::Promise = clipboard.write_text(text);
    let future: wasm_bindgen_futures::JsFuture = wasm_bindgen_futures::JsFuture::from(promise);
    future.await.is_ok()
}

/// Reads the browser window inner dimensions.
///
/// # Returns
///
/// - `(i32, i32)`: A tuple of (inner_width, inner_height).
pub fn window_inner_size() -> (i32, i32) {
    let window: Window = window().expect("no global window exists");
    let width: i32 = window
        .inner_width()
        .ok()
        .and_then(|v| v.as_f64())
        .map(|v| v as i32)
        .unwrap_or(0);
    let height: i32 = window
        .inner_height()
        .ok()
        .and_then(|v| v.as_f64())
        .map(|v| v as i32)
        .unwrap_or(0);
    (width, height)
}

/// Reads the browser navigator user agent string.
///
/// # Returns
///
/// - `String`: The user agent string.
pub fn navigator_user_agent() -> String {
    let window: Window = window().expect("no global window exists");
    window
        .navigator()
        .user_agent()
        .unwrap_or_else(|_| "Unknown".to_string())
}

/// Reads the browser navigator language.
///
/// # Returns
///
/// - `String`: The preferred language string.
pub fn navigator_language() -> String {
    let window: Window = window().expect("no global window exists");
    window
        .navigator()
        .language()
        .unwrap_or_else(|| "Unknown".to_string())
}

/// Reads the current browser location href.
///
/// # Returns
///
/// - `String`: The current full URL.
pub fn location_href() -> String {
    let window: Window = window().expect("no global window exists");
    window
        .location()
        .href()
        .unwrap_or_else(|_| "Unknown".to_string())
}

/// Reads the current browser location origin.
///
/// # Returns
///
/// - `String`: The origin portion of the URL.
pub fn location_origin() -> String {
    let window: Window = window().expect("no global window exists");
    window
        .location()
        .origin()
        .unwrap_or_else(|_| "Unknown".to_string())
}

/// Reads the current browser location pathname.
///
/// # Returns
///
/// - `String`: The pathname portion of the URL.
pub fn location_pathname() -> String {
    let window: Window = window().expect("no global window exists");
    window
        .location()
        .pathname()
        .unwrap_or_else(|_| "Unknown".to_string())
}

/// Creates a click event handler that sets a localStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to set the localStorage item.
pub fn local_storage_on_set(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.local_key.get();
        let value: String = state.local_value.get();
        if !key.is_empty() {
            local_storage_set(&key, &value);
            state.local_result.set(format!("Set: {} = {}", key, value));
        }
    })
}

/// Creates a click event handler that gets a localStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to get the localStorage item.
pub fn local_storage_on_get(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.local_key.get();
        let value: Option<String> = local_storage_get(&key);
        match value {
            Some(v) => state.local_result.set(format!("Get: {} = {}", key, v)),
            None => state.local_result.set(format!("Key '{}' not found", key)),
        }
    })
}

/// Creates a click event handler that removes a localStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to remove the localStorage item.
pub fn local_storage_on_remove(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.local_key.get();
        local_storage_remove(&key);
        state.local_result.set(format!("Removed key: {}", key));
    })
}

/// Creates a click event handler that sets a sessionStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to set the sessionStorage item.
pub fn session_storage_on_set(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.session_key.get();
        let value: String = state.session_value.get();
        if !key.is_empty() {
            session_storage_set(&key, &value);
            state
                .session_result
                .set(format!("Set: {} = {}", key, value));
        }
    })
}

/// Creates a click event handler that gets a sessionStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to get the sessionStorage item.
pub fn session_storage_on_get(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.session_key.get();
        let value: Option<String> = session_storage_get(&key);
        match value {
            Some(v) => state.session_result.set(format!("Get: {} = {}", key, v)),
            None => state.session_result.set(format!("Key '{}' not found", key)),
        }
    })
}

/// Creates a click event handler that removes a sessionStorage item.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to remove the sessionStorage item.
pub fn session_storage_on_remove(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let key: String = state.session_key.get();
        session_storage_remove(&key);
        state.session_result.set(format!("Removed key: {}", key));
    })
}

/// Creates a click event handler that copies text to clipboard.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to copy text to clipboard.
pub fn clipboard_on_copy(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let text: String = state.clipboard_text.get();
        let text_clone: String = text.clone();
        let result: Signal<String> = state.clipboard_result;
        if text.is_empty() {
            result.set("Please enter text to copy".to_string());
        } else {
            wasm_bindgen_futures::spawn_local(async move {
                let success: bool = clipboard_write_text(&text_clone).await;
                if success {
                    result.set("Copied to clipboard!".to_string());
                } else {
                    result.set("Failed to copy".to_string());
                }
            });
        }
    })
}

/// Creates a click event handler that reads text from clipboard.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to read text from clipboard.
pub fn clipboard_on_paste(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let result: Signal<String> = state.clipboard_result;
        wasm_bindgen_futures::spawn_local(async move {
            let text: String = clipboard_read_text().await;
            result.set(format!("Pasted: {}", text));
        });
    })
}

/// Creates a click event handler that refreshes the window size display.
///
/// # Arguments
///
/// - `UseBrowserApi`: The browser API state.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler to refresh the window size.
pub fn window_on_refresh_size(state: UseBrowserApi) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let (width, height): (i32, i32) = window_inner_size();
        state.window_size.set(format!("{} x {}", width, height));
    })
}

/// Creates a click event handler that logs a console message.
///
/// # Arguments
///
/// - `Signal<String>`: The console input signal.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler for console.log.
pub fn console_on_log(console_input: Signal<String>) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let message: String = console_input.get();
        Console::log(&message);
    })
}

/// Creates a click event handler that warns a console message.
///
/// # Arguments
///
/// - `Signal<String>`: The console input signal.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler for console.warn.
pub fn console_on_warn(console_input: Signal<String>) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let message: String = console_input.get();
        Console::warn(&message);
    })
}

/// Creates a click event handler that errors a console message.
///
/// # Arguments
///
/// - `Signal<String>`: The console input signal.
///
/// # Returns
///
/// - `NativeEventHandler`: A click handler for console.error.
pub fn console_on_error(console_input: Signal<String>) -> NativeEventHandler {
    NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
        let message: String = console_input.get();
        Console::error(&message);
    })
}