Add support for loading external files in the wasm interpreter

The imported files don't have tabs though, and caching is done entirely
by the browser.
This commit is contained in:
Simon Hausmann 2020-10-30 17:49:18 +01:00
parent a2ae00ee92
commit 330f61d6c1
2 changed files with 26 additions and 2 deletions

View file

@ -24,11 +24,31 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub async fn compile_from_string(
source: String,
base_url: String,
mut optional_import_callback: Option<js_sys::Function>,
) -> Result<WrappedCompiledComp, JsValue> {
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
let c = match sixtyfps_interpreter::load(source, base_url.into(), Default::default()).await {
let mut config = sixtyfps_interpreter::CompilerConfiguration::default();
if let Some(callback) = optional_import_callback.take() {
config.open_import_fallback = Some(Box::new(move |file_name| {
Box::pin({
let callback = callback.clone();
let result = callback.call1(&JsValue::UNDEFINED, &file_name.into());
let promise: js_sys::Promise = result.unwrap().into();
async move {
let future = wasm_bindgen_futures::JsFuture::from(promise);
match future.await {
Ok(js_ok) => Ok(js_ok.as_string().unwrap_or_default()),
Err(js_err) => Err(js_err.as_string().unwrap_or_default()),
}
}
})
}));
}
let c = match sixtyfps_interpreter::load(source, base_url.into(), config).await {
(Ok(c), ..) => {
//TODO: warnings.print();
c

View file

@ -98,7 +98,11 @@ async function render_or_error(source, base_url, div) {
div.innerHTML = "";
div.appendChild(canvas);
try {
var compiled_component = await sixtyfps.compile_from_string(source, base_url);
var compiled_component = await sixtyfps.compile_from_string(source, base_url, async (file_name: string) => {
let u = new URL(file_name, base_url);
const response = await fetch(u.toString());
return await response.text();
});
} catch (e) {
let text = document.createTextNode(e.message);
let p = document.createElement('pre');