euv_ui/hook/use_clipboard/impl.rs
1use super::*;
2
3/// Inherent implementation of [`UseClipboard`].
4impl UseClipboard {
5 /// Creates a handle whose status starts at
6 /// [`UseClipboardStatus::Idle`].
7 ///
8 /// # Returns
9 ///
10 /// - `UseClipboard` - The fresh handle.
11 pub(crate) fn new() -> Self {
12 Self {
13 status: Signal::create(UseClipboardStatus::Idle),
14 }
15 }
16
17 /// Returns the current status as a snapshot.
18 ///
19 /// # Returns
20 ///
21 /// - `UseClipboardStatus` - The outcome of the last write.
22 pub fn current_status(&self) -> UseClipboardStatus {
23 self.get_status().get()
24 }
25
26 /// Copies `text` to the clipboard.
27 ///
28 /// The write is asynchronous: this call starts it and returns
29 /// whether the browser accepted the request. The status settles
30 /// once the browser has answered, so a render closure that reads
31 /// `get_status()` shows the result.
32 ///
33 /// # Arguments
34 ///
35 /// - `&str` - The text to copy.
36 ///
37 /// # Returns
38 ///
39 /// - `bool` - `true` when the write was started.
40 pub fn copy(&self, text: &str) -> bool {
41 #[cfg(target_arch = "wasm32")]
42 {
43 let Some(window) = browser_window() else {
44 self.get_status().set(UseClipboardStatus::Unavailable);
45 return false;
46 };
47 let navigator: Navigator = window.navigator();
48 let clipboard: Clipboard = navigator.clipboard();
49 let status: Signal<UseClipboardStatus> = self.get_status();
50 let payload: String = text.to_owned();
51 spawn_local(async move {
52 match clipboard.write_text(&payload).await {
53 Ok(_) => status.set(UseClipboardStatus::Copied),
54 Err(_) => status.set(UseClipboardStatus::Failed),
55 }
56 });
57 true
58 }
59 #[cfg(not(target_arch = "wasm32"))]
60 {
61 let _: &str = text;
62 self.get_status().set(UseClipboardStatus::Unavailable);
63 false
64 }
65 }
66}