Parameterise nodes etc on output type, so we can type event handlers based on it.

With this, Node<String> only accepts event handlers implemented
for String, etc. No danger of trying to stringify functions and vice versa.
This commit is contained in:
Bodil Stokke 2018-11-16 22:55:25 +00:00
parent 2b95530637
commit 001a7ba016
8 changed files with 120 additions and 74 deletions

View File

@ -91,19 +91,20 @@ impl Declare {
let mut body = TokenStream::new(); let mut body = TokenStream::new();
for (child_name, child_type, _) in self.req_children() { for (child_name, child_type, _) in self.req_children() {
body.extend(quote!( pub $child_name: Box<$child_type>, )); body.extend(quote!( pub $child_name: Box<$child_type<T>>, ));
} }
if let Some(child_constraint) = &self.opt_children { if let Some(child_constraint) = &self.opt_children {
let child_constraint = child_constraint.clone(); let child_constraint = child_constraint.clone();
body.extend(quote!(pub children: Vec<Box<$child_constraint>>,)); body.extend(quote!(pub children: Vec<Box<$child_constraint<T>>>,));
} }
quote!( quote!(
pub struct $elem_name { pub struct $elem_name<T> where T: ::OutputType {
phantom_output: std::marker::PhantomData<T>,
pub attrs: $attr_type_name, pub attrs: $attr_type_name,
pub data_attributes: Vec<(&'static str, String)>, pub data_attributes: Vec<(&'static str, String)>,
pub events: ::events::Events, pub events: ::events::Events<T>,
$body $body
} }
) )
@ -115,7 +116,7 @@ impl Declare {
let mut args = TokenStream::new(); let mut args = TokenStream::new();
for (child_name, child_type, _) in self.req_children() { for (child_name, child_type, _) in self.req_children() {
args.extend(quote!( $child_name: Box<$child_type>, )); args.extend(quote!( $child_name: Box<$child_type<T>>, ));
} }
let mut attrs = TokenStream::new(); let mut attrs = TokenStream::new();
@ -137,9 +138,10 @@ impl Declare {
} }
quote!( quote!(
impl $elem_name { impl<T> $elem_name<T> where T: ::OutputType {
pub fn new($args) -> Self { pub fn new($args) -> Self {
$elem_name { $elem_name {
phantom_output: std::marker::PhantomData,
events: ::events::Events::default(), events: ::events::Events::default(),
$body $body
} }
@ -194,8 +196,8 @@ impl Declare {
let elem_name = self.elem_name(); let elem_name = self.elem_name();
let vnode = self.impl_vnode(); let vnode = self.impl_vnode();
quote!( quote!(
impl ::dom::Node for $elem_name { impl<T> ::dom::Node<T> for $elem_name<T> where T: ::OutputType {
fn vnode<'a>(&'a mut self) -> ::dom::VNode<'a> { fn vnode(&'_ mut self) -> ::dom::VNode<'_, T> {
$vnode $vnode
} }
} }
@ -222,7 +224,7 @@ impl Declare {
} }
quote!( quote!(
impl ::dom::Element for $elem_name { impl<T> ::dom::Element<T> for $elem_name<T> where T: ::OutputType {
fn name() -> &'static str { fn name() -> &'static str {
$name $name
} }
@ -253,7 +255,7 @@ impl Declare {
for t in &self.traits { for t in &self.traits {
let name = t.clone(); let name = t.clone();
body.extend(quote!( body.extend(quote!(
impl $name for $elem_name {} impl<T> $name<T> for $elem_name<T> where T: ::OutputType {}
)); ));
} }
body body
@ -316,13 +318,13 @@ impl Declare {
print_events.extend(quote!( print_events.extend(quote!(
if let Some(ref value) = self.events.$event_name { if let Some(ref value) = self.events.$event_name {
write!(f, " on{}=\"{}\"", $event_str, write!(f, " on{}=\"{}\"", $event_str,
::htmlescape::encode_attribute(&value.render().unwrap()))?; ::htmlescape::encode_attribute(value.render().unwrap().as_str()))?;
} }
)); ));
} }
quote!( quote!(
impl std::fmt::Display for $elem_name { impl<T> std::fmt::Display for $elem_name<T> where T: ::OutputType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "<{}", $name)?; write!(f, "<{}", $name)?;
$print_attrs $print_attrs

View File

@ -4,16 +4,29 @@ extern crate rocket;
extern crate typed_html; extern crate typed_html;
extern crate typed_html_macros; extern crate typed_html_macros;
use rocket::http::ContentType; use rocket::http::{ContentType, Status};
use rocket::response::Content; use rocket::response::{Responder, Result};
use rocket::{get, routes}; use rocket::{get, routes, Request, Response};
use typed_html::text; use std::io::Cursor;
use typed_html::types::LinkType; use typed_html::types::LinkType;
use typed_html::{dom::Node, text};
use typed_html_macros::html; use typed_html_macros::html;
struct Html(Box<Node<String>>);
impl<'r> Responder<'r> for Html {
fn respond_to(self, _request: &Request) -> Result<'r> {
Ok(Response::build()
.status(Status::Ok)
.header(ContentType::HTML)
.sized_body(Cursor::new(self.0.to_string()))
.finalize())
}
}
#[get("/")] #[get("/")]
fn index() -> Content<String> { fn index() -> Html {
Content(ContentType::HTML, html!( Html(html!(
<html> <html>
<head> <head>
<title>"Hello Kitty!"</title> <title>"Hello Kitty!"</title>
@ -34,7 +47,7 @@ fn index() -> Content<String> {
<button onclick="alert('She is not a cat.')">"Click me!"</button> <button onclick="alert('She is not a cat.')">"Click me!"</button>
</body> </body>
</html> </html>
).to_string()) ))
} }
fn main() { fn main() {

View File

@ -5,7 +5,7 @@
extern crate typed_html; extern crate typed_html;
extern crate typed_html_macros; extern crate typed_html_macros;
use typed_html::dom::Node; use typed_html::dom::TextNode;
use typed_html::types::*; use typed_html::types::*;
use typed_html_macros::html; use typed_html_macros::html;
@ -14,7 +14,7 @@ struct Foo {
} }
fn main() { fn main() {
let the_big_question = text!("How does she eat?"); let the_big_question: Box<TextNode<String>> = text!("How does she eat?");
let splain_class = "well-actually"; let splain_class = "well-actually";
let wibble = Foo { foo: "welp" }; let wibble = Foo { foo: "welp" };
let doc = html!( let doc = html!(

View File

@ -1,7 +1,9 @@
//! DOM and virtual DOM types. //! DOM and virtual DOM types.
use std::fmt::Display; use std::fmt::Display;
use std::marker::PhantomData;
use super::OutputType;
use elements::{FlowContent, PhrasingContent}; use elements::{FlowContent, PhrasingContent};
use events::Events; use events::Events;
use htmlescape::encode_minimal; use htmlescape::encode_minimal;
@ -21,17 +23,17 @@ use htmlescape::encode_minimal;
/// ``` /// ```
/// ///
/// [Node]: trait.Node.html /// [Node]: trait.Node.html
pub enum VNode<'a> { pub enum VNode<'a, T: OutputType> {
Text(&'a str), Text(&'a str),
Element(VElement<'a>), Element(VElement<'a, T>),
} }
/// An untyped representation of an HTML element. /// An untyped representation of an HTML element.
pub struct VElement<'a> { pub struct VElement<'a, T: OutputType> {
pub name: &'static str, pub name: &'static str,
pub attributes: Vec<(&'static str, String)>, pub attributes: Vec<(&'static str, String)>,
pub events: &'a mut Events, pub events: &'a mut Events<T>,
pub children: Vec<VNode<'a>>, pub children: Vec<VNode<'a, T>>,
} }
/// Trait for rendering a typed HTML node. /// Trait for rendering a typed HTML node.
@ -46,11 +48,11 @@ pub struct VElement<'a> {
/// [TextNode]: struct.TextNode.html /// [TextNode]: struct.TextNode.html
/// [elements]: ../elements/index.html /// [elements]: ../elements/index.html
/// [vnode]: #tymethod.vnode /// [vnode]: #tymethod.vnode
pub trait Node: Display { pub trait Node<T: OutputType>: Display {
/// Render the node into a [`VNode`][VNode] tree. /// Render the node into a [`VNode`][VNode] tree.
/// ///
/// [VNode]: enum.VNode.html /// [VNode]: enum.VNode.html
fn vnode<'a>(&'a mut self) -> VNode<'a>; fn vnode<'a>(&'a mut self) -> VNode<'a, T>;
} }
/// Trait for querying a typed HTML element. /// Trait for querying a typed HTML element.
@ -58,7 +60,7 @@ pub trait Node: Display {
/// All [HTML elements][elements] implement this. /// All [HTML elements][elements] implement this.
/// ///
/// [elements]: ../elements/index.html /// [elements]: ../elements/index.html
pub trait Element: Node { pub trait Element<T: OutputType>: Node<T> {
/// Get the name of the element. /// Get the name of the element.
fn name() -> &'static str; fn name() -> &'static str;
/// Get a list of the attribute names for this element. /// Get a list of the attribute names for this element.
@ -80,7 +82,7 @@ pub trait Element: Node {
} }
/// An HTML text node. /// An HTML text node.
pub struct TextNode(String); pub struct TextNode<T: OutputType>(String, PhantomData<T>);
/// Macro for creating text nodes. /// Macro for creating text nodes.
/// ///
@ -112,7 +114,7 @@ macro_rules! text {
}; };
} }
impl TextNode { impl<T: OutputType> TextNode<T> {
/// Construct a text node. /// Construct a text node.
/// ///
/// The preferred way to construct a text node is with the [`text!()`][text] /// The preferred way to construct a text node is with the [`text!()`][text]
@ -120,39 +122,39 @@ impl TextNode {
/// ///
/// [text]: ../macro.text.html /// [text]: ../macro.text.html
pub fn new<S: Into<String>>(s: S) -> Self { pub fn new<S: Into<String>>(s: S) -> Self {
TextNode(s.into()) TextNode(s.into(), PhantomData)
} }
} }
impl Display for TextNode { impl<T: OutputType> Display for TextNode<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
f.write_str(&encode_minimal(&self.0)) f.write_str(&encode_minimal(&self.0))
} }
} }
impl Node for TextNode { impl<T: OutputType> Node<T> for TextNode<T> {
fn vnode<'a>(&'a mut self) -> VNode<'a> { fn vnode(&'_ mut self) -> VNode<'_, T> {
VNode::Text(&self.0) VNode::Text(&self.0)
} }
} }
impl IntoIterator for TextNode { impl<T: OutputType> IntoIterator for TextNode<T> {
type Item = TextNode; type Item = TextNode<T>;
type IntoIter = std::vec::IntoIter<TextNode>; type IntoIter = std::vec::IntoIter<TextNode<T>>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
vec![self].into_iter() vec![self].into_iter()
} }
} }
impl IntoIterator for Box<TextNode> { impl<T: OutputType> IntoIterator for Box<TextNode<T>> {
type Item = Box<TextNode>; type Item = Box<TextNode<T>>;
type IntoIter = std::vec::IntoIter<Box<TextNode>>; type IntoIter = std::vec::IntoIter<Box<TextNode<T>>>;
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
vec![self].into_iter() vec![self].into_iter()
} }
} }
impl FlowContent for TextNode {} impl<T: OutputType> FlowContent<T> for TextNode<T> {}
impl PhrasingContent for TextNode {} impl<T: OutputType> PhrasingContent<T> for TextNode<T> {}

View File

@ -2,29 +2,30 @@
use typed_html_macros::declare_elements; use typed_html_macros::declare_elements;
use super::OutputType;
use dom::{Node, TextNode}; use dom::{Node, TextNode};
use types::*; use types::*;
// Marker traits for element content groups // Marker traits for element content groups
pub trait MetadataContent: Node {} pub trait MetadataContent<T: OutputType>: Node<T> {}
pub trait FlowContent: Node {} pub trait FlowContent<T: OutputType>: Node<T> {}
pub trait SectioningContent: Node {} pub trait SectioningContent<T: OutputType>: Node<T> {}
pub trait HeadingContent: Node {} pub trait HeadingContent<T: OutputType>: Node<T> {}
// Phrasing content seems to be entirely a subclass of FlowContent // Phrasing content seems to be entirely a subclass of FlowContent
pub trait PhrasingContent: FlowContent {} pub trait PhrasingContent<T: OutputType>: FlowContent<T> {}
pub trait EmbeddedContent: Node {} pub trait EmbeddedContent<T: OutputType>: Node<T> {}
pub trait InteractiveContent: Node {} pub trait InteractiveContent<T: OutputType>: Node<T> {}
pub trait FormContent: Node {} pub trait FormContent<T: OutputType>: Node<T> {}
// Traits for elements that are more picky about their children // Traits for elements that are more picky about their children
pub trait DescriptionListContent: Node {} pub trait DescriptionListContent<T: OutputType>: Node<T> {}
pub trait HGroupContent: Node {} pub trait HGroupContent<T: OutputType>: Node<T> {}
pub trait MapContent: Node {} pub trait MapContent<T: OutputType>: Node<T> {}
pub trait MediaContent: Node {} // <audio> and <video> pub trait MediaContent<T: OutputType>: Node<T> {} // <audio> and <video>
pub trait SelectContent: Node {} pub trait SelectContent<T: OutputType>: Node<T> {}
pub trait TableContent: Node {} pub trait TableContent<T: OutputType>: Node<T> {}
pub trait TableColumnContent: Node {} pub trait TableColumnContent<T: OutputType>: Node<T> {}
declare_elements!{ declare_elements!{
html { html {

View File

@ -1,16 +1,30 @@
//! Event handlers.
use std::marker::PhantomData; use std::marker::PhantomData;
use stdweb::web::event::*; use stdweb::web::event::*;
use stdweb::web::{Element, EventListenerHandle, IEventTarget}; use stdweb::web::{Element, EventListenerHandle, IEventTarget};
use super::{OutputType, DOM};
macro_rules! declare_events { macro_rules! declare_events {
($($name:ident : $type:ty ,)*) => { ($($name:ident : $type:ty ,)*) => {
#[derive(Default)] /// Container type for DOM events.
pub struct Events { pub struct Events<T: OutputType> {
$( $(
pub $name: Option<Box<dyn EventHandler<$type>>>, pub $name: Option<Box<dyn EventHandler<T, $type>>>,
)* )*
} }
impl<T: OutputType> Default for Events<T> {
fn default() -> Self {
Events {
$(
$name: None,
)*
}
}
}
#[macro_export] #[macro_export]
macro_rules! for_events { macro_rules! for_events {
($event:ident in $events:expr => $body:block) => { ($event:ident in $events:expr => $body:block) => {
@ -94,7 +108,7 @@ declare_events! {
} }
/// Trait for event handlers. /// Trait for event handlers.
pub trait EventHandler<EventType> { pub trait EventHandler<T: OutputType, E> {
/// Build a callback function from this event handler. /// Build a callback function from this event handler.
/// ///
/// Returns `None` is this event handler can't be used to build a callback /// Returns `None` is this event handler can't be used to build a callback
@ -112,10 +126,13 @@ pub trait EventHandler<EventType> {
fn render(&self) -> Option<String>; fn render(&self) -> Option<String>;
} }
pub trait IntoEventHandler<E> { /// Trait for building event handlers from other types.
fn into_event_handler(self) -> Box<dyn EventHandler<E>>; pub trait IntoEventHandler<T: OutputType, E> {
/// Construct an event handler from an instance of the source type.
fn into_event_handler(self) -> Box<dyn EventHandler<T, E>>;
} }
/// Wrapper type for closures as event handlers.
pub struct EFn<F, E>(Option<F>, PhantomData<E>); pub struct EFn<F, E>(Option<F>, PhantomData<E>);
impl<F, E> EFn<F, E> impl<F, E> EFn<F, E>
@ -128,27 +145,27 @@ where
} }
} }
impl<F, E> IntoEventHandler<E> for EFn<F, E> impl<F, E> IntoEventHandler<DOM, E> for EFn<F, E>
where where
F: FnMut(E) + 'static, F: FnMut(E) + 'static,
E: ConcreteEvent + 'static, E: ConcreteEvent + 'static,
{ {
fn into_event_handler(self) -> Box<dyn EventHandler<E>> { fn into_event_handler(self) -> Box<dyn EventHandler<DOM, E>> {
Box::new(self) Box::new(self)
} }
} }
impl<F, E> IntoEventHandler<E> for F impl<F, E> IntoEventHandler<DOM, E> for F
where where
F: FnMut(E) + 'static, F: FnMut(E) + 'static,
E: ConcreteEvent + 'static, E: ConcreteEvent + 'static,
{ {
fn into_event_handler(self) -> Box<dyn EventHandler<E>> { fn into_event_handler(self) -> Box<dyn EventHandler<DOM, E>> {
Box::new(EFn::new(self)) Box::new(EFn::new(self))
} }
} }
impl<F, E> EventHandler<E> for EFn<F, E> impl<F, E> EventHandler<DOM, E> for EFn<F, E>
where where
F: FnMut(E) + 'static, F: FnMut(E) + 'static,
E: ConcreteEvent, E: ConcreteEvent,
@ -163,7 +180,7 @@ where
} }
} }
impl<E> EventHandler<E> for &'static str { impl<E> EventHandler<String, E> for &'static str {
fn attach(&mut self, _target: &Element) -> EventListenerHandle { fn attach(&mut self, _target: &Element) -> EventListenerHandle {
panic!("Silly wabbit, strings as event handlers are only for printing."); panic!("Silly wabbit, strings as event handlers are only for printing.");
} }
@ -173,8 +190,8 @@ impl<E> EventHandler<E> for &'static str {
} }
} }
impl<E> IntoEventHandler<E> for &'static str { impl<E> IntoEventHandler<String, E> for &'static str {
fn into_event_handler(self) -> Box<dyn EventHandler<E>> { fn into_event_handler(self) -> Box<dyn EventHandler<String, E>> {
Box::new(self) Box::new(self)
} }
} }

View File

@ -17,3 +17,13 @@ pub mod dom;
pub mod elements; pub mod elements;
pub mod events; pub mod events;
pub mod types; pub mod types;
/// Marker trait for outputs
pub trait OutputType {}
/// String output
impl OutputType for String {}
/// DOM output
pub struct DOM;
impl OutputType for DOM {}

View File

@ -9,9 +9,10 @@ use stdweb::web::{self, Element, IElement, INode};
use typed_html::dom::{Node, VNode}; use typed_html::dom::{Node, VNode};
use typed_html::events::Events; use typed_html::events::Events;
use typed_html::for_events; use typed_html::for_events;
use typed_html::DOM;
use typed_html_macros::html; use typed_html_macros::html;
fn install_handlers(target: &Element, handlers: &mut Events) { fn install_handlers(target: &Element, handlers: &mut Events<DOM>) {
for_events!(handler in handlers => { for_events!(handler in handlers => {
handler.attach(target); handler.attach(target);
}); });
@ -19,7 +20,7 @@ fn install_handlers(target: &Element, handlers: &mut Events) {
fn build( fn build(
document: &web::Document, document: &web::Document,
vnode: VNode, vnode: VNode<'_, DOM>,
) -> Result<web::Node, web::error::InvalidCharacterError> { ) -> Result<web::Node, web::error::InvalidCharacterError> {
match vnode { match vnode {
VNode::Text(text) => Ok(document.create_text_node(&text).into()), VNode::Text(text) => Ok(document.create_text_node(&text).into()),