Docs and cleanups.

This commit is contained in:
Bodil Stokke 2018-11-17 14:19:37 +00:00
parent 001a7ba016
commit 28513b93e9
12 changed files with 355 additions and 307 deletions

View File

@ -9,10 +9,9 @@ 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;
use typed_html::{dom::DOMTree, html, text};
struct Html(Box<Node<String>>);
struct Html(DOMTree<String>);
impl<'r> Responder<'r> for Html {
fn respond_to(self, _request: &Request) -> Result<'r> {

View File

@ -9,7 +9,6 @@ strum = "0.11.0"
strum_macros = "0.11.0"
mime = "0.3.12"
language-tags = "0.2.2"
enumset = "0.3.12"
http = "0.1.13"
htmlescape = "0.3.1"
stdweb = "0.4.10"

View File

@ -3,11 +3,10 @@
#[macro_use]
extern crate typed_html;
extern crate typed_html_macros;
use typed_html::dom::TextNode;
use typed_html::html;
use typed_html::types::*;
use typed_html_macros::html;
struct Foo {
foo: &'static str,

View File

@ -8,6 +8,26 @@ use elements::{FlowContent, PhrasingContent};
use events::Events;
use htmlescape::encode_minimal;
/// A boxed DOM tree, as returned from the `html!` macro.
///
/// # Examples
///
/// ```
/// # #![feature(proc_macro_hygiene)]
/// # extern crate typed_html;
/// # use typed_html::html;
/// # use typed_html::dom::DOMTree;
/// # fn main() {
/// let tree: DOMTree<String> = html!(
/// <div class="hello">
/// <p>"Hello Joe!"</p>
/// </div>
/// );
/// let rendered_tree: String = tree.to_string();
/// # }
/// ```
pub type DOMTree<T> = Box<Node<T>>;
/// An untyped representation of an HTML node.
///
/// This structure is designed to be easily walked in order to render a DOM tree
@ -52,7 +72,7 @@ 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, T>;
fn vnode(&mut self) -> VNode<T>;
}
/// Trait for querying a typed HTML element.

View File

@ -25,6 +25,26 @@ macro_rules! declare_events {
}
}
/// Iterate over the defined events on a DOM object.
///
/// # Examples
///
/// ```
/// # #![feature(proc_macro_hygiene)]
/// # extern crate typed_html;
/// # use typed_html::{html, for_events};
/// # use typed_html::dom::{DOMTree, VNode};
/// # fn main() {
/// let mut doc: DOMTree<String> = html!(
/// <button onclick="alert('clicked!')"/>
/// );
/// if let VNode::Element(element) = doc.vnode() {
/// for_events!(event in element.events => {
/// assert_eq!("alert('clicked!')", event.render().unwrap());
/// });
/// }
/// # }
/// ```
#[macro_export]
macro_rules! for_events {
($event:ident in $events:expr => $body:block) => {

View File

@ -1,7 +1,5 @@
#![feature(try_from)]
#[macro_use]
extern crate enumset;
#[macro_use]
extern crate strum_macros;
@ -13,6 +11,8 @@ extern crate stdweb;
extern crate strum;
extern crate typed_html_macros;
pub use typed_html_macros::html;
pub mod dom;
pub mod elements;
pub mod events;

View File

@ -5,13 +5,22 @@ use std::str::FromStr;
use super::Id;
/// A valid CSS class.
///
/// A CSS class is a non-empty string that starts with an alphanumeric character
/// and is followed by any number of alphanumeric characters and the
/// `_`, `-` and `.` characters.
///
/// See also [`Id`][Id].
///
/// [Id]: struct.Id.html
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Class(String);
impl Class {
// Construct a new class name from a string.
//
// Returns `None` if the provided string is invalid.
/// Construct a new class name from a string.
///
/// Returns `Err` if the provided string is invalid.
pub fn try_new<S: Into<String>>(id: S) -> Result<Self, &'static str> {
let id = id.into();
{
@ -34,9 +43,9 @@ impl Class {
Ok(Class(id))
}
// Construct a new class name from a string.
//
// Panics if the provided string is invalid.
/// Construct a new class name from a string.
///
/// Panics if the provided string is invalid.
pub fn new<S: Into<String>>(id: S) -> Self {
let id = id.into();
Self::try_new(id.clone()).unwrap_or_else(|err| {

View File

@ -5,13 +5,22 @@ use std::str::FromStr;
use super::Class;
/// A valid HTML ID.
///
/// An ID is a non-empty string that starts with an alphanumeric character
/// and is followed by any number of alphanumeric characters and the
/// `_`, `-` and `.` characters.
///
/// See also [`Class`][Class].
///
/// [Class]: struct.Class.html
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Id(String);
impl Id {
// Construct a new ID from a string.
//
// Returns `None` if the provided string is invalid.
/// Construct a new ID from a string.
///
/// Returns `Err` if the provided string is invalid.
pub fn try_new<S: Into<String>>(id: S) -> Result<Self, &'static str> {
let id = id.into();
{
@ -32,9 +41,9 @@ impl Id {
Ok(Id(id))
}
// Construct a new ID from a string.
//
// Panics if the provided string is invalid.
/// Construct a new ID from a string.
///
/// Panics if the provided string is invalid.
pub fn new<S: Into<String>>(id: S) -> Self {
let id = id.into();
Self::try_new(id.clone()).unwrap_or_else(|err| {

View File

@ -25,320 +25,284 @@ pub type Integrity = String;
pub type Nonce = String;
pub type Target = String;
enum_set_type! {
#[derive(EnumString, Display)]
pub enum AreaShape {
#[strum(to_string = "rect")]
Rectangle,
#[strum(to_string = "circle")]
Circle,
#[strum(to_string = "poly")]
Polygon,
#[strum(to_string = "default")]
Default,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum AreaShape {
#[strum(to_string = "rect")]
Rectangle,
#[strum(to_string = "circle")]
Circle,
#[strum(to_string = "poly")]
Polygon,
#[strum(to_string = "default")]
Default,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum BoolOrDefault {
#[strum(to_string = "true")]
True,
#[strum(to_string = "default")]
Default,
#[strum(to_string = "false")]
False,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum BoolOrDefault {
#[strum(to_string = "true")]
True,
#[strum(to_string = "default")]
Default,
#[strum(to_string = "false")]
False,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum ButtonType {
#[strum(to_string = "submit")]
Submit,
#[strum(to_string = "reset")]
Reset,
#[strum(to_string = "button")]
Button,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum ButtonType {
#[strum(to_string = "submit")]
Submit,
#[strum(to_string = "reset")]
Reset,
#[strum(to_string = "button")]
Button,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum CrossOrigin {
#[strum(to_string = "anonymous")]
Anonymous,
#[strum(to_string = "use-credentials")]
UseCredentials,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum CrossOrigin {
#[strum(to_string = "anonymous")]
Anonymous,
#[strum(to_string = "use-credentials")]
UseCredentials,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum FormEncodingType {
#[strum(to_string = "application/x-www-form-urlencoded")]
UrlEncoded,
#[strum(to_string = "multipart/form-data")]
FormData,
#[strum(to_string = "text/plain")]
Text,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum FormEncodingType {
#[strum(to_string = "application/x-www-form-urlencoded")]
UrlEncoded,
#[strum(to_string = "multipart/form-data")]
FormData,
#[strum(to_string = "text/plain")]
Text,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum FormMethod {
#[strum(to_string = "post")]
Post,
#[strum(to_string = "get")]
Get,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum FormMethod {
#[strum(to_string = "post")]
Post,
#[strum(to_string = "get")]
Get,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum ImageDecoding {
#[strum(to_string = "sync")]
Sync,
#[strum(to_string = "async")]
Async,
#[strum(to_string = "auto")]
Auto,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum ImageDecoding {
#[strum(to_string = "sync")]
Sync,
#[strum(to_string = "async")]
Async,
#[strum(to_string = "auto")]
Auto,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum InputType {
#[strum(to_string = "button")]
Button,
#[strum(to_string = "checkbox")]
Checkbox,
#[strum(to_string = "color")]
Color,
#[strum(to_string = "date")]
Date,
#[strum(to_string = "datetime-local")]
DatetimeLocal,
#[strum(to_string = "email")]
Email,
#[strum(to_string = "file")]
File,
#[strum(to_string = "hidden")]
Hidden,
#[strum(to_string = "image")]
Image,
#[strum(to_string = "month")]
Month,
#[strum(to_string = "number")]
Number,
#[strum(to_string = "password")]
Password,
#[strum(to_string = "radio")]
Radio,
#[strum(to_string = "range")]
Range,
#[strum(to_string = "reset")]
Reset,
#[strum(to_string = "search")]
Search,
#[strum(to_string = "submit")]
Submit,
#[strum(to_string = "tel")]
Tel,
#[strum(to_string = "text")]
Text,
#[strum(to_string = "time")]
Time,
#[strum(to_string = "url")]
Url,
#[strum(to_string = "week")]
Week,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum InputType {
#[strum(to_string = "button")]
Button,
#[strum(to_string = "checkbox")]
Checkbox,
#[strum(to_string = "color")]
Color,
#[strum(to_string = "date")]
Date,
#[strum(to_string = "datetime-local")]
DatetimeLocal,
#[strum(to_string = "email")]
Email,
#[strum(to_string = "file")]
File,
#[strum(to_string = "hidden")]
Hidden,
#[strum(to_string = "image")]
Image,
#[strum(to_string = "month")]
Month,
#[strum(to_string = "number")]
Number,
#[strum(to_string = "password")]
Password,
#[strum(to_string = "radio")]
Radio,
#[strum(to_string = "range")]
Range,
#[strum(to_string = "reset")]
Reset,
#[strum(to_string = "search")]
Search,
#[strum(to_string = "submit")]
Submit,
#[strum(to_string = "tel")]
Tel,
#[strum(to_string = "text")]
Text,
#[strum(to_string = "time")]
Time,
#[strum(to_string = "url")]
Url,
#[strum(to_string = "week")]
Week,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum LinkType {
#[strum(to_string = "alternate")]
Alternate,
#[strum(to_string = "author")]
Author,
#[strum(to_string = "bookmark")]
Bookmark,
#[strum(to_string = "canonical")]
Canonical,
#[strum(to_string = "external")]
External,
#[strum(to_string = "help")]
Help,
#[strum(to_string = "icon")]
Icon,
#[strum(to_string = "license")]
License,
#[strum(to_string = "manifest")]
Manifest,
#[strum(to_string = "modulepreload")]
ModulePreload,
#[strum(to_string = "next")]
Next,
#[strum(to_string = "nofollow")]
NoFollow,
#[strum(to_string = "noopener")]
NoOpener,
#[strum(to_string = "noreferrer")]
NoReferrer,
#[strum(to_string = "pingback")]
PingBack,
#[strum(to_string = "prefetch")]
Prefetch,
#[strum(to_string = "preload")]
Preload,
#[strum(to_string = "prev")]
Prev,
#[strum(to_string = "search")]
Search,
#[strum(to_string = "shortlink")]
ShortLink,
#[strum(to_string = "stylesheet")]
StyleSheet,
#[strum(to_string = "tag")]
Tag,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum LinkType {
#[strum(to_string = "alternate")]
Alternate,
#[strum(to_string = "author")]
Author,
#[strum(to_string = "bookmark")]
Bookmark,
#[strum(to_string = "canonical")]
Canonical,
#[strum(to_string = "external")]
External,
#[strum(to_string = "help")]
Help,
#[strum(to_string = "icon")]
Icon,
#[strum(to_string = "license")]
License,
#[strum(to_string = "manifest")]
Manifest,
#[strum(to_string = "modulepreload")]
ModulePreload,
#[strum(to_string = "next")]
Next,
#[strum(to_string = "nofollow")]
NoFollow,
#[strum(to_string = "noopener")]
NoOpener,
#[strum(to_string = "noreferrer")]
NoReferrer,
#[strum(to_string = "pingback")]
PingBack,
#[strum(to_string = "prefetch")]
Prefetch,
#[strum(to_string = "preload")]
Preload,
#[strum(to_string = "prev")]
Prev,
#[strum(to_string = "search")]
Search,
#[strum(to_string = "shortlink")]
ShortLink,
#[strum(to_string = "stylesheet")]
StyleSheet,
#[strum(to_string = "tag")]
Tag,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum OnOff {
#[strum(to_string = "on")]
On,
#[strum(to_string = "off")]
Off,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum OnOff {
#[strum(to_string = "on")]
On,
#[strum(to_string = "off")]
Off,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum OrderedListType {
#[strum(to_string = "a")]
LowerCaseLetters,
#[strum(to_string = "A")]
UpperCaseLetters,
#[strum(to_string = "i")]
LowerCaseRomanNumerals,
#[strum(to_string = "I")]
UpperCaseRomanNumerals,
#[strum(to_string = "1")]
Numbers,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum OrderedListType {
#[strum(to_string = "a")]
LowerCaseLetters,
#[strum(to_string = "A")]
UpperCaseLetters,
#[strum(to_string = "i")]
LowerCaseRomanNumerals,
#[strum(to_string = "I")]
UpperCaseRomanNumerals,
#[strum(to_string = "1")]
Numbers,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum Preload {
#[strum(to_string = "none")]
None,
#[strum(to_string = "metadata")]
Metadata,
#[strum(to_string = "auto")]
Auto,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum Preload {
#[strum(to_string = "none")]
None,
#[strum(to_string = "metadata")]
Metadata,
#[strum(to_string = "auto")]
Auto,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum ReferrerPolicy {
#[strum(to_string = "no-referrer")]
NoReferrer,
#[strum(to_string = "no-referrer-when-downgrade")]
NoReferrerWhenDowngrade,
#[strum(to_string = "origin")]
Origin,
#[strum(to_string = "origin-when-cross-origin")]
OriginWhenCrossOrigin,
#[strum(to_string = "unsafe-url")]
UnsafeUrl,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum ReferrerPolicy {
#[strum(to_string = "no-referrer")]
NoReferrer,
#[strum(to_string = "no-referrer-when-downgrade")]
NoReferrerWhenDowngrade,
#[strum(to_string = "origin")]
Origin,
#[strum(to_string = "origin-when-cross-origin")]
OriginWhenCrossOrigin,
#[strum(to_string = "unsafe-url")]
UnsafeUrl,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum Sandbox {
#[strum(to_string = "allow-forms")]
AllowForms,
#[strum(to_string = "allow-modals")]
AllowModals,
#[strum(to_string = "allow-orientation-lock")]
AllowOrientationLock,
#[strum(to_string = "allow-pointer-lock")]
AllowPointerLock,
#[strum(to_string = "allow-popups")]
AllowPopups,
#[strum(to_string = "allow-popups-to-escape-sandbox")]
AllowPopupsToEscapeSandbox,
#[strum(to_string = "allow-presentation")]
AllowPresentation,
#[strum(to_string = "allow-same-origin")]
AllowSameOrigin,
#[strum(to_string = "allow-scripts")]
AllowScripts,
#[strum(to_string = "allow-top-navigation")]
AllowTopNavigation,
#[strum(to_string = "allow-top-navigation-by-user-navigation")]
AllowTopNavigationByUserNavigation,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum Sandbox {
#[strum(to_string = "allow-forms")]
AllowForms,
#[strum(to_string = "allow-modals")]
AllowModals,
#[strum(to_string = "allow-orientation-lock")]
AllowOrientationLock,
#[strum(to_string = "allow-pointer-lock")]
AllowPointerLock,
#[strum(to_string = "allow-popups")]
AllowPopups,
#[strum(to_string = "allow-popups-to-escape-sandbox")]
AllowPopupsToEscapeSandbox,
#[strum(to_string = "allow-presentation")]
AllowPresentation,
#[strum(to_string = "allow-same-origin")]
AllowSameOrigin,
#[strum(to_string = "allow-scripts")]
AllowScripts,
#[strum(to_string = "allow-top-navigation")]
AllowTopNavigation,
#[strum(to_string = "allow-top-navigation-by-user-navigation")]
AllowTopNavigationByUserNavigation,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum TableHeaderScope {
#[strum(to_string = "row")]
Row,
#[strum(to_string = "col")]
Column,
#[strum(to_string = "rowgroup")]
RowGroup,
#[strum(to_string = "colgroup")]
ColGroup,
#[strum(to_string = "auto")]
Auto,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum TableHeaderScope {
#[strum(to_string = "row")]
Row,
#[strum(to_string = "col")]
Column,
#[strum(to_string = "rowgroup")]
RowGroup,
#[strum(to_string = "colgroup")]
ColGroup,
#[strum(to_string = "auto")]
Auto,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum TextDirection {
#[strum(to_string = "ltr")]
LeftToRight,
#[strum(to_string = "rtl")]
RightToLeft,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum TextDirection {
#[strum(to_string = "ltr")]
LeftToRight,
#[strum(to_string = "rtl")]
RightToLeft,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum VideoKind {
#[strum(to_string = "subtitles")]
Subtitles,
#[strum(to_string = "captions")]
Captions,
#[strum(to_string = "descriptions")]
Descriptions,
#[strum(to_string = "chapters")]
Chapters,
#[strum(to_string = "metadata")]
Metadata,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum VideoKind {
#[strum(to_string = "subtitles")]
Subtitles,
#[strum(to_string = "captions")]
Captions,
#[strum(to_string = "descriptions")]
Descriptions,
#[strum(to_string = "chapters")]
Chapters,
#[strum(to_string = "metadata")]
Metadata,
}
enum_set_type! {
#[derive(EnumString, Display)]
pub enum Wrap {
#[strum(to_string = "hard")]
Hard,
#[strum(to_string = "soft")]
Soft,
#[strum(to_string = "off")]
Off,
}
#[derive(EnumString, Display, PartialEq, Eq, PartialOrd, Ord, AsRefStr, AsStaticStr)]
pub enum Wrap {
#[strum(to_string = "hard")]
Hard,
#[strum(to_string = "soft")]
Soft,
#[strum(to_string = "off")]
Off,
}

View File

@ -3,10 +3,18 @@ use std::iter::FromIterator;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
/// A space separated list of values.
///
/// This type represents a list of non-unique values represented as a string of
/// values separated by spaces in HTML attributes. This is rarely used; a
/// [`SpacedSet`][SpacedSet] of unique values is much more common.
///
/// [SpacedSet]: struct.SpacedSet.html
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SpacedList<A>(Vec<A>);
impl<A> SpacedList<A> {
/// Construct an empty `SpacedList`.
pub fn new() -> Self {
SpacedList(Vec::new())
}

View File

@ -4,10 +4,33 @@ use std::iter::FromIterator;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
/// A space separated set of unique values.
///
/// This type represents a set of unique values represented as a string of
/// values separated by spaces in HTML attributes.
///
/// # Examples
///
/// ```
/// # extern crate typed_html;
/// # use std::convert::From;
/// use typed_html::types::{Class, SpacedSet};
///
/// # fn main() {
/// let classList: SpacedSet<Class> = "foo bar baz".into();
/// let classList: SpacedSet<Class> = ["foo", "bar", "baz"].into();
/// let classList: SpacedSet<Class> = ("foo", "bar", "baz").into();
///
/// let classList1: SpacedSet<Class> = "foo bar foo".into();
/// let classList2: SpacedSet<Class> = "bar foo bar".into();
/// assert_eq!(classList1, classList2);
/// # }
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SpacedSet<A: Ord>(BTreeSet<A>);
impl<A: Ord> SpacedSet<A> {
/// Construct an empty `SpacedSet`.
pub fn new() -> Self {
SpacedSet(BTreeSet::new())
}
@ -46,7 +69,7 @@ where
fn from_str(s: &str) -> Result<Self, Self::Err> {
let result: Result<Vec<A>, Self::Err> =
s.split_whitespace().map(|s| FromStr::from_str(s)).collect();
result.map(|items| Self::from_iter(items))
result.map(Self::from_iter)
}
}

View File

@ -8,9 +8,7 @@ extern crate typed_html_macros;
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;
use typed_html::{for_events, html, DOM};
fn install_handlers(target: &Element, handlers: &mut Events<DOM>) {
for_events!(handler in handlers => {