Compare commits
No commits in common. "bceb43e6d0997e857e42fea254af1dde6c117d2c" and "91139d43d3be8b5f86bf27fde84a2ecb2cc624c8" have entirely different histories.
bceb43e6d0
...
91139d43d3
15 changed files with 7 additions and 2060 deletions
30
Cargo.lock
generated
30
Cargo.lock
generated
|
@ -918,13 +918,12 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
|
|||
|
||||
[[package]]
|
||||
name = "pagetop"
|
||||
version = "0.0.4"
|
||||
version = "0.0.3"
|
||||
dependencies = [
|
||||
"actix-web",
|
||||
"colored",
|
||||
"config",
|
||||
"figlet-rs",
|
||||
"itoa",
|
||||
"pagetop-macros",
|
||||
"serde",
|
||||
"substring",
|
||||
|
@ -937,13 +936,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "pagetop-macros"
|
||||
version = "0.0.2"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"proc-macro2-diagnostics",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -1043,15 +1038,6 @@ dependencies = [
|
|||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35"
|
||||
dependencies = [
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
|
@ -1061,18 +1047,6 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2-diagnostics"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "pagetop"
|
||||
version = "0.0.4"
|
||||
version = "0.0.3"
|
||||
edition = "2021"
|
||||
|
||||
description = """\
|
||||
|
@ -18,7 +18,6 @@ authors.workspace = true
|
|||
colored = "3.0.0"
|
||||
config = { version = "0.15.11", default-features = false, features = ["toml"] }
|
||||
figlet-rs = "0.1.5"
|
||||
itoa = "1.0.15"
|
||||
serde.workspace = true
|
||||
substring = "1.4.5"
|
||||
terminal_size = "0.4.2"
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "pagetop-macros"
|
||||
version = "0.0.2"
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
|
||||
description = """\
|
||||
|
@ -18,8 +18,4 @@ authors.workspace = true
|
|||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0.95"
|
||||
proc-macro2-diagnostics = { version = "0.10.1", default-features = false }
|
||||
proc-macro-crate = "3.3.0"
|
||||
quote = "1.0.40"
|
||||
syn = { version = "2.0.104", features = ["full"] }
|
||||
|
|
|
@ -8,13 +8,6 @@
|
|||
|
||||
</div>
|
||||
|
||||
## Descripción general
|
||||
|
||||
Entre sus macros se incluye una adaptación de [maud-macros](https://crates.io/crates/maud_macros)
|
||||
([0.25.0](https://github.com/lambda-fairy/maud/tree/v0.25.0/maud_macros)) de
|
||||
[Chris Wong](https://crates.io/users/lambda-fairy) para no tener que referenciar `maud` en las
|
||||
dependencias del archivo `Cargo.toml` de cada proyecto `PageTop`.
|
||||
|
||||
## Sobre PageTop
|
||||
|
||||
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
|
||||
|
|
|
@ -14,17 +14,9 @@
|
|||
//! web clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles
|
||||
//! y configurables, basadas en HTML, CSS y JavaScript.
|
||||
|
||||
mod maud;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
|
||||
/// Macro para escribir plantillas HTML ([Maud](https://docs.rs/maud)).
|
||||
#[proc_macro]
|
||||
pub fn html(input: TokenStream) -> TokenStream {
|
||||
maud::expand(input.into()).into()
|
||||
}
|
||||
|
||||
/// Define una función `main` asíncrona como punto de entrada de `PageTop`.
|
||||
///
|
||||
/// # Ejemplos
|
||||
|
|
|
@ -1,60 +0,0 @@
|
|||
// #![doc(html_root_url = "https://docs.rs/maud_macros/0.27.0")]
|
||||
// TokenStream values are reference counted, and the mental overhead of tracking
|
||||
// lifetimes outweighs the marginal gains from explicit borrowing
|
||||
// #![allow(clippy::needless_pass_by_value)]
|
||||
|
||||
mod ast;
|
||||
mod escape;
|
||||
mod generate;
|
||||
|
||||
use ast::DiagnosticParse;
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use proc_macro2_diagnostics::Diagnostic;
|
||||
use proc_macro_crate::{crate_name, FoundCrate};
|
||||
use quote::quote;
|
||||
use syn::parse::{ParseStream, Parser};
|
||||
|
||||
pub fn expand(input: TokenStream) -> TokenStream {
|
||||
// Heuristic: the size of the resulting markup tends to correlate with the
|
||||
// code size of the template itself
|
||||
let size_hint = input.to_string().len();
|
||||
|
||||
let mut diagnostics = Vec::new();
|
||||
let markups = match Parser::parse2(
|
||||
|input: ParseStream| ast::Markups::diagnostic_parse(input, &mut diagnostics),
|
||||
input,
|
||||
) {
|
||||
Ok(data) => data,
|
||||
Err(err) => {
|
||||
let err = err.to_compile_error();
|
||||
let diag_tokens = diagnostics.into_iter().map(Diagnostic::emit_as_expr_tokens);
|
||||
|
||||
return quote! {{
|
||||
#err
|
||||
#(#diag_tokens)*
|
||||
}};
|
||||
}
|
||||
};
|
||||
|
||||
let diag_tokens = diagnostics.into_iter().map(Diagnostic::emit_as_expr_tokens);
|
||||
|
||||
let output_ident = Ident::new("__maud_output", Span::mixed_site());
|
||||
let stmts = generate::generate(markups, output_ident.clone());
|
||||
|
||||
let found_crate = crate_name("pagetop").expect("pagetop must be in Cargo.toml");
|
||||
let crate_ident = match found_crate {
|
||||
FoundCrate::Itself => Ident::new("pagetop", Span::call_site()),
|
||||
FoundCrate::Name(ref name) => Ident::new(name, Span::call_site()),
|
||||
};
|
||||
let pre_escaped = quote! {
|
||||
#crate_ident::html::PreEscaped(#output_ident)
|
||||
};
|
||||
|
||||
quote! {{
|
||||
extern crate alloc;
|
||||
let mut #output_ident = alloc::string::String::with_capacity(#size_hint);
|
||||
#stmts
|
||||
#(#diag_tokens)*
|
||||
#pre_escaped
|
||||
}}
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -1,27 +0,0 @@
|
|||
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
// !!!!!!!! PLEASE KEEP THIS IN SYNC WITH `maud/src/escape.rs` !!!!!!!!!
|
||||
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
|
||||
pub fn escape_to_string(input: &str, output: &mut String) {
|
||||
for b in input.bytes() {
|
||||
match b {
|
||||
b'&' => output.push_str("&"),
|
||||
b'<' => output.push_str("<"),
|
||||
b'>' => output.push_str(">"),
|
||||
b'"' => output.push_str("""),
|
||||
_ => unsafe { output.as_mut_vec().push(b) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::escape_to_string;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let mut s = String::new();
|
||||
escape_to_string("<script>launchMissiles()</script>", &mut s);
|
||||
assert_eq!(s, "<script>launchMissiles()</script>");
|
||||
}
|
||||
}
|
|
@ -1,392 +0,0 @@
|
|||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{quote, ToTokens};
|
||||
use syn::{parse_quote, token::Brace, Expr, Local};
|
||||
|
||||
use crate::maud::{ast::*, escape};
|
||||
|
||||
use proc_macro_crate::{crate_name, FoundCrate};
|
||||
|
||||
pub fn generate(markups: Markups<Element>, output_ident: Ident) -> TokenStream {
|
||||
let mut build = Builder::new(output_ident.clone());
|
||||
Generator::new(output_ident).markups(markups, &mut build);
|
||||
build.finish()
|
||||
}
|
||||
|
||||
struct Generator {
|
||||
output_ident: Ident,
|
||||
}
|
||||
|
||||
impl Generator {
|
||||
fn new(output_ident: Ident) -> Generator {
|
||||
Generator { output_ident }
|
||||
}
|
||||
|
||||
fn builder(&self) -> Builder {
|
||||
Builder::new(self.output_ident.clone())
|
||||
}
|
||||
|
||||
fn markups<E: Into<Element>>(&self, markups: Markups<E>, build: &mut Builder) {
|
||||
for markup in markups.markups {
|
||||
self.markup(markup, build);
|
||||
}
|
||||
}
|
||||
|
||||
fn markup<E: Into<Element>>(&self, markup: Markup<E>, build: &mut Builder) {
|
||||
match markup {
|
||||
Markup::Block(block) => {
|
||||
if block.markups.markups.iter().any(|markup| {
|
||||
matches!(
|
||||
*markup,
|
||||
Markup::ControlFlow(ControlFlow {
|
||||
kind: ControlFlowKind::Let(_),
|
||||
..
|
||||
})
|
||||
)
|
||||
}) {
|
||||
self.block(block, build);
|
||||
} else {
|
||||
self.markups(block.markups, build);
|
||||
}
|
||||
}
|
||||
Markup::Lit(lit) => build.push_escaped(&lit.to_string()),
|
||||
Markup::Splice { expr, .. } => self.splice(expr, build),
|
||||
Markup::Element(element) => self.element(element.into(), build),
|
||||
Markup::ControlFlow(control_flow) => self.control_flow(control_flow, build),
|
||||
Markup::Semi(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn block<E: Into<Element>>(&self, block: Block<E>, build: &mut Builder) {
|
||||
let markups = {
|
||||
let mut build = self.builder();
|
||||
self.markups(block.markups, &mut build);
|
||||
build.finish()
|
||||
};
|
||||
|
||||
build.push_tokens(quote!({ #markups }));
|
||||
}
|
||||
|
||||
fn splice(&self, expr: Expr, build: &mut Builder) {
|
||||
let output_ident = &self.output_ident;
|
||||
|
||||
let found_crate = crate_name("pagetop").expect("pagetop debe existir en Cargo.toml");
|
||||
let crate_ident = match found_crate {
|
||||
FoundCrate::Itself => Ident::new("pagetop", Span::call_site()),
|
||||
FoundCrate::Name(name) => Ident::new(&name, Span::call_site()),
|
||||
};
|
||||
build.push_tokens(quote! {
|
||||
#crate_ident::html::html_private::render_to!(&(#expr), &mut #output_ident);
|
||||
});
|
||||
}
|
||||
|
||||
fn element(&self, element: Element, build: &mut Builder) {
|
||||
let element_name = element.name.clone().unwrap_or_else(|| parse_quote!(div));
|
||||
build.push_str("<");
|
||||
self.name(element_name.clone(), build);
|
||||
self.attrs(element.attrs, build);
|
||||
build.push_str(">");
|
||||
if let ElementBody::Block(block) = element.body {
|
||||
self.markups(block.markups, build);
|
||||
build.push_str("</");
|
||||
self.name(element_name, build);
|
||||
build.push_str(">");
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self, name: HtmlName, build: &mut Builder) {
|
||||
build.push_escaped(&name.to_string());
|
||||
}
|
||||
|
||||
fn name_or_markup(&self, name: HtmlNameOrMarkup, build: &mut Builder) {
|
||||
match name {
|
||||
HtmlNameOrMarkup::HtmlName(name) => self.name(name, build),
|
||||
HtmlNameOrMarkup::Markup(markup) => self.markup(markup, build),
|
||||
}
|
||||
}
|
||||
|
||||
fn attr(&self, name: HtmlName, value: AttributeType, build: &mut Builder) {
|
||||
match value {
|
||||
AttributeType::Normal { value, .. } => {
|
||||
build.push_str(" ");
|
||||
self.name(name, build);
|
||||
build.push_str("=\"");
|
||||
self.markup(value, build);
|
||||
build.push_str("\"");
|
||||
}
|
||||
AttributeType::Optional {
|
||||
toggler: Toggler { cond, .. },
|
||||
..
|
||||
} => {
|
||||
let inner_value: Expr = parse_quote!(inner_value);
|
||||
|
||||
let body = {
|
||||
let mut build = self.builder();
|
||||
build.push_str(" ");
|
||||
self.name(name, &mut build);
|
||||
build.push_str("=\"");
|
||||
self.splice(inner_value.clone(), &mut build);
|
||||
build.push_str("\"");
|
||||
build.finish()
|
||||
};
|
||||
build.push_tokens(quote!(if let Some(#inner_value) = (#cond) { #body }));
|
||||
}
|
||||
AttributeType::Empty(None) => {
|
||||
build.push_str(" ");
|
||||
self.name(name, build);
|
||||
}
|
||||
AttributeType::Empty(Some(Toggler { cond, .. })) => {
|
||||
let body = {
|
||||
let mut build = self.builder();
|
||||
build.push_str(" ");
|
||||
self.name(name, &mut build);
|
||||
build.finish()
|
||||
};
|
||||
build.push_tokens(quote!(if (#cond) { #body }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn attrs(&self, attrs: Vec<Attribute>, build: &mut Builder) {
|
||||
let (classes, id, named_attrs) = split_attrs(attrs);
|
||||
|
||||
if !classes.is_empty() {
|
||||
let mut toggle_class_exprs = vec![];
|
||||
|
||||
build.push_str(" ");
|
||||
self.name(parse_quote!(class), build);
|
||||
build.push_str("=\"");
|
||||
for (i, (name, toggler)) in classes.into_iter().enumerate() {
|
||||
if let Some(toggler) = toggler {
|
||||
toggle_class_exprs.push((i > 0, name, toggler));
|
||||
} else {
|
||||
if i > 0 {
|
||||
build.push_str(" ");
|
||||
}
|
||||
self.name_or_markup(name, build);
|
||||
}
|
||||
}
|
||||
|
||||
for (not_first, name, toggler) in toggle_class_exprs {
|
||||
let body = {
|
||||
let mut build = self.builder();
|
||||
if not_first {
|
||||
build.push_str(" ");
|
||||
}
|
||||
self.name_or_markup(name, &mut build);
|
||||
build.finish()
|
||||
};
|
||||
build.push_tokens(quote!(if (#toggler) { #body }));
|
||||
}
|
||||
|
||||
build.push_str("\"");
|
||||
}
|
||||
|
||||
if let Some(id) = id {
|
||||
build.push_str(" ");
|
||||
self.name(parse_quote!(id), build);
|
||||
build.push_str("=\"");
|
||||
self.name_or_markup(id, build);
|
||||
build.push_str("\"");
|
||||
}
|
||||
|
||||
for (name, attr_type) in named_attrs {
|
||||
self.attr(name, attr_type, build);
|
||||
}
|
||||
}
|
||||
|
||||
fn control_flow<E: Into<Element>>(&self, control_flow: ControlFlow<E>, build: &mut Builder) {
|
||||
match control_flow.kind {
|
||||
ControlFlowKind::If(if_) => self.control_flow_if(if_, build),
|
||||
ControlFlowKind::Let(let_) => self.control_flow_let(let_, build),
|
||||
ControlFlowKind::For(for_) => self.control_flow_for(for_, build),
|
||||
ControlFlowKind::While(while_) => self.control_flow_while(while_, build),
|
||||
ControlFlowKind::Match(match_) => self.control_flow_match(match_, build),
|
||||
}
|
||||
}
|
||||
|
||||
fn control_flow_if<E: Into<Element>>(
|
||||
&self,
|
||||
IfExpr {
|
||||
if_token,
|
||||
cond,
|
||||
then_branch,
|
||||
else_branch,
|
||||
}: IfExpr<E>,
|
||||
build: &mut Builder,
|
||||
) {
|
||||
build.push_tokens(quote!(#if_token #cond));
|
||||
self.block(then_branch, build);
|
||||
|
||||
if let Some((_, else_token, if_or_block)) = else_branch {
|
||||
build.push_tokens(quote!(#else_token));
|
||||
self.control_flow_if_or_block(*if_or_block, build);
|
||||
}
|
||||
}
|
||||
|
||||
fn control_flow_if_or_block<E: Into<Element>>(
|
||||
&self,
|
||||
if_or_block: IfOrBlock<E>,
|
||||
build: &mut Builder,
|
||||
) {
|
||||
match if_or_block {
|
||||
IfOrBlock::If(if_) => self.control_flow_if(if_, build),
|
||||
IfOrBlock::Block(block) => self.block(block, build),
|
||||
}
|
||||
}
|
||||
|
||||
fn control_flow_let(&self, let_: Local, build: &mut Builder) {
|
||||
build.push_tokens(let_.to_token_stream());
|
||||
}
|
||||
|
||||
fn control_flow_for<E: Into<Element>>(
|
||||
&self,
|
||||
ForExpr {
|
||||
for_token,
|
||||
pat,
|
||||
in_token,
|
||||
expr,
|
||||
body,
|
||||
}: ForExpr<E>,
|
||||
build: &mut Builder,
|
||||
) {
|
||||
build.push_tokens(quote!(#for_token #pat #in_token (#expr)));
|
||||
self.block(body, build);
|
||||
}
|
||||
|
||||
fn control_flow_while<E: Into<Element>>(
|
||||
&self,
|
||||
WhileExpr {
|
||||
while_token,
|
||||
cond,
|
||||
body,
|
||||
}: WhileExpr<E>,
|
||||
build: &mut Builder,
|
||||
) {
|
||||
build.push_tokens(quote!(#while_token #cond));
|
||||
self.block(body, build);
|
||||
}
|
||||
|
||||
fn control_flow_match<E: Into<Element>>(
|
||||
&self,
|
||||
MatchExpr {
|
||||
match_token,
|
||||
expr,
|
||||
brace_token,
|
||||
arms,
|
||||
}: MatchExpr<E>,
|
||||
build: &mut Builder,
|
||||
) {
|
||||
let arms = {
|
||||
let mut build = self.builder();
|
||||
for MatchArm {
|
||||
pat,
|
||||
guard,
|
||||
fat_arrow_token,
|
||||
body,
|
||||
comma_token,
|
||||
} in arms
|
||||
{
|
||||
build.push_tokens(quote!(#pat));
|
||||
if let Some((if_token, cond)) = guard {
|
||||
build.push_tokens(quote!(#if_token #cond));
|
||||
}
|
||||
build.push_tokens(quote!(#fat_arrow_token));
|
||||
self.block(
|
||||
Block {
|
||||
brace_token: Brace(Span::call_site()),
|
||||
markups: Markups {
|
||||
markups: vec![body],
|
||||
},
|
||||
},
|
||||
&mut build,
|
||||
);
|
||||
build.push_tokens(quote!(#comma_token));
|
||||
}
|
||||
build.finish()
|
||||
};
|
||||
|
||||
let mut arm_block = TokenStream::new();
|
||||
|
||||
brace_token.surround(&mut arm_block, |tokens| {
|
||||
arms.to_tokens(tokens);
|
||||
});
|
||||
|
||||
build.push_tokens(quote!(#match_token #expr #arm_block));
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn split_attrs(
|
||||
attrs: Vec<Attribute>,
|
||||
) -> (
|
||||
Vec<(HtmlNameOrMarkup, Option<Expr>)>,
|
||||
Option<HtmlNameOrMarkup>,
|
||||
Vec<(HtmlName, AttributeType)>,
|
||||
) {
|
||||
let mut classes = vec![];
|
||||
let mut id = None;
|
||||
let mut named_attrs = vec![];
|
||||
|
||||
for attr in attrs {
|
||||
match attr {
|
||||
Attribute::Class { name, toggler, .. } => {
|
||||
classes.push((name, toggler.map(|toggler| toggler.cond)))
|
||||
}
|
||||
Attribute::Id { name, .. } => id = Some(name),
|
||||
Attribute::Named { name, attr_type } => named_attrs.push((name, attr_type)),
|
||||
}
|
||||
}
|
||||
|
||||
(classes, id, named_attrs)
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
struct Builder {
|
||||
output_ident: Ident,
|
||||
tokens: TokenStream,
|
||||
tail: String,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
fn new(output_ident: Ident) -> Builder {
|
||||
Builder {
|
||||
output_ident,
|
||||
tokens: TokenStream::new(),
|
||||
tail: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_str(&mut self, string: &'static str) {
|
||||
self.tail.push_str(string);
|
||||
}
|
||||
|
||||
fn push_escaped(&mut self, string: &str) {
|
||||
escape::escape_to_string(string, &mut self.tail);
|
||||
}
|
||||
|
||||
fn push_tokens(&mut self, tokens: TokenStream) {
|
||||
self.cut();
|
||||
self.tokens.extend(tokens);
|
||||
}
|
||||
|
||||
fn cut(&mut self) {
|
||||
if self.tail.is_empty() {
|
||||
return;
|
||||
}
|
||||
let push_str_expr = {
|
||||
let output_ident = self.output_ident.clone();
|
||||
let tail = &self.tail;
|
||||
quote!(#output_ident.push_str(#tail);)
|
||||
};
|
||||
self.tail.clear();
|
||||
self.tokens.extend(push_str_expr);
|
||||
}
|
||||
|
||||
fn finish(mut self) -> TokenStream {
|
||||
self.cut();
|
||||
self.tokens
|
||||
}
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
//! HTML en código.
|
||||
|
||||
mod maud;
|
||||
pub use maud::{display, html, html_private, Escaper, Markup, PreEscaped, Render, DOCTYPE};
|
381
src/html/maud.rs
381
src/html/maud.rs
|
@ -1,381 +0,0 @@
|
|||
// #![no_std]
|
||||
|
||||
//! A macro for writing HTML templates.
|
||||
//!
|
||||
//! This documentation only describes the runtime API. For a general
|
||||
//! guide, check out the [book] instead.
|
||||
//!
|
||||
//! [book]: https://maud.lambda.xyz/
|
||||
|
||||
// #![doc(html_root_url = "https://docs.rs/maud/0.27.0")]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc};
|
||||
use core::fmt::{self, Arguments, Display, Write};
|
||||
|
||||
pub use pagetop_macros::html;
|
||||
|
||||
mod escape;
|
||||
|
||||
/// An adapter that escapes HTML special characters.
|
||||
///
|
||||
/// The following characters are escaped:
|
||||
///
|
||||
/// * `&` is escaped as `&`
|
||||
/// * `<` is escaped as `<`
|
||||
/// * `>` is escaped as `>`
|
||||
/// * `"` is escaped as `"`
|
||||
///
|
||||
/// All other characters are passed through unchanged.
|
||||
///
|
||||
/// **Note:** In versions prior to 0.13, the single quote (`'`) was
|
||||
/// escaped as well.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use pagetop::html::Escaper;
|
||||
/// use std::fmt::Write;
|
||||
/// let mut s = String::new();
|
||||
/// write!(Escaper::new(&mut s), "<script>launchMissiles()</script>").unwrap();
|
||||
/// assert_eq!(s, "<script>launchMissiles()</script>");
|
||||
/// ```
|
||||
pub struct Escaper<'a>(&'a mut String);
|
||||
|
||||
impl<'a> Escaper<'a> {
|
||||
/// Creates an `Escaper` from a `String`.
|
||||
pub fn new(buffer: &'a mut String) -> Escaper<'a> {
|
||||
Escaper(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Write for Escaper<'_> {
|
||||
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||
escape::escape_to_string(s, self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a type that can be rendered as HTML.
|
||||
///
|
||||
/// To implement this for your own type, override either the `.render()`
|
||||
/// or `.render_to()` methods; since each is defined in terms of the
|
||||
/// other, you only need to implement one of them. See the example below.
|
||||
///
|
||||
/// # Minimal implementation
|
||||
///
|
||||
/// An implementation of this trait must override at least one of
|
||||
/// `.render()` or `.render_to()`. Since the default definitions of
|
||||
/// these methods call each other, not doing this will result in
|
||||
/// infinite recursion.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use pagetop::html::{html, Markup, Render};
|
||||
///
|
||||
/// /// Provides a shorthand for linking to a CSS stylesheet.
|
||||
/// pub struct Stylesheet(&'static str);
|
||||
///
|
||||
/// impl Render for Stylesheet {
|
||||
/// fn render(&self) -> Markup {
|
||||
/// html! {
|
||||
/// link rel="stylesheet" type="text/css" href=(self.0);
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Render {
|
||||
/// Renders `self` as a block of `Markup`.
|
||||
fn render(&self) -> Markup {
|
||||
let mut buffer = String::new();
|
||||
self.render_to(&mut buffer);
|
||||
PreEscaped(buffer)
|
||||
}
|
||||
|
||||
/// Appends a representation of `self` to the given buffer.
|
||||
///
|
||||
/// Its default implementation just calls `.render()`, but you may
|
||||
/// override it with something more efficient.
|
||||
///
|
||||
/// Note that no further escaping is performed on data written to
|
||||
/// the buffer. If you override this method, you must make sure that
|
||||
/// any data written is properly escaped, whether by hand or using
|
||||
/// the [`Escaper`](struct.Escaper.html) wrapper struct.
|
||||
fn render_to(&self, buffer: &mut String) {
|
||||
buffer.push_str(&self.render().into_string());
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for str {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
escape::escape_to_string(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for String {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
str::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Cow<'_, str> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
str::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Arguments<'_> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
let _ = Escaper::new(w).write_fmt(*self);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Render + ?Sized> Render for &T {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
T::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Render + ?Sized> Render for &mut T {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
T::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Render + ?Sized> Render for Box<T> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
T::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Render + ?Sized> Render for Arc<T> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
T::render_to(self, w);
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_render_with_display {
|
||||
($($ty:ty)*) => {
|
||||
$(
|
||||
impl Render for $ty {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
// TODO: remove the explicit arg when Rust 1.58 is released
|
||||
format_args!("{self}", self = self).render_to(w);
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_render_with_display! {
|
||||
char f32 f64
|
||||
}
|
||||
|
||||
macro_rules! impl_render_with_itoa {
|
||||
($($ty:ty)*) => {
|
||||
$(
|
||||
impl Render for $ty {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
w.push_str(itoa::Buffer::new().format(*self));
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_render_with_itoa! {
|
||||
i8 i16 i32 i64 i128 isize
|
||||
u8 u16 u32 u64 u128 usize
|
||||
}
|
||||
|
||||
/// Renders a value using its [`Display`] impl.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use pagetop::html::{display, html};
|
||||
/// use std::net::Ipv4Addr;
|
||||
///
|
||||
/// let ip_address = Ipv4Addr::new(127, 0, 0, 1);
|
||||
///
|
||||
/// let markup = html! {
|
||||
/// "My IP address is: "
|
||||
/// (display(ip_address))
|
||||
/// };
|
||||
///
|
||||
/// assert_eq!(markup.into_string(), "My IP address is: 127.0.0.1");
|
||||
/// ```
|
||||
pub fn display(value: impl Display) -> impl Render {
|
||||
struct DisplayWrapper<T>(T);
|
||||
|
||||
impl<T: Display> Render for DisplayWrapper<T> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
format_args!("{0}", self.0).render_to(w);
|
||||
}
|
||||
}
|
||||
|
||||
DisplayWrapper(value)
|
||||
}
|
||||
|
||||
/// A wrapper that renders the inner value without escaping.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PreEscaped<T>(pub T);
|
||||
|
||||
impl<T: AsRef<str>> Render for PreEscaped<T> {
|
||||
fn render_to(&self, w: &mut String) {
|
||||
w.push_str(self.0.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
/// A block of markup is a string that does not need to be escaped.
|
||||
///
|
||||
/// The `html!` macro expands to an expression of this type.
|
||||
pub type Markup = PreEscaped<String>;
|
||||
|
||||
impl Markup {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<String>> PreEscaped<T> {
|
||||
/// Converts the inner value to a string.
|
||||
pub fn into_string(self) -> String {
|
||||
self.0.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<String>> From<PreEscaped<T>> for String {
|
||||
fn from(value: PreEscaped<T>) -> String {
|
||||
value.into_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Default> Default for PreEscaped<T> {
|
||||
fn default() -> Self {
|
||||
Self(Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
/// The literal string `<!DOCTYPE html>`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// A minimal web page:
|
||||
///
|
||||
/// ```rust
|
||||
/// use pagetop::html::{DOCTYPE, html};
|
||||
///
|
||||
/// let markup = html! {
|
||||
/// (DOCTYPE)
|
||||
/// html {
|
||||
/// head {
|
||||
/// meta charset="utf-8";
|
||||
/// title { "Test page" }
|
||||
/// }
|
||||
/// body {
|
||||
/// p { "Hello, world!" }
|
||||
/// }
|
||||
/// }
|
||||
/// };
|
||||
/// ```
|
||||
pub const DOCTYPE: PreEscaped<&'static str> = PreEscaped("<!DOCTYPE html>");
|
||||
|
||||
mod actix_support {
|
||||
extern crate alloc;
|
||||
|
||||
use core::{
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use crate::html::PreEscaped;
|
||||
use actix_web::{
|
||||
body::{BodySize, MessageBody},
|
||||
http::header,
|
||||
web::Bytes,
|
||||
HttpRequest, HttpResponse, Responder,
|
||||
};
|
||||
use alloc::string::String;
|
||||
|
||||
impl MessageBody for PreEscaped<String> {
|
||||
type Error = <String as MessageBody>::Error;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
self.0.size()
|
||||
}
|
||||
|
||||
fn poll_next(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
Pin::new(&mut self.0).poll_next(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl Responder for PreEscaped<String> {
|
||||
type Body = String;
|
||||
|
||||
fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
|
||||
HttpResponse::Ok()
|
||||
.content_type(header::ContentType::html())
|
||||
.message_body(self.0)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub mod html_private {
|
||||
extern crate alloc;
|
||||
|
||||
use super::{display, Render};
|
||||
use alloc::string::String;
|
||||
use core::fmt::Display;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! render_to {
|
||||
($x:expr, $buffer:expr) => {{
|
||||
use $crate::html::html_private::*;
|
||||
match ChooseRenderOrDisplay($x) {
|
||||
x => (&&x).implements_render_or_display().render_to(x.0, $buffer),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub use render_to;
|
||||
|
||||
pub struct ChooseRenderOrDisplay<T>(pub T);
|
||||
|
||||
pub struct ViaRenderTag;
|
||||
pub struct ViaDisplayTag;
|
||||
|
||||
pub trait ViaRender {
|
||||
fn implements_render_or_display(&self) -> ViaRenderTag {
|
||||
ViaRenderTag
|
||||
}
|
||||
}
|
||||
pub trait ViaDisplay {
|
||||
fn implements_render_or_display(&self) -> ViaDisplayTag {
|
||||
ViaDisplayTag
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Render> ViaRender for &ChooseRenderOrDisplay<T> {}
|
||||
impl<T: Display> ViaDisplay for ChooseRenderOrDisplay<T> {}
|
||||
|
||||
impl ViaRenderTag {
|
||||
pub fn render_to<T: Render + ?Sized>(self, value: &T, buffer: &mut String) {
|
||||
value.render_to(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
impl ViaDisplayTag {
|
||||
pub fn render_to<T: Display + ?Sized>(self, value: &T, buffer: &mut String) {
|
||||
display(value).render_to(buffer);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
// !!!!! PLEASE KEEP THIS IN SYNC WITH `maud_macros/src/escape.rs` !!!!!
|
||||
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use alloc::string::String;
|
||||
|
||||
pub fn escape_to_string(input: &str, output: &mut String) {
|
||||
for b in input.bytes() {
|
||||
match b {
|
||||
b'&' => output.push_str("&"),
|
||||
b'<' => output.push_str("<"),
|
||||
b'>' => output.push_str(">"),
|
||||
b'"' => output.push_str("""),
|
||||
_ => unsafe { output.as_mut_vec().push(b) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
extern crate alloc;
|
||||
|
||||
use super::escape_to_string;
|
||||
use alloc::string::String;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let mut s = String::new();
|
||||
escape_to_string("<script>launchMissiles()</script>", &mut s);
|
||||
assert_eq!(s, "<script>launchMissiles()</script>");
|
||||
}
|
||||
}
|
|
@ -32,7 +32,7 @@
|
|||
|
||||
// RE-EXPORTED *************************************************************************************
|
||||
|
||||
pub use pagetop_macros::{html, main, test};
|
||||
pub use pagetop_macros::{main, test};
|
||||
|
||||
// API *********************************************************************************************
|
||||
|
||||
|
@ -42,8 +42,6 @@ pub mod config;
|
|||
pub mod global;
|
||||
// Gestión de trazas y registro de eventos de la aplicación.
|
||||
pub mod trace;
|
||||
// HTML en código.
|
||||
pub mod html;
|
||||
// Gestión del servidor y servicios web.
|
||||
pub mod service;
|
||||
// Prepara y ejecuta la aplicación.
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
// RE-EXPORTED.
|
||||
|
||||
pub use crate::{html, main, test};
|
||||
pub use crate::{main, test};
|
||||
|
||||
// MACROS.
|
||||
|
||||
|
@ -15,8 +15,6 @@ pub use crate::global;
|
|||
|
||||
pub use crate::trace;
|
||||
|
||||
pub use crate::html::*;
|
||||
|
||||
pub use crate::service;
|
||||
|
||||
pub use crate::app::Application;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
//! Gestión del servidor y servicios web ([Actix Web](https://docs.rs/actix-web)).
|
||||
//! Gestión del servidor y servicios web ([actix-web](https://docs.rs/actix-web)).
|
||||
|
||||
pub use actix_web::body::BoxBody;
|
||||
pub use actix_web::dev::Server;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue