fantasy_craft/core/web_context.rs
1use macroquad::prelude::*;
2
3#[allow(dead_code)]
4unsafe extern "C" {
5 fn js_get_base_url(ptr: *mut u8, cap: i32) -> i32;
6}
7
8pub struct WebContext;
9
10impl WebContext {
11 /// Retrieves the base URL for assets from the JavaScript layer.
12 pub fn get_base_url() -> String {
13 #[cfg(target_arch = "wasm32")]
14 unsafe {
15 // 1. Allocate a buffer in Rust memory to hold the string
16 let mut buffer = [0u8; 1024]; // 1024 chars should be enough for a URL
17
18 // 2. Call the JS function, passing our buffer's pointer and capacity
19 let len = js_get_base_url(buffer.as_mut_ptr(), buffer.len() as i32);
20
21 // 3. Convert the written bytes back to a Rust String
22 let bytes = &buffer[0..len as usize];
23 String::from_utf8_lossy(bytes).to_string()
24 }
25
26 #[cfg(not(target_arch = "wasm32"))]
27 {
28 // Fallback for desktop builds (local debugging)
29 String::from("")
30 }
31 }
32}