Compare commits

...

13 Commits
0.2.0 ... main

4 changed files with 279 additions and 53 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "wasm-web-component-macros"
version = "0.2.0"
version = "0.3.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -33,13 +33,23 @@ fn expand_crate_ref(name: &str, path: Path) -> syn::Path {
}
}
struct AttributeConfig {
class_name: Literal,
element_name: Literal,
observed_attributes: Literal,
observed_events: Literal,
base_class: Literal,
}
fn get_class_and_element_names(
args: Vec<NestedMeta>,
struct_name: &Ident,
) -> (Literal, Literal, Literal) {
) -> AttributeConfig {
let mut class_name = None;
let mut element_name = None;
let mut observed_attributes = None;
let mut observed_events = None;
let mut base_class = None;
for arg in args {
if let NestedMeta::Meta(Meta::NameValue(nv)) = arg {
if nv.path.is_ident("class_name") {
@ -54,6 +64,14 @@ fn get_class_and_element_names(
if let Lit::Str(nm) = nv.lit {
observed_attributes = Some(nm);
}
} else if nv.path.is_ident("observed_events") {
if let Lit::Str(nm) = nv.lit {
observed_events = Some(nm);
}
} else if nv.path.is_ident("base_class") {
if let Lit::Str(nm) = nv.lit {
base_class = Some(nm);
}
}
}
}
@ -69,11 +87,21 @@ fn get_class_and_element_names(
LitStr::new(&class_kebab, Span::call_site()).token()
}
};
let base_class = base_class.unwrap_or_else(|| LitStr::new("HTMLElement", Span::call_site())).token();
let observed_attributes = observed_attributes
.map(|n| n.token())
.unwrap_or_else(|| LitStr::new("[]", Span::call_site()).token());
(class_name, element_name, observed_attributes)
let observed_events = observed_events
.map(|n| n.token())
.unwrap_or_else(|| LitStr::new("[]", Span::call_site()).token());
AttributeConfig {
class_name,
element_name,
observed_attributes,
observed_events,
base_class,
}
}
fn expand_component_def(
@ -99,8 +127,15 @@ fn expand_component_def(
fn expand_wc_struct_trait_shim(
struct_name: &Ident,
once_name: &Ident,
observed_attrs: Literal,
config: AttributeConfig,
) -> syn::ItemImpl {
let AttributeConfig {
class_name: _,
element_name: _,
observed_attributes,
observed_events,
base_class,
} = config;
let trait_path = expand_crate_ref("wasm-web-component", parse_quote!(WebComponentDef));
let handle_path = expand_crate_ref("wasm-web-component", parse_quote!(WebComponentHandle));
parse_quote! {
@ -121,19 +156,30 @@ fn expand_wc_struct_trait_shim(
}
#[doc = "Defines this web component element if not defined already otherwise returns an error."]
pub fn define() -> std::result::Result<#handle_path, wasm_bindgen::JsValue> {
use wasm_bindgen::JsCast;
use web_sys::{window, Element, HtmlElement};
pub fn define() -> std::result::Result<#handle_path, ::wasm_bindgen::JsValue> {
use ::wasm_bindgen::JsCast;
use web_sys::{Element, HtmlElement};
let registry = web_sys::window().unwrap().custom_elements();
let maybe_element = registry.get(Self::element_name());
if maybe_element.is_truthy() {
return Err("Custom Element has already been defined".into());
}
let body = format!(
"class {name} extends HTMLElement {{
"class {name} extends {base_class} {{
constructor() {{
super();
this._impl = impl();
this._impl.init_impl(this);
var self = this;
if (self.shadowRoot) {{
for (const t of this.observedEvents()) {{
self.shadowRoot.addEventListener(t, function(evt) {{ self.handleComponentEvent(evt); }} );
}}
}} else {{
for (const t of self.observedEvents()) {{
self.addEventListener(t, function(evt) {{ self.handleComponentEvent(evt); }} );
}}
}}
}}
connectedCallback() {{
@ -148,11 +194,15 @@ fn expand_wc_struct_trait_shim(
return {observed_attributes};
}}
observedEvents() {{
return {observed_events};
}}
adoptedCallback() {{
this._impl.adopted_impl(this);
}}
attributeChangedCallback(name, oldValue, newValue) {{
attributeChangedCallback(name, oldValue, newValue) {{
this._impl.attribute_changed_impl(this, name, oldValue, newValue);
}}
@ -165,17 +215,19 @@ var element = customElements.get(\"{element_name}\");
return element;",
name = Self::class_name(),
element_name = Self::element_name(),
observed_attributes = #observed_attrs,
observed_attributes = #observed_attributes,
observed_events = #observed_events,
base_class = #base_class,
);
let fun = js_sys::Function::new_with_args("impl", &body);
let f: Box<dyn FnMut() -> Self> = Box::new(|| {
let obj = Self::new();
obj
});
let constructor_handle = wasm_bindgen::prelude::Closure::wrap(f).into_js_value().unchecked_into::<js_sys::Function>();
let constructor_handle = ::wasm_bindgen::prelude::Closure::wrap(f).into_js_value().unchecked_into::<js_sys::Function>();
let element = fun
.call1(
&window().unwrap(),
&web_sys::window().unwrap(),
constructor_handle.as_ref(),
)?
.dyn_into()?;
@ -190,47 +242,72 @@ return element;",
fn expand_wasm_shim(struct_name: &Ident) -> syn::ItemImpl {
let trait_path = expand_crate_ref("wasm-web-component", parse_quote!(WebComponentBinding));
parse_quote! {
#[wasm_bindgen::prelude::wasm_bindgen]
#[::wasm_bindgen::prelude::wasm_bindgen]
impl #struct_name {
#[wasm_bindgen::prelude::wasm_bindgen(constructor)]
#[::wasm_bindgen::prelude::wasm_bindgen(constructor)]
pub fn new() -> Self {
Self::default()
}
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn connected_impl(&self, element: &web_sys::HtmlElement) {
#[::wasm_bindgen::prelude::wasm_bindgen]
#[doc = "Attach an open shadowroot to our element."]
pub fn attach_shadow(&self, element: &web_sys::HtmlElement, root: &str) {
self.attach_shadow_with_mode(element, root, web_sys::ShadowRootMode::Open);
}
#[::wasm_bindgen::prelude::wasm_bindgen]
#[doc = "Attach a shadowroot with the given mode to our element."]
pub fn attach_shadow_with_mode(&self, element: &web_sys::HtmlElement, root: &str, mode: web_sys::ShadowRootMode) {
let shadow_root = element.attach_shadow(&web_sys::ShadowRootInit::new(mode)).unwrap();
shadow_root.set_inner_html(root);
}
#[::wasm_bindgen::prelude::wasm_bindgen]
pub fn init_impl(&mut self, element: &web_sys::HtmlElement) {
use #trait_path;
self.init(element);
self.init_mut(element);
}
#[::wasm_bindgen::prelude::wasm_bindgen]
pub fn connected_impl(&mut self, element: &web_sys::HtmlElement) {
use #trait_path;
self.connected(element);
self.connected_mut(element);
}
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn disconnected_impl(&self, element: &web_sys::HtmlElement) {
#[::wasm_bindgen::prelude::wasm_bindgen]
pub fn disconnected_impl(&mut self, element: &web_sys::HtmlElement) {
use #trait_path;
self.disconnected(element);
self.disconnected_mut(element);
}
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn adopted_impl(&self, element: &web_sys::HtmlElement) {
#[::wasm_bindgen::prelude::wasm_bindgen]
pub fn adopted_impl(&mut self, element: &web_sys::HtmlElement) {
use #trait_path;
self.adopted(element);
self.adopted_mut(element);
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[::wasm_bindgen::prelude::wasm_bindgen]
pub fn attribute_changed_impl(
&self,
&mut self,
element: &web_sys::HtmlElement,
name: wasm_bindgen::JsValue,
old_value: wasm_bindgen::JsValue,
new_value: wasm_bindgen::JsValue,
name: ::wasm_bindgen::JsValue,
old_value: ::wasm_bindgen::JsValue,
new_value: ::wasm_bindgen::JsValue,
) {
use #trait_path;
self.attribute_changed(element, name, old_value, new_value);
self.attribute_changed(element, name.clone(), old_value.clone(), new_value.clone());
self.attribute_changed_mut(element, name, old_value, new_value);
}
pub fn handle_component_event_impl(&self, element: &web_sys::HtmlElement, event: &web_sys::Event) {
pub fn handle_component_event_impl(&mut self, element: &web_sys::HtmlElement, event: &web_sys::Event) {
use #trait_path;
self.handle_event(element, event);
self.handle_event_mut(element, event);
}
}
}
@ -245,26 +322,22 @@ fn expand_binding(struct_name: &Ident) -> syn::ItemImpl {
fn expand_web_component_struct(
item_struct: ItemStruct,
class_name: Literal,
element_name: Literal,
observed_attributes: Literal,
config: AttributeConfig,
) -> TokenStream {
let struct_name = item_struct.ident.clone();
let struct_once_name = Ident::new(
&(struct_name.to_string().to_snake_case().to_uppercase() + "_ONCE"),
Span::call_site(),
);
let component_def = expand_component_def(&struct_name, &class_name, &element_name);
let component_def = expand_component_def(&struct_name, &config.class_name, &config.element_name);
let non_wasm_impl =
expand_wc_struct_trait_shim(&struct_name, &struct_once_name, observed_attributes);
expand_wc_struct_trait_shim(&struct_name, &struct_once_name, config);
let wasm_shim = expand_wasm_shim(&struct_name);
let binding_trait = expand_binding(&struct_name);
let expanded = quote! {
use std::sync::Once;
use wasm_bindgen;
#[allow(non_snake_case)]
static #struct_once_name: Once = Once::new();
#[wasm_bindgen::prelude::wasm_bindgen]
static #struct_once_name: std::sync::Once = std::sync::Once::new();
#[::wasm_bindgen::prelude::wasm_bindgen]
#[derive(Default, Debug)]
#item_struct
#component_def
@ -285,9 +358,8 @@ 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::OnceLock;
use web_sys::Node;
static #struct_once_name: OnceLock<Option<String>> = OnceLock::new();
static #struct_once_name: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
#item_struct
impl #trait_path for #struct_name {}
impl #struct_name {
@ -317,15 +389,14 @@ fn expand_template_struct(item_struct: ItemStruct) -> TokenStream {
/// Creates the necessary Rust and Javascript shims for a Web Component.
#[proc_macro_attribute]
pub fn web_component(attr: TokenStream, item: TokenStream) -> TokenStream {
// TODO(jwall): Attrs for class name and element name
// Gather our attributes
let args = parse_macro_input!(attr as AttributeArgs);
let item_struct = parse_macro_input!(item as ItemStruct);
let (class_name, element_name, observed_attributes) =
let config =
get_class_and_element_names(args, &item_struct.ident);
expand_web_component_struct(item_struct, class_name, element_name, observed_attributes)
expand_web_component_struct(item_struct, config)
}
/// Creates the neccessary Rust and Javascript shims for rendering an HtmlTemplateElement

View File

@ -1,6 +1,6 @@
[package]
name = "wasm-web-component"
version = "0.2.0"
version = "0.3.0"
edition = "2021"
[lib]
@ -24,8 +24,8 @@ version = "0.3"
version = "0.3"
features = [
"CustomElementRegistry",
"CustomEvent",
"Document",
"KeyboardEvent",
"Event",
"EventTarget",
"Element",

View File

@ -1,4 +1,5 @@
use js_sys::Function;
use wasm_bindgen::JsCast;
use wasm_bindgen::{convert::IntoWasmAbi, JsValue};
#[cfg(feature = "HtmlTemplateElement")]
use web_sys::HtmlTemplateElement;
@ -16,18 +17,27 @@ use web_sys::{window, Element, Event, HtmlElement, Window};
/// It supports three optional attributes `name = value` parameters.
/// * `class_name = "ClassName"` - The class name to use for the javascript shim. If not provided uses the structs name instead.
/// * `element_name = "class-name"` - A valid custom element name to use for the element. if not proviced derives it from the class name.
/// * `observed_attrs = "['attr1', attr2']"` - A javascript array with a list of observed attributes for this compoment. Defaults to "[]".
/// * `observed_attrs = "['attr1', 'attr2']"` - A javascript array with a list of observed attributes for this compoment. Defaults to "[]".
/// * `observed_events = "['click', 'change']"` - A javascript array with a list of observed event types for this compoment. Defaults to "[]".
/// * `base_class = "HTMLInputElement"` - The HTMLElement base class this custom-element should
/// inherit from. Defaults to "HTMLElement".
///
/// It will also create a `Self::define_once` method that will define the WebComponent exactly
/// once.
///
/// ## Example
///
/// ```rust
/// ```ignore
/// use web_sys::*;
/// use wasm_bindgen::*;
/// use wasm_web_component::{web_component, WebComponent, WebComponentHandle, WebComponentDef, WebComponentBinding};
///
/// #[web_component(
/// class_name = "MyElement",
/// element_name = "my-element",
/// observed_attrs = "['class']"
/// observed_attrs = "['class']",
/// observed_events = "['click']",
/// base_class = "HTMLElement"
/// )]
/// pub struct MyElementImpl {}
///
@ -65,6 +75,10 @@ use web_sys::{window, Element, Event, HtmlElement, Window};
/// )));
/// element.append_child(&node).unwrap();
/// }
///
/// fn handle_event(&self, element: &HtmlElement, event: &Event) {
/// // handle this event
/// }
/// }
///
/// pub fn define_me() {
@ -91,7 +105,10 @@ pub use wasm_web_component_macros::web_component;
/// if the template has not been defined yet `None` will get returned.
///
/// ## Example usage
/// ```rust
/// ```ignore
/// use wasm_web_component::*;
/// use wasm_bindgen::*;
/// # #[cfg(feature = "HtmlTemplateElement")]
/// #[template_element]
/// pub struct MyTemplate ();
/// impl TemplateElementRender for MyTemplate {
@ -123,15 +140,20 @@ pub trait WebComponentDef: IntoWasmAbi + Default {
}
fn create() -> Element {
Self::create_in_window(window().unwrap())
Self::create_in_window(window().expect("Failed to get window"))
}
fn create_in_window(window: Window) -> Element {
window
.document()
.unwrap()
.expect("Failed to get document")
.create_element(Self::element_name())
.unwrap()
.expect("Failed to create element")
}
/// Creates a custom event
fn custom_event(event_type: &str) -> web_sys::Event {
web_sys::CustomEvent::new(event_type).unwrap().dyn_into().unwrap()
}
fn element_name() -> &'static str;
@ -142,6 +164,15 @@ pub trait WebComponentDef: IntoWasmAbi + Default {
/// Each method is optional. You only need to implement the ones
/// you want to specify behavior for.
pub trait WebComponentBinding: WebComponentDef {
/// Called during element construction.
fn init(&self, _element: &HtmlElement) {
// noop
}
fn init_mut(&mut self, _element: &HtmlElement) {
// noop
}
/// Called when the web component is connected to the DOM.
/// This is when you should do any setup like attaching a ShadowDom
/// or appending elements.
@ -149,16 +180,33 @@ pub trait WebComponentBinding: WebComponentDef {
// noop
}
/// Called when the web component is connected to the DOM.
/// This is when you should do any setup like attaching a ShadowDom
/// or appending elements.
fn connected_mut(&mut self, _element: &HtmlElement) {
// noop
}
/// Called when the web component is disconnected from the DOM.
fn disconnected(&self, _element: &HtmlElement) {
// noop
}
/// Called when the web component is disconnected from the DOM.
fn disconnected_mut(&mut self, _element: &HtmlElement) {
// noop
}
/// Called When the web component is moved to a new document.
fn adopted(&self, _element: &HtmlElement) {
// noop
}
/// Called When the web component is moved to a new document.
fn adopted_mut(&mut self, _element: &HtmlElement) {
// noop
}
/// Called when one of the observed attributes has changed.
/// the observedc attributes are listed in the observed_attrs argument to the
/// `#[web_component(observed_attrs = "['attr1', 'attr2']")` attribute.
@ -172,10 +220,28 @@ pub trait WebComponentBinding: WebComponentDef {
// noop
}
/// Top level event handler for this custome element.
/// Called when one of the observed attributes has changed.
/// the observedc attributes are listed in the observed_attrs argument to the
/// `#[web_component(observed_attrs = "['attr1', 'attr2']")` attribute.
fn attribute_changed_mut(
&mut self,
_element: &HtmlElement,
_name: JsValue,
_old_value: JsValue,
_new_value: JsValue,
) {
// noop
}
/// Top level event handler for this custom element.
fn handle_event(&self, _element: &HtmlElement, _event: &Event) {
// noop
}
/// Top level event handler for this custom element.
fn handle_event_mut(&mut self, _element: &HtmlElement, _event: &Event) {
// noop
}
}
/// Marker trait used in the generated shims to assert that there are Rust implemtntations
@ -299,7 +365,7 @@ mod tests {
#[web_component(
class_name = "MyElement",
element_name = "my-element",
observed_attrs = "['class']"
observed_attrs = "['class']",
)]
pub struct MyElementImpl {}
@ -378,9 +444,96 @@ mod tests {
"Added a text node on adopt"
);
}
// Then we can have the new document adopt this node.
}
#[wasm_bindgen_test]
fn test_component_mut() {
#[web_component(
class_name = "MyElementMut",
element_name = "my-element-mut",
observed_attrs = "['class']",
)]
pub struct MyElementMutImpl {}
impl WebComponentBinding for MyElementMutImpl {
fn connected_mut(&mut self, element: &HtmlElement) {
let node = Text::new().unwrap();
node.set_text_content(Some("Added a text node on connect".into()));
element.append_child(&node).unwrap();
}
fn disconnected_mut(&mut self, element: &HtmlElement) {
let node = element.first_child().unwrap();
element.remove_child(&node).unwrap();
}
fn adopted_mut(&mut self, element: &HtmlElement) {
let node = Text::new().unwrap();
node.set_text_content(Some("Added a text node on adopt".into()));
element.append_child(&node).unwrap();
}
fn attribute_changed_mut(
&mut self,
element: &HtmlElement,
name: JsValue,
old_value: JsValue,
new_value: JsValue,
) {
let node = element.first_child().unwrap();
node.set_text_content(Some(&format!(
"Setting {} from {} to {}",
name.as_string().unwrap_or("None".to_owned()),
old_value.as_string().unwrap_or("None".to_owned()),
new_value.as_string().unwrap_or("None".to_owned()),
)));
element.append_child(&node).unwrap();
}
}
let obj = MyElementMutImpl::define().expect("Failed to define web component");
let fun = obj.element_constructor.dyn_ref::<Function>().unwrap();
assert_eq!(fun.name(), MyElementMutImpl::class_name());
let element = MyElementMutImpl::create();
assert_eq!(
element.tag_name().to_uppercase(),
MyElementMutImpl::element_name().to_uppercase()
);
let document = window().unwrap().document().unwrap();
let body = document.body().unwrap();
// Test the connected callback
body.append_child(&element).unwrap();
assert_eq!(
element.text_content().unwrap(),
"Added a text node on connect"
);
// Test the disconnected callback
body.remove_child(&element).unwrap();
assert_eq!(element.text_content().unwrap(), "");
body.append_child(&element).unwrap();
element.set_attribute("class", "foo").unwrap();
assert_eq!(
element.text_content().unwrap(),
"Setting class from None to foo"
);
// NOTE(jwall): If we are running headless then this can fail sometimes.
// We don't fail the test when that happens.
if let Ok(Some(new_window)) = window().unwrap().open() {
// Test the adopted callback
// First we need a new window with a new document to perform the adoption with.
new_window.document().unwrap().adopt_node(&element).unwrap();
assert_eq!(
element.text_content().unwrap(),
"Added a text node on adopt"
);
} else {
assert!(false);
}
}
#[wasm_bindgen_test]
fn test_component_no_element_name() {
#[web_component(class_name = "AnElement")]
@ -410,6 +563,8 @@ mod tests {
assert_eq!(ThisElement::element_name(), "this-old-element");
}
// TODO(jwall): Tests for event handling
// TODO(jwall): Benchmarks for TemplateElements?
#[cfg(feature = "HtmlTemplateElement")]
#[wasm_bindgen_test]