paiagram/rw_data/
write.rs1#[cfg(not(target_arch = "wasm32"))]
2pub fn write_text_file(data: &str, filename: &str) -> Result<(), std::io::Error> {
3 let mut save_dialog = rfd::FileDialog::new();
4 save_dialog = save_dialog.set_file_name(filename);
5 if let Some(path) = save_dialog.save_file() {
6 std::fs::write(&path, data)?;
7 bevy::log::info!("File saved to {:?}", path);
8 }
9 Ok(())
10}
11
12#[cfg(target_arch = "wasm32")]
14pub fn write_text_file(data: &str, filename: &str) -> Result<(), String> {
15 use wasm_bindgen::JsCast;
16 use web_sys::{Blob, BlobPropertyBag, Url};
17
18 let window = web_sys::window().ok_or("no global window found")?;
19 let document = window
20 .document()
21 .ok_or("should have a document on window")?;
22 let body = document.body().ok_or("document should have a body")?;
23
24 let mut properties = BlobPropertyBag::new();
26 properties.type_("text/plain");
27
28 let data_array = js_sys::Array::of1(&wasm_bindgen::JsValue::from_str(data));
29 let blob = Blob::new_with_str_sequence_and_options(&data_array, &properties)
30 .map_err(|e| format!("Failed to create blob: {:?}", e))?;
31
32 let url = Url::create_object_url_with_blob(&blob)
34 .map_err(|e| format!("Failed to create URL: {:?}", e))?;
35
36 let anchor = document
38 .create_element("a")
39 .map_err(|e| format!("Failed to create anchor: {:?}", e))?
40 .dyn_into::<web_sys::HtmlAnchorElement>()
41 .map_err(|e| format!("Failed to cast to anchor: {:?}", e))?;
42
43 anchor.set_href(&url);
44 anchor.set_download(filename);
45
46 body.append_child(&anchor)
48 .map_err(|e| format!("Failed to append anchor: {:?}", e))?;
49 anchor.click();
50 body.remove_child(&anchor)
51 .map_err(|e| format!("Failed to remove anchor: {:?}", e))?;
52
53 Url::revoke_object_url(&url).map_err(|e| format!("Failed to revoke URL: {:?}", e))?;
55
56 Ok(())
57}