From 2f7c3793c5160ed6eb01f6c677d3b4f1880f6d1d Mon Sep 17 00:00:00 2001 From: Jeremy Wall Date: Sun, 12 Nov 2023 18:28:21 -0500 Subject: [PATCH] Add an api for retrieving the id of the element --- macros/src/lib.rs | 20 ++++++++++++++------ wasm-web-component/src/lib.rs | 6 ++++-- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 8fc3117..2d00bf5 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -285,21 +285,29 @@ fn expand_template_struct(item_struct: ItemStruct) -> TokenStream { ); let trait_path = expand_crate_ref("wasm-web-component", parse_quote!(TemplateElement)); let expanded = quote! { - use std::sync::Once; + use std::sync::OnceLock; use web_sys::Node; - static #struct_once_name: Once = Once::new(); + static #struct_once_name: OnceLock> = OnceLock::new(); #item_struct impl #trait_path for #struct_name {} impl #struct_name { - #[doc = "Defines this HtmlTemplateElement and adds it to the document exactly once. Subsequent calls are noops."] - pub fn define_once() { // TODO(jwall): Should this return the element? - #struct_once_name.call_once(|| { + #[doc = "Defines this HtmlTemplateElement and adds it to the document exactly once. Subsequent calls are noops. Returns the the template element id it exists on the template element."] + pub fn define_once() -> Option<&'static Option> { + #struct_once_name.get_or_init(|| { let template_element = Self::render(); + let id: Option = template_element.get_attribute("id"); let body = web_sys::window().expect("Failed to get window") .document().expect("Failed to get window document"). body().expect("Failed to get document body"); body.append_child(template_element.as_ref()).expect("Failed to add template element to document"); - }) + return id; + }); + return #struct_once_name.get(); + } + + #[doc = "Returns the the template element id it exists. None if the element has not been defined yet. Some(&None) if the element has no id. Some(&Some(id)) if the element has an id."] + pub fn get_id() -> Option<&'static Option> { + return #struct_once_name.get(); } } }; diff --git a/wasm-web-component/src/lib.rs b/wasm-web-component/src/lib.rs index a314121..e108181 100644 --- a/wasm-web-component/src/lib.rs +++ b/wasm-web-component/src/lib.rs @@ -334,13 +334,15 @@ mod tests { .unwrap() .into(); let el: HtmlTemplateElement = val.into(); - el + el.set_attribute("id", "template-id").unwrap(); + return el; } } let body = window().unwrap().document().unwrap().body().unwrap(); assert!(!body.last_child().unwrap().has_type::()); - MyTemplate::define_once(); + let id = MyTemplate::define_once(); + assert_eq!(id.unwrap(), &Some(String::from("template-id"))); assert!(body.last_child().unwrap().has_type::()); } }