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

View File

@ -4,16 +4,29 @@ extern crate rocket;
extern crate typed_html;
extern crate typed_html_macros;
use rocket::http::ContentType;
use rocket::response::Content;
use rocket::{get, routes};
use typed_html::text;
use rocket::http::{ContentType, Status};
use rocket::response::{Responder, Result};
use rocket::{get, routes, Request, Response};
use std::io::Cursor;
use typed_html::types::LinkType;
use typed_html::{dom::Node, text};
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("/")]
fn index() -> Content<String> {
Content(ContentType::HTML, html!(
fn index() -> Html {
Html(html!(
<html>
<head>
<title>"Hello Kitty!"</title>
@ -34,7 +47,7 @@ fn index() -> Content<String> {
<button onclick="alert('She is not a cat.')">"Click me!"</button>
</body>
</html>
).to_string())
))
}
fn main() {

View File

@ -5,7 +5,7 @@
extern crate typed_html;
extern crate typed_html_macros;
use typed_html::dom::Node;
use typed_html::dom::TextNode;
use typed_html::types::*;
use typed_html_macros::html;
@ -14,7 +14,7 @@ struct Foo {
}
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 wibble = Foo { foo: "welp" };
let doc = html!(

View File

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

View File

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

View File

@ -1,16 +1,30 @@
//! Event handlers.
use std::marker::PhantomData;
use stdweb::web::event::*;
use stdweb::web::{Element, EventListenerHandle, IEventTarget};
use super::{OutputType, DOM};
macro_rules! declare_events {
($($name:ident : $type:ty ,)*) => {
#[derive(Default)]
pub struct Events {
/// Container type for DOM 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_rules! for_events {
($event:ident in $events:expr => $body:block) => {
@ -94,7 +108,7 @@ declare_events! {
}
/// Trait for event handlers.
pub trait EventHandler<EventType> {
pub trait EventHandler<T: OutputType, E> {
/// Build a callback function from this event handler.
///
/// 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>;
}
pub trait IntoEventHandler<E> {
fn into_event_handler(self) -> Box<dyn EventHandler<E>>;
/// Trait for building event handlers from other types.
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>);
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
F: FnMut(E) + '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)
}
}
impl<F, E> IntoEventHandler<E> for F
impl<F, E> IntoEventHandler<DOM, E> for F
where
F: FnMut(E) + '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))
}
}
impl<F, E> EventHandler<E> for EFn<F, E>
impl<F, E> EventHandler<DOM, E> for EFn<F, E>
where
F: FnMut(E) + 'static,
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 {
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 {
fn into_event_handler(self) -> Box<dyn EventHandler<E>> {
impl<E> IntoEventHandler<String, E> for &'static str {
fn into_event_handler(self) -> Box<dyn EventHandler<String, E>> {
Box::new(self)
}
}

View File

@ -17,3 +17,13 @@ pub mod dom;
pub mod elements;
pub mod events;
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::events::Events;
use typed_html::for_events;
use typed_html::DOM;
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 => {
handler.attach(target);
});
@ -19,7 +20,7 @@ fn install_handlers(target: &Element, handlers: &mut Events) {
fn build(
document: &web::Document,
vnode: VNode,
vnode: VNode<'_, DOM>,
) -> Result<web::Node, web::error::InvalidCharacterError> {
match vnode {
VNode::Text(text) => Ok(document.create_text_node(&text).into()),