feat: tachys

This commit is contained in:
Greg Johnston 2024-02-05 07:33:43 -05:00
parent 61f5294f67
commit 63dacdcc95
55 changed files with 12391 additions and 13 deletions

View file

@ -3,6 +3,8 @@ resolver = "2"
members = [
# utilities
"oco",
"const_str_slice_concat",
"next_tuple",
"or_poisoned",
# core
@ -18,6 +20,7 @@ members = [
"server_fn",
"server_fn_macro",
"server_fn/server_fn_macro_default",
"tachys",
# integrations
"integrations/actix",
@ -35,20 +38,24 @@ version = "0.6.13"
rust-version = "1.75"
[workspace.dependencies]
oco_ref = { path = "./oco", version = "0.1.0" }
leptos = { path = "./leptos", version = "0.6.13" }
leptos_dom = { path = "./leptos_dom", version = "0.6.13" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.6.13" }
leptos_macro = { path = "./leptos_macro", version = "0.6.13" }
leptos_reactive = { path = "./leptos_reactive", version = "0.6.13" }
leptos_server = { path = "./leptos_server", version = "0.6.13" }
server_fn = { path = "./server_fn", version = "0.6.13" }
server_fn_macro = { path = "./server_fn_macro", version = "0.6.13" }
const_str_slice_concat = { path = "./const_str_slice_concat" }
leptos = { path = "./leptos", version = "0.6.5" }
leptos_config = { path = "./leptos_config", version = "0.6.5" }
leptos_dom = { path = "./leptos_dom", version = "0.6.5" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.6.5" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.6.5" }
leptos_macro = { path = "./leptos_macro", version = "0.6.5" }
leptos_reactive = { path = "./leptos_reactive", version = "0.6.5" }
leptos_router = { path = "./router", version = "0.6.5" }
leptos_server = { path = "./leptos_server", version = "0.6.5" }
leptos_meta = { path = "./meta", version = "0.6.5" }
next_tuple = { path = "./next_tuple" }
or_poisoned = { path = "./or_poisoned" }
reactive_graph = { path = "./reactive_graph" }
server_fn = { path = "./server_fn", version = "0.6.5" }
server_fn_macro = { path = "./server_fn_macro", version = "0.6.5" }
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.6" }
leptos_config = { path = "./leptos_config", version = "0.6.13" }
leptos_router = { path = "./router", version = "0.6.13" }
leptos_meta = { path = "./meta", version = "0.6.13" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.6.13" }
tachys = { path = "./tachys" }
[profile.release]
codegen-units = 1

20
TODO.md Normal file
View file

@ -0,0 +1,20 @@
- hackernews example
- SSR
- islands
- TODOs
- Suspense/Transition/Await components
- nicer routing components
- async routing (waiting for data to load before navigation)
- `<A>` component
- figure out rebuilding issues: list (needs new signal IDs) vs. regular rebuild
- better import/export API
- escaping HTML correctly (attributes + text nodes)
- nested routes
- Signal wrappers
- SignalDispose implementations on all Copy types
- untracked access warnings
- nicer type than -> `impl RenderHtml<Dom>`
- \_meta package (and use in hackernews)
- building out examples to find missing features
- fix order of el and key so they're the same across traits, in build and rebuild, for attr and property
- update streaming SSR tests

View file

@ -0,0 +1,8 @@
[package]
name = "const_str_slice_concat"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,133 @@
pub(crate) const MAX_TEMPLATE_SIZE: usize = 4096;
/// Converts a zero-terminated buffer of bytes into a UTF-8 string.
pub const fn str_from_buffer(buf: &[u8; MAX_TEMPLATE_SIZE]) -> &str {
match std::ffi::CStr::from_bytes_until_nul(buf) {
Ok(cstr) => match cstr.to_str() {
Ok(str) => str,
Err(_) => panic!("TEMPLATE FAILURE"),
},
Err(_) => panic!("TEMPLATE FAILURE"),
}
}
/// Concatenates any number of static strings in a single one.
// credit to Rainer Stropek, "Constant fun," Rust Linz, June 2022
pub const fn const_concat(
strs: &'static [&'static str],
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable refernces in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
remaining = tail;
}
buffer
}
/// Converts a zero-terminated buffer of bytes into a UTF-8 string with the given prefix.
pub const fn const_concat_with_prefix(
strs: &'static [&'static str],
prefix: &'static str,
suffix: &'static str,
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable refernces in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
remaining = tail;
}
if buffer[0] == 0 {
buffer
} else {
let mut new_buf = [0; MAX_TEMPLATE_SIZE];
let prefix = prefix.as_bytes();
let suffix = suffix.as_bytes();
let mut position = 0;
let mut i = 0;
while i < prefix.len() {
new_buf[position] = prefix[i];
position += 1;
i += 1;
}
i = 0;
while i < buffer.len() {
if buffer[i] == 0 {
break;
}
new_buf[position] = buffer[i];
position += 1;
i += 1;
}
i = 0;
while i < suffix.len() {
new_buf[position] = suffix[i];
position += 1;
i += 1;
}
new_buf
}
}
/// Converts any number of strings into a UTF-8 string, separated by the given string.
pub const fn const_concat_with_separator(
strs: &[&str],
separator: &'static str,
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable refernces in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
if !x.is_empty() {
let mut position = 0;
let separator = separator.as_bytes();
while i < separator.len() {
buffer[position] = separator[i];
position += 1;
i += 1;
}
}
remaining = tail;
}
buffer
}

8
next_tuple/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "next_tuple"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

75
next_tuple/src/lib.rs Normal file
View file

@ -0,0 +1,75 @@
#![allow(non_snake_case)]
pub trait TupleBuilder<Next> {
type Output;
fn next_tuple(self, next: Next) -> Self::Output;
}
pub trait ConcatTuples<Next> {
type Output;
fn concat(self, next: Next) -> Self::Output;
}
macro_rules! impl_tuple_builder {
($($ty:ident),* => $last:ident) => {
impl<$($ty),*, $last> TupleBuilder<$last> for ($($ty,)*) {
type Output = ($($ty,)* $last);
fn next_tuple(self, next: $last) -> Self::Output {
let ($($ty,)*) = self;
($($ty,)* next)
}
}
};
}
impl<A> TupleBuilder<A> for () {
type Output = (A,);
fn next_tuple(self, next: A) -> Self::Output {
(next,)
}
}
impl_tuple_builder!(A => B);
impl_tuple_builder!(A, B => C);
impl_tuple_builder!(A, B, C => D);
impl_tuple_builder!(A, B, C, D => E);
impl_tuple_builder!(A, B, C, D, E => F);
impl_tuple_builder!(A, B, C, D, E, F => G);
impl_tuple_builder!(A, B, C, D, E, F, G => H);
impl_tuple_builder!(A, B, C, D, E, F, G, H => I);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I => J);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J => K);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K => L);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L => M);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M => N);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N => O);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O => P);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P => Q);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q => R);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R => S);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S => T
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T => U
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U => V
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V => W
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W => X
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X => Y
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y =>
Z
);

160
tachys/Cargo.toml Normal file
View file

@ -0,0 +1,160 @@
[package]
name = "tachys"
version = "0.1.0"
edition = "2021"
[dependencies]
const_str_slice_concat = { workspace = true }
next_tuple = { path = "../next_tuple" }
reactive_graph = { workspace = true, optional = true }
slotmap = { version = "1", optional = true }
once_cell = "1"
paste = "1"
wasm-bindgen = "0.2"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Window",
"Document",
"HtmlElement",
"HtmlInputElement",
"Element",
"Event",
"console",
"Comment",
"Text",
"Node",
"HtmlTemplateElement",
"DocumentFragment",
"DomTokenList",
"CssStyleDeclaration",
"ShadowRoot",
# Events we cast to in leptos_macro -- added here so we don't force users to import them
"AddEventListenerOptions",
"AnimationEvent",
"BeforeUnloadEvent",
"ClipboardEvent",
"CompositionEvent",
"CustomEvent",
"DeviceMotionEvent",
"DeviceOrientationEvent",
"DragEvent",
"ErrorEvent",
"Event",
"FocusEvent",
"GamepadEvent",
"HashChangeEvent",
"InputEvent",
"KeyboardEvent",
"MessageEvent",
"MouseEvent",
"PageTransitionEvent",
"PointerEvent",
"PopStateEvent",
"ProgressEvent",
"PromiseRejectionEvent",
"SecurityPolicyViolationEvent",
"StorageEvent",
"SubmitEvent",
"TouchEvent",
"TransitionEvent",
"UiEvent",
"WheelEvent",
# HTML Element Types
"HtmlHtmlElement",
"HtmlBaseElement",
"HtmlHeadElement",
"HtmlLinkElement",
"HtmlMetaElement",
"HtmlStyleElement",
"HtmlTitleElement",
"HtmlBodyElement",
"HtmlHeadingElement",
"HtmlQuoteElement",
"HtmlDivElement",
"HtmlDListElement",
"HtmlHrElement",
"HtmlLiElement",
"HtmlOListElement",
"HtmlParagraphElement",
"HtmlPreElement",
"HtmlUListElement",
"HtmlAnchorElement",
"HtmlBrElement",
"HtmlDataElement",
"HtmlQuoteElement",
"HtmlSpanElement",
"HtmlTimeElement",
"HtmlAreaElement",
"HtmlAudioElement",
"HtmlImageElement",
"HtmlMapElement",
"HtmlTrackElement",
"HtmlVideoElement",
"HtmlEmbedElement",
"HtmlIFrameElement",
"HtmlObjectElement",
"HtmlParamElement",
"HtmlPictureElement",
"HtmlSourceElement",
"SvgElement",
"HtmlCanvasElement",
"HtmlScriptElement",
"HtmlModElement",
"HtmlTableCaptionElement",
"HtmlTableColElement",
"HtmlTableColElement",
"HtmlTableElement",
"HtmlTableSectionElement",
"HtmlTableCellElement",
"HtmlTableSectionElement",
"HtmlTableCellElement",
"HtmlTableSectionElement",
"HtmlTableRowElement",
"HtmlButtonElement",
"HtmlDataListElement",
"HtmlFieldSetElement",
"HtmlFormElement",
"HtmlInputElement",
"HtmlLabelElement",
"HtmlLegendElement",
"HtmlMeterElement",
"HtmlOptGroupElement",
"HtmlOutputElement",
"HtmlProgressElement",
"HtmlSelectElement",
"HtmlTextAreaElement",
"HtmlDetailsElement",
"HtmlDialogElement",
"HtmlMenuElement",
"HtmlSlotElement",
"HtmlTemplateElement",
"HtmlOptionElement",
] }
drain_filter_polyfill = "0.1"
indexmap = "2"
rustc-hash = "1"
tokio = { version = "1", optional = true, features = ["rt"] }
wasm-bindgen-futures = { version = "0.4", optional = true }
futures = "0.3"
parking_lot = "0.12"
pin-project-lite = "0.2"
itertools = "0.12"
send_wrapper = "0.6"
[dev-dependencies]
tokio-test = "0.4"
tokio = { version = "1", features = ["rt", "macros"] }
[features]
default = ["testing"]
delegation = [] # enables event delegation
hydrate = []
islands = []
ssr = []
nightly = ["reactive_graph/nightly"]
testing = ["dep:slotmap"]
reactive_graph = ["dep:reactive_graph"]
tokio = ["dep:tokio"]
web = ["dep:wasm-bindgen-futures"]

View file

@ -0,0 +1,251 @@
use crate::{
hydration::Cursor,
renderer::{Renderer, SpawningRenderer},
spawner::Spawner,
ssr::StreamBuilder,
view::{
either::{Either, EitherState},
Mountable, Position, PositionState, Render, RenderHtml,
},
};
use futures::FutureExt;
use parking_lot::RwLock;
use std::{fmt::Debug, future::Future, sync::Arc};
pub trait FutureViewExt: Sized {
fn suspend(self) -> Suspend<false, (), Self>
where
Self: Future,
{
Suspend {
fallback: (),
fut: self,
}
}
}
impl<F> FutureViewExt for F where F: Future + Sized {}
pub struct Suspend<const TRANSITION: bool, Fal, Fut> {
pub fallback: Fal,
pub fut: Fut,
}
impl<const TRANSITION: bool, Fal, Fut> Suspend<TRANSITION, Fal, Fut> {
pub fn with_fallback<Fal2>(
self,
fallback: Fal2,
) -> Suspend<TRANSITION, Fal2, Fut> {
let fut = self.fut;
Suspend { fallback, fut }
}
pub fn transition(self) -> Suspend<true, Fal, Fut> {
let Suspend { fallback, fut } = self;
Suspend { fallback, fut }
}
}
impl<const TRANSITION: bool, Fal, Fut> Debug for Suspend<TRANSITION, Fal, Fut> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SuspendedFuture")
.field("transition", &TRANSITION)
.finish()
}
}
// TODO make this cancelable
impl<const TRANSITION: bool, Fal, Fut, Rndr> Render<Rndr>
for Suspend<TRANSITION, Fal, Fut>
where
Fal: Render<Rndr> + 'static,
Fut: Future + 'static,
Fut::Output: Render<Rndr>,
Rndr: SpawningRenderer + 'static,
{
type State = Arc<RwLock<EitherState<Fal, Fut::Output, Rndr>>>;
fn build(self) -> Self::State {
// poll the future once immediately
// if it's already available, start in the ready state
// otherwise, start with the fallback
let mut fut = Box::pin(self.fut);
let initial = match fut.as_mut().now_or_never() {
Some(resolved) => Either::Right(resolved),
None => Either::Left(self.fallback),
};
// store whether this was pending at first
// by the time we need to know, we will have consumed `initial`
let initially_pending = matches!(initial, Either::Left(_));
// now we can build the initial state
let state = Arc::new(RwLock::new(initial.build()));
// if the initial state was pending, spawn a future to wait for it
// spawning immediately means that our now_or_never poll result isn't lost
// if it wasn't pending at first, we don't need to poll the Future again
if initially_pending {
Rndr::Spawn::spawn_local({
let state = Arc::clone(&state);
async move {
let value = fut.as_mut().await;
Either::Right(value).rebuild(&mut *state.write());
}
});
}
state
}
fn rebuild(self, state: &mut Self::State) {
if !TRANSITION {
// fall back to fallback state
Either::Left(self.fallback).rebuild(&mut *state.write());
}
// spawn the future, and rebuild the state when it resolves
Rndr::Spawn::spawn_local({
let state = Arc::clone(state);
async move {
let value = self.fut.await;
Either::Right(value).rebuild(&mut *state.write());
}
});
}
}
impl<const TRANSITION: bool, Fal, Fut, Rndr> RenderHtml<Rndr>
for Suspend<TRANSITION, Fal, Fut>
where
Fal: RenderHtml<Rndr> + Send + Sync + 'static,
Fut: Future + Send + Sync + 'static,
Fut::Output: RenderHtml<Rndr>,
Rndr: SpawningRenderer + 'static,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
const MIN_LENGTH: usize = Fal::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
Either::<Fal, Fut::Output>::Left(self.fallback)
.to_html_with_buf(buf, position);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
buf.next_id();
let mut fut = Box::pin(self.fut);
match fut.as_mut().now_or_never() {
Some(resolved) => {
Either::<Fal, Fut::Output>::Right(resolved)
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
None => {
let id = buf.clone_id();
// out-of-order streams immediately push fallback,
// wrapped by suspense markers
if OUT_OF_ORDER {
buf.push_fallback(self.fallback, position);
buf.push_async_out_of_order(
false, /* TODO should_block */ fut, position,
);
} else {
buf.push_async(
false, // TODO should_block
{
let mut position = *position;
async move {
let value = fut.await;
let mut builder = StreamBuilder::new(id);
Either::<Fal, Fut::Output>::Right(value)
.to_html_async_with_buf::<OUT_OF_ORDER>(
&mut builder,
&mut position,
);
builder.finish().take_chunks()
}
},
);
*position = Position::NextChild;
}
}
};
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
// poll the future once immediately
// if it's already available, start in the ready state
// otherwise, start with the fallback
let mut fut = Box::pin(self.fut);
let initial = match fut.as_mut().now_or_never() {
Some(resolved) => Either::Right(resolved),
None => Either::Left(self.fallback),
};
// store whether this was pending at first
// by the time we need to know, we will have consumed `initial`
let initially_pending = matches!(initial, Either::Left(_));
// now we can build the initial state
let state = Arc::new(RwLock::new(
initial.hydrate::<FROM_SERVER>(cursor, position),
));
// if the initial state was pending, spawn a future to wait for it
// spawning immediately means that our now_or_never poll result isn't lost
// if it wasn't pending at first, we don't need to poll the Future again
if initially_pending {
Rndr::Spawn::spawn_local({
let state = Arc::clone(&state);
async move {
let value = fut.as_mut().await;
Either::Right(value).rebuild(&mut *state.write());
}
});
}
state
}
}
impl<Rndr, Fal, Output> Mountable<Rndr>
for Arc<RwLock<EitherState<Fal, Output, Rndr>>>
where
Fal: Render<Rndr>,
Fal::State: Mountable<Rndr>,
Output: Render<Rndr>,
Output::State: Mountable<Rndr>,
Rndr: Renderer,
{
fn unmount(&mut self) {
self.write().unmount();
}
fn mount(
&mut self,
parent: &<Rndr as Renderer>::Element,
marker: Option<&<Rndr as Renderer>::Node>,
) {
self.write().mount(parent, marker);
}
fn insert_before_this(
&self,
parent: &<Rndr as Renderer>::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
self.write().insert_before_this(parent, child)
}
}

62
tachys/src/dom.rs Normal file
View file

@ -0,0 +1,62 @@
use once_cell::unsync::Lazy;
use wasm_bindgen::JsCast;
use web_sys::{Document, HtmlElement, Node, Window};
pub fn window() -> Window {
web_sys::window().unwrap()
}
pub fn document() -> Document {
window().document().unwrap()
}
pub fn body() -> HtmlElement {
document().body().unwrap()
}
pub fn comment() -> Node {
thread_local! {
static COMMENT: Lazy<Node> = Lazy::new(|| {
document().create_comment("").unchecked_into()
});
}
COMMENT.with(|n| n.clone_node().unwrap())
}
pub fn log(s: &str) {
web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(s));
}
/// Helper function to extract [`Event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target)
/// from any event.
pub fn event_target<T>(event: &web_sys::Event) -> T
where
T: JsCast,
{
event.target().unwrap().unchecked_into::<T>()
}
/// Helper function to extract `event.target.value` from an event.
///
/// This is useful in the `on:input` or `on:change` listeners for an `<input>` element.
pub fn event_target_value<T>(event: &T) -> String
where
T: JsCast,
{
event
.unchecked_ref::<web_sys::Event>()
.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>()
.value()
}
/// Helper function to extract `event.target.checked` from an event.
///
/// This is useful in the `on:change` listeners for an `<input type="checkbox">` element.
pub fn event_target_checked(ev: &web_sys::Event) -> bool {
ev.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>()
.checked()
}

35
tachys/src/error.rs Normal file
View file

@ -0,0 +1,35 @@
use std::{error, fmt, ops};
/// This is a result type into which any error can be converted,
/// and which can be used directly in your `view`.
///
/// All errors will be stored as [`struct@Error`].
pub type Result<T> = core::result::Result<T, Error>;
/// A generic wrapper for any error.
#[derive(Debug)]
#[repr(transparent)]
pub struct Error(Box<dyn error::Error + Send + Sync>);
impl ops::Deref for Error {
type Target = Box<dyn error::Error + Send + Sync>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl<T> From<T> for Error
where
T: error::Error + Send + Sync + 'static,
{
fn from(value: T) -> Self {
Error(Box::new(value))
}
}

View file

@ -0,0 +1,199 @@
use crate::html::attribute::{global::AddAttribute, Attr, *};
pub trait AriaAttributes<Rndr, V>
where
Self: Sized
+ AddAttribute<Attr<AriaAtomic, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaBusy, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaControls, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaCurrent, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDescribedby, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDescription, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDetails, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDisabled, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDropeffect, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaErrormessage, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaFlowto, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaGrabbed, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaHaspopup, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaHidden, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaInvalid, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaKeyshortcuts, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLabel, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLabelledby, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLive, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaOwns, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaRelevant, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaRoledescription, V, Rndr>, Rndr>,
V: AttributeValue<Rndr>,
Rndr: Renderer,
{
fn aria_atomic(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaAtomic, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_atomic(value))
}
fn aria_busy(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaBusy, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_busy(value))
}
fn aria_controls(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaControls, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_controls(value))
}
fn aria_current(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaCurrent, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_current(value))
}
fn aria_describedby(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaDescribedby, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_describedby(value))
}
fn aria_description(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaDescription, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_description(value))
}
fn aria_details(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaDetails, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_details(value))
}
fn aria_disabled(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaDisabled, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_disabled(value))
}
fn aria_dropeffect(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaDropeffect, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_dropeffect(value))
}
fn aria_errormessage(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaErrormessage, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_errormessage(value))
}
fn aria_flowto(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaFlowto, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_flowto(value))
}
fn aria_grabbed(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaGrabbed, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_grabbed(value))
}
fn aria_haspopup(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaHaspopup, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_haspopup(value))
}
fn aria_hidden(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaHidden, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_hidden(value))
}
fn aria_invalid(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaInvalid, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_invalid(value))
}
fn aria_keyshortcuts(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaKeyshortcuts, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_keyshortcuts(value))
}
fn aria_label(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaLabel, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_label(value))
}
fn aria_labelledby(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaLabelledby, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_labelledby(value))
}
fn aria_live(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaLive, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_live(value))
}
fn aria_owns(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaOwns, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_owns(value))
}
fn aria_relevant(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaRelevant, V, Rndr>, Rndr>>::Output {
self.add_attr(aria_relevant(value))
}
fn aria_roledescription(
self,
value: V,
) -> <Self as AddAttribute<Attr<AriaRoledescription, V, Rndr>, Rndr>>::Output
{
self.add_attr(aria_roledescription(value))
}
}
impl<T, Rndr, V> AriaAttributes<Rndr, V> for T
where
T: AddAttribute<Attr<AriaAtomic, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaBusy, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaControls, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaCurrent, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDescribedby, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDescription, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDetails, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDisabled, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaDropeffect, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaErrormessage, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaFlowto, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaGrabbed, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaHaspopup, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaHidden, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaInvalid, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaKeyshortcuts, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLabel, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLabelledby, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaLive, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaOwns, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaRelevant, V, Rndr>, Rndr>
+ AddAttribute<Attr<AriaRoledescription, V, Rndr>, Rndr>,
V: AttributeValue<Rndr>,
Rndr: Renderer,
{
}

View file

@ -0,0 +1,147 @@
use super::global::AddAttribute;
use crate::{
html::attribute::{Attribute, AttributeValue},
renderer::DomRenderer,
view::{Position, ToTemplate},
};
use std::{borrow::Cow, marker::PhantomData, rc::Rc, sync::Arc};
#[inline(always)]
pub fn custom_attribute<K, V, R>(key: K, value: V) -> CustomAttr<K, V, R>
where
K: CustomAttributeKey,
V: AttributeValue<R>,
R: DomRenderer,
{
CustomAttr {
key,
value,
rndr: PhantomData,
}
}
pub struct CustomAttr<K, V, R>
where
K: CustomAttributeKey,
V: AttributeValue<R>,
R: DomRenderer,
{
key: K,
value: V,
rndr: PhantomData<R>,
}
impl<K, V, R> Attribute<R> for CustomAttr<K, V, R>
where
K: CustomAttributeKey,
V: AttributeValue<R>,
R: DomRenderer,
{
const MIN_LENGTH: usize = 0;
type State = V::State;
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
self.value.to_html(self.key.as_ref(), buf);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
if !K::KEY.is_empty() {
self.value.hydrate::<FROM_SERVER>(self.key.as_ref(), el)
} else {
self.value.build(el, self.key.as_ref())
}
}
fn build(self, el: &R::Element) -> Self::State {
self.value.build(el, self.key.as_ref())
}
fn rebuild(self, state: &mut Self::State) {
self.value.rebuild(self.key.as_ref(), state);
}
}
impl<K, V, R> ToTemplate for CustomAttr<K, V, R>
where
K: CustomAttributeKey,
V: AttributeValue<R>,
R: DomRenderer,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
if !K::KEY.is_empty() {
V::to_template(K::KEY, buf);
}
}
}
pub trait CustomAttributeKey: AsRef<str> {
const KEY: &'static str;
}
impl<'a> CustomAttributeKey for &'a str {
const KEY: &'static str = "";
}
impl<'a> CustomAttributeKey for Cow<'a, str> {
const KEY: &'static str = "";
}
impl CustomAttributeKey for &String {
const KEY: &'static str = "";
}
impl CustomAttributeKey for String {
const KEY: &'static str = "";
}
impl CustomAttributeKey for Rc<str> {
const KEY: &'static str = "";
}
impl CustomAttributeKey for Arc<str> {
const KEY: &'static str = "";
}
#[cfg(feature = "nightly")]
impl<const K: &'static str> CustomAttributeKey
for crate::view::static_types::Static<K>
{
const KEY: &'static str = K;
}
pub trait CustomAttribute<K, V, Rndr>
where
K: CustomAttributeKey,
V: AttributeValue<Rndr>,
Rndr: DomRenderer,
Self: Sized + AddAttribute<CustomAttr<K, V, Rndr>, Rndr>,
{
fn attr(
self,
key: K,
value: V,
) -> <Self as AddAttribute<CustomAttr<K, V, Rndr>, Rndr>>::Output {
self.add_attr(custom_attribute(key, value))
}
}
impl<T, K, V, Rndr> CustomAttribute<K, V, Rndr> for T
where
T: AddAttribute<CustomAttr<K, V, Rndr>, Rndr>,
K: CustomAttributeKey,
V: AttributeValue<Rndr>,
Rndr: DomRenderer,
{
}

View file

@ -0,0 +1,388 @@
use super::Lang;
use crate::{
html::{
attribute::*,
class::{class, Class, IntoClass},
event::{on, EventDescriptor, On},
property::{property, IntoProperty, Property},
style::{style, IntoStyle, Style},
},
renderer::DomRenderer,
};
use core::convert::From;
pub trait AddAttribute<NewAttr, Rndr>
where
Rndr: Renderer,
{
type Output;
fn add_attr(self, attr: NewAttr) -> Self::Output;
}
pub trait GlobalAttributes<Rndr, V>
where
Self: Sized
+ AddAttribute<Attr<Accesskey, V, Rndr>, Rndr>
+ AddAttribute<Attr<Autocapitalize, V, Rndr>, Rndr>
+ AddAttribute<Attr<Autofocus, V, Rndr>, Rndr>
+ AddAttribute<Attr<Contenteditable, V, Rndr>, Rndr>
+ AddAttribute<Attr<Dir, V, Rndr>, Rndr>
+ AddAttribute<Attr<Draggable, V, Rndr>, Rndr>
+ AddAttribute<Attr<Enterkeyhint, V, Rndr>, Rndr>
+ AddAttribute<Attr<Hidden, V, Rndr>, Rndr>
+ AddAttribute<Attr<Id, V, Rndr>, Rndr>
+ AddAttribute<Attr<Inert, V, Rndr>, Rndr>
+ AddAttribute<Attr<Inputmode, V, Rndr>, Rndr>
+ AddAttribute<Attr<Is, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemid, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemprop, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemref, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemscope, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemtype, V, Rndr>, Rndr>
+ AddAttribute<Attr<Lang, V, Rndr>, Rndr>
+ AddAttribute<Attr<Nonce, V, Rndr>, Rndr>
+ AddAttribute<Attr<Part, V, Rndr>, Rndr>
+ AddAttribute<Attr<Popover, V, Rndr>, Rndr>
+ AddAttribute<Attr<Role, V, Rndr>, Rndr>
+ AddAttribute<Attr<Slot, V, Rndr>, Rndr>
+ AddAttribute<Attr<Spellcheck, V, Rndr>, Rndr>
+ AddAttribute<Attr<Tabindex, V, Rndr>, Rndr>
+ AddAttribute<Attr<Title, V, Rndr>, Rndr>
+ AddAttribute<Attr<Translate, V, Rndr>, Rndr>
+ AddAttribute<Attr<Virtualkeyboardpolicy, V, Rndr>, Rndr>,
V: AttributeValue<Rndr>,
Rndr: Renderer,
{
fn accesskey(
self,
value: V,
) -> <Self as AddAttribute<Attr<Accesskey, V, Rndr>, Rndr>>::Output {
self.add_attr(accesskey(value))
}
fn autocapitalize(
self,
value: V,
) -> <Self as AddAttribute<Attr<Autocapitalize, V, Rndr>, Rndr>>::Output
{
self.add_attr(autocapitalize(value))
}
fn autofocus(
self,
value: V,
) -> <Self as AddAttribute<Attr<Autofocus, V, Rndr>, Rndr>>::Output {
self.add_attr(autofocus(value))
}
fn contenteditable(
self,
value: V,
) -> <Self as AddAttribute<Attr<Contenteditable, V, Rndr>, Rndr>>::Output
{
self.add_attr(contenteditable(value))
}
fn dir(
self,
value: V,
) -> <Self as AddAttribute<Attr<Dir, V, Rndr>, Rndr>>::Output {
self.add_attr(dir(value))
}
fn draggable(
self,
value: V,
) -> <Self as AddAttribute<Attr<Draggable, V, Rndr>, Rndr>>::Output {
self.add_attr(draggable(value))
}
fn enterkeyhint(
self,
value: V,
) -> <Self as AddAttribute<Attr<Enterkeyhint, V, Rndr>, Rndr>>::Output {
self.add_attr(enterkeyhint(value))
}
fn hidden(
self,
value: V,
) -> <Self as AddAttribute<Attr<Hidden, V, Rndr>, Rndr>>::Output {
self.add_attr(hidden(value))
}
fn id(
self,
value: V,
) -> <Self as AddAttribute<Attr<Id, V, Rndr>, Rndr>>::Output {
self.add_attr(id(value))
}
fn inert(
self,
value: V,
) -> <Self as AddAttribute<Attr<Inert, V, Rndr>, Rndr>>::Output {
self.add_attr(inert(value))
}
fn inputmode(
self,
value: V,
) -> <Self as AddAttribute<Attr<Inputmode, V, Rndr>, Rndr>>::Output {
self.add_attr(inputmode(value))
}
fn is(
self,
value: V,
) -> <Self as AddAttribute<Attr<Is, V, Rndr>, Rndr>>::Output {
self.add_attr(is(value))
}
fn itemid(
self,
value: V,
) -> <Self as AddAttribute<Attr<Itemid, V, Rndr>, Rndr>>::Output {
self.add_attr(itemid(value))
}
fn itemprop(
self,
value: V,
) -> <Self as AddAttribute<Attr<Itemprop, V, Rndr>, Rndr>>::Output {
self.add_attr(itemprop(value))
}
fn itemref(
self,
value: V,
) -> <Self as AddAttribute<Attr<Itemref, V, Rndr>, Rndr>>::Output {
self.add_attr(itemref(value))
}
fn itemscope(
self,
value: V,
) -> <Self as AddAttribute<Attr<Itemscope, V, Rndr>, Rndr>>::Output {
self.add_attr(itemscope(value))
}
fn itemtype(
self,
value: V,
) -> <Self as AddAttribute<Attr<Itemtype, V, Rndr>, Rndr>>::Output {
self.add_attr(itemtype(value))
}
fn lang(
self,
value: V,
) -> <Self as AddAttribute<Attr<Lang, V, Rndr>, Rndr>>::Output {
self.add_attr(lang(value))
}
fn nonce(
self,
value: V,
) -> <Self as AddAttribute<Attr<Nonce, V, Rndr>, Rndr>>::Output {
self.add_attr(nonce(value))
}
fn part(
self,
value: V,
) -> <Self as AddAttribute<Attr<Part, V, Rndr>, Rndr>>::Output {
self.add_attr(part(value))
}
fn popover(
self,
value: V,
) -> <Self as AddAttribute<Attr<Popover, V, Rndr>, Rndr>>::Output {
self.add_attr(popover(value))
}
fn role(
self,
value: V,
) -> <Self as AddAttribute<Attr<Role, V, Rndr>, Rndr>>::Output {
self.add_attr(role(value))
}
fn slot(
self,
value: V,
) -> <Self as AddAttribute<Attr<Slot, V, Rndr>, Rndr>>::Output {
self.add_attr(slot(value))
}
fn spellcheck(
self,
value: V,
) -> <Self as AddAttribute<Attr<Spellcheck, V, Rndr>, Rndr>>::Output {
self.add_attr(spellcheck(value))
}
fn tabindex(
self,
value: V,
) -> <Self as AddAttribute<Attr<Tabindex, V, Rndr>, Rndr>>::Output {
self.add_attr(tabindex(value))
}
fn title(
self,
value: V,
) -> <Self as AddAttribute<Attr<Title, V, Rndr>, Rndr>>::Output {
self.add_attr(title(value))
}
fn translate(
self,
value: V,
) -> <Self as AddAttribute<Attr<Translate, V, Rndr>, Rndr>>::Output {
self.add_attr(translate(value))
}
fn virtualkeyboardpolicy(
self,
value: V,
) -> <Self as AddAttribute<Attr<Virtualkeyboardpolicy, V, Rndr>, Rndr>>::Output{
self.add_attr(virtualkeyboardpolicy(value))
}
}
pub trait ClassAttribute<C, Rndr>
where
C: IntoClass<Rndr>,
Rndr: DomRenderer,
Self: Sized + AddAttribute<Class<C, Rndr>, Rndr>,
{
fn class(
self,
value: C,
) -> <Self as AddAttribute<Class<C, Rndr>, Rndr>>::Output {
self.add_attr(class(value))
}
}
pub trait PropAttribute<K, P, Rndr>
where
K: AsRef<str>,
P: IntoProperty<Rndr>,
Rndr: DomRenderer,
Self: Sized + AddAttribute<Property<K, P, Rndr>, Rndr>,
{
fn prop(
self,
key: K,
value: P,
) -> <Self as AddAttribute<Property<K, P, Rndr>, Rndr>>::Output {
self.add_attr(property(key, value))
}
}
pub trait StyleAttribute<S, Rndr>
where
S: IntoStyle<Rndr>,
Rndr: DomRenderer,
Self: Sized + AddAttribute<Style<S, Rndr>, Rndr>,
{
fn style(
self,
value: S,
) -> <Self as AddAttribute<Style<S, Rndr>, Rndr>>::Output {
self.add_attr(style(value))
}
}
pub trait OnAttribute<E, F, Rndr>
where
E: EventDescriptor + 'static,
E::EventType: 'static,
E::EventType: From<Rndr::Event>,
F: FnMut(E::EventType) + 'static,
Rndr: DomRenderer,
Self: Sized + AddAttribute<On<Rndr>, Rndr>,
{
fn on(
self,
event: E,
cb: F,
) -> <Self as AddAttribute<On<Rndr>, Rndr>>::Output
where {
self.add_attr(on(event, cb))
}
}
impl<T, Rndr, V> GlobalAttributes<Rndr, V> for T
where
T: AddAttribute<Attr<Accesskey, V, Rndr>, Rndr>
+ AddAttribute<Attr<Autocapitalize, V, Rndr>, Rndr>
+ AddAttribute<Attr<Autofocus, V, Rndr>, Rndr>
+ AddAttribute<Attr<Contenteditable, V, Rndr>, Rndr>
+ AddAttribute<Attr<Dir, V, Rndr>, Rndr>
+ AddAttribute<Attr<Draggable, V, Rndr>, Rndr>
+ AddAttribute<Attr<Enterkeyhint, V, Rndr>, Rndr>
+ AddAttribute<Attr<Hidden, V, Rndr>, Rndr>
+ AddAttribute<Attr<Id, V, Rndr>, Rndr>
+ AddAttribute<Attr<Inert, V, Rndr>, Rndr>
+ AddAttribute<Attr<Inputmode, V, Rndr>, Rndr>
+ AddAttribute<Attr<Is, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemid, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemprop, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemref, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemscope, V, Rndr>, Rndr>
+ AddAttribute<Attr<Itemtype, V, Rndr>, Rndr>
+ AddAttribute<Attr<Lang, V, Rndr>, Rndr>
+ AddAttribute<Attr<Nonce, V, Rndr>, Rndr>
+ AddAttribute<Attr<Part, V, Rndr>, Rndr>
+ AddAttribute<Attr<Popover, V, Rndr>, Rndr>
+ AddAttribute<Attr<Role, V, Rndr>, Rndr>
+ AddAttribute<Attr<Slot, V, Rndr>, Rndr>
+ AddAttribute<Attr<Spellcheck, V, Rndr>, Rndr>
+ AddAttribute<Attr<Tabindex, V, Rndr>, Rndr>
+ AddAttribute<Attr<Title, V, Rndr>, Rndr>
+ AddAttribute<Attr<Translate, V, Rndr>, Rndr>
+ AddAttribute<Attr<Virtualkeyboardpolicy, V, Rndr>, Rndr>,
V: AttributeValue<Rndr>,
Rndr: Renderer,
{
}
impl<T, C, Rndr> ClassAttribute<C, Rndr> for T
where
T: AddAttribute<Class<C, Rndr>, Rndr>,
C: IntoClass<Rndr>,
Rndr: DomRenderer,
{
}
impl<T, K, P, Rndr> PropAttribute<K, P, Rndr> for T
where
T: AddAttribute<Property<K, P, Rndr>, Rndr>,
K: AsRef<str>,
P: IntoProperty<Rndr>,
Rndr: DomRenderer,
{
}
impl<T, S, Rndr> StyleAttribute<S, Rndr> for T
where
T: AddAttribute<Style<S, Rndr>, Rndr>,
S: IntoStyle<Rndr>,
Rndr: DomRenderer,
{
}
impl<T, E, F, Rndr> OnAttribute<E, F, Rndr> for T
where
T: AddAttribute<On<Rndr>, Rndr>,
E: EventDescriptor + 'static,
E::EventType: 'static,
E::EventType: From<Rndr::Event>,
F: FnMut(E::EventType) + 'static,
Rndr: DomRenderer,
{
}

View file

@ -0,0 +1,307 @@
use super::{Attr, AttributeValue};
use crate::renderer::Renderer;
use std::{fmt::Debug, marker::PhantomData};
pub trait AttributeKey {
const KEY: &'static str;
}
macro_rules! attributes {
($($key:ident $html:literal),* $(,)?) => {
paste::paste! {
$(
pub fn $key<V, Rndr>(value: V) -> Attr<[<$key:camel>], V, Rndr>
where V: AttributeValue<Rndr>,
Rndr: Renderer
{
Attr([<$key:camel>], value, PhantomData)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct [<$key:camel>];
impl AttributeKey for [<$key:camel>] {
const KEY: &'static str = $html;
}
)*
}
}
}
// TODO attribute names with underscores should be kebab-cased
attributes! {
// HTML
abbr "abbr", // [],
accept_charset "accept-charset", // [],
accept "accept", // [],
accesskey "accesskey", // [], // [GlobalAttribute]
action "action", // [],
align "align", // [],
allow "allow", // [],
allowfullscreen "allowfullscreen", // [],
allowpaymentrequest "allowpaymentrequest", // [],
alt "alt", // [],
aria_atomic "aria-atomic", // [], // [GlobalAttribute] // [AriaAttribute],
aria_busy "aria-busy", // [], // [GlobalAttribute] // [AriaAttribute],
aria_controls "aria-controls", // [], // [GlobalAttribute] // [AriaAttribute],
aria_current "aria-current", // [], // [GlobalAttribute] // [AriaAttribute],
aria_describedby "aria-describedby", // [], // [GlobalAttribute] // [AriaAttribute],
aria_description "aria-description", // [], // [GlobalAttribute] // [AriaAttribute],
aria_details "aria-details", // [], // [GlobalAttribute] // [AriaAttribute],
aria_disabled "aria-disabled", // [], // [GlobalAttribute] // [AriaAttribute],
aria_dropeffect "aria-dropeffect", // [], // [GlobalAttribute] // [AriaAttribute],
aria_errormessage "aria-errormessage", // [], // [GlobalAttribute] // [AriaAttribute],
aria_flowto "aria-flowto", // [], // [GlobalAttribute] // [AriaAttribute],
aria_grabbed "aria-grabbed", // [], // [GlobalAttribute] // [AriaAttribute],
aria_haspopup "aria-haspopup", // [], // [GlobalAttribute] // [AriaAttribute],
aria_hidden "aria-hidden", // [], // [GlobalAttribute] // [AriaAttribute],
aria_invalid "aria-invalid", // [], // [GlobalAttribute] // [AriaAttribute],
aria_keyshortcuts "aria-keyshortcuts", // [], // [GlobalAttribute] // [AriaAttribute],
aria_label "aria-label", // [], // [GlobalAttribute] // [AriaAttribute],
aria_labelledby "aria-labelledby", // [], // [GlobalAttribute] // [AriaAttribute],
aria_live "aria-live", // [], // [GlobalAttribute] // [AriaAttribute],
aria_owns "aria-owns", // [], // [GlobalAttribute] // [AriaAttribute],
aria_relevant "aria-relevant", // [], // [GlobalAttribute] // [AriaAttribute],
aria_roledescription "aria-roledescription", // [], // [GlobalAttribute] // [AriaAttribute],
r#as "as", // [],
r#async "async", // [],
autocapitalize "autocapitalize", // [], // [GlobalAttribute]
autocomplete "autocomplete", // [],
autofocus "autofocus", // [], // [GlobalAttribute]
autoplay "autoplay", // [],
background "background", // [],
bgcolor "bgcolor", // [],
blocking "blocking", // [],
border "border", // [],
buffered "buffered", // [],
capture "capture", // [],
challenge "challenge", // [],
charset "charset", // [],
checked "checked", // [],
cite "cite", // [],
// class is handled in ../class.rs instead
//class "class", // [],
code "code", // [],
color "color", // [],
cols "cols", // [],
colspan "colspan", // [],
content "content", // [],
contenteditable "contenteditable", // [], // [GlobalAttribute]
contextmenu "contextmenu", // [], // [GlobalAttribute]
controls "controls", // [],
controlslist "controlslist", // [],
coords "coords", // [],
crossorigin "crossorigin", // [],
csp "csp", // [],
data "data", // [],
datetime "datetime", // [],
decoding "decoding", // [],
default "default", // [],
defer "defer", // [],
dir "dir", // [], // [GlobalAttribute]
dirname "dirname", // [],
disabled "disabled", // [],
disablepictureinpicture "disablepictureinpicture", // [],
disableremoteplayback "disableremoteplayback", // [],
download "download", // [],
draggable "draggable", // [], // [GlobalAttribute]
enctype "enctype", // [],
enterkeyhint "enterkeyhint", // [], // [GlobalAttribute]
exportparts "exportparts", // [], // [GlobalAttribute]
fetchpriority "fetchprioty", // [],
r#for "for", // [],
form "form", // [],
formaction "formaction", // [],
formenctype "formenctype", // [],
formmethod "formmethod", // [],
formnovalidate "formnovalidate", // [],
formtarget "formtarget", // [],
headers "headers", // [],
height "height", // [],
hidden "hidden", // [], // [GlobalAttribute]
high "high", // [],
href "href", // [],
hreflang "hreflang", // [],
http_equiv "http-equiv", // [],
icon "icon", // [],
id "id", // [], // [GlobalAttribute]
importance "importance", // [],
inert "inert", // [], // [GlobalAttribute]
inputmode "inputmode", // [], // [GlobalAttribute]
integrity "integrity", // [],
intrinsicsize "intrinsicsize", // [],
is "is", // [], // [GlobalAttribute]
ismap "ismap", // [],
itemid "itemid", // [], // [GlobalAttribute]
itemprop "itemprop", // [], // [GlobalAttribute]
itemref "itemref", // [], // [GlobalAttribute]
itemscope "itemscope", // [], // [GlobalAttribute]
itemtype "itemtype", // [], // [GlobalAttribute]
keytype "keytype", // [],
kind "kind", // [],
label "label", // [],
lang "lang", // [], // [GlobalAttribute]
language "language", // [],
list "list", // [],
loading "loading", // [],
r#loop "loop", // [],
low "low", // [],
manifest "manifest", // [],
max "max", // [],
maxlength "maxlength", // [],
media "media", // [],
method "method", // [],
min "min", // [],
minlength "minlength", // [],
multiple "multiple", // [],
muted "muted", // [],
name "name", // [],
nomodule "nomodule", // [],
nonce "nonce", // [], // [GlobalAttribute]
novalidate "novalidate", // [],
open "open", // [],
optimum "optimum", // [],
part "part", // [], // [GlobalAttribute]
pattern "pattern", // [],
ping "ping", // [],
placeholder "placeholder", // [],
playsinline "playsinline", // [],
popover "popover", // [], // [GlobalAttribute]
poster "poster", // [],
preload "preload", // [],
radiogroup "radiogroup", // [],
readonly "readonly", // [],
referrerpolicy "referrerpolicy", // [],
rel "rel", // [],
required "required", // [],
reversed "reversed", // [],
role "role", // [], // [GlobalAttribute] // [AriaAttribute],
rows "rows", // [],
rowspan "rowspan", // [],
sandbox "sandbox", // [],
scope "scope", // [],
scoped "scoped", // [],
selected "selected", // [],
shape "shape", // [],
size "size", // [],
sizes "sizes", // [],
slot "slot", // [], // [GlobalAttribute]
span "span", // [],
spellcheck "spellcheck", // [], // [GlobalAttribute]
src "src", // [],
srcdoc "srcdoc", // [],
srclang "srclang", // [],
srcset "srcset", // [],
start "start", // [],
step "step", // [],
// style is handled in ../style.rs instead
// style "style", // [],
summary "summary", // [],
tabindex "tabindex", // [], // [GlobalAttribute]
target "target", // [],
title "title", // [], // [GlobalAttribute]
translate "translate", // [], // [GlobalAttribute]
r#type "type", // [],
usemap "usemap", // [],
value "value", // [],
virtualkeyboardpolicy "virtualkeyboardpolicy", // [], // [GlobalAttribute]
width "width", // [],
wrap "wrap", // [],
// Event Handler Attributes
onabort "onabort", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onautocomplete "onautocomplete", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onautocompleteerror "onautocompleteerror", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onblur "onblur", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oncancel "oncancel", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oncanplay "oncanplay", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oncanplaythrough "oncanplaythrough", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onchange "onchange", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onclick "onclick", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onclose "onclose", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oncontextmenu "oncontextmenu", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oncuechange "oncuechange", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondblclick "ondblclick", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondrag "ondrag", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondragend "ondragend", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondragenter "ondragenter", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondragleave "ondragleave", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondragover "ondragover", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondragstart "ondragstart", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondrop "ondrop", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ondurationchange "ondurationchange", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onemptied "onemptied", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onended "onended", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onerror "onerror", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onfocus "onfocus", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oninput "oninput", // [], // [GlobalAttribute] // [EventHandlerAttribute],
oninvalid "oninvalid", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onkeydown "onkeydown", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onkeypress "onkeypress", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onkeyup "onkeyup", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onload "onload", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onloadeddata "onloadeddata", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onloadedmetadata "onloadedmetadata", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onloadstart "onloadstart", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmousedown "onmousedown", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmouseenter "onmouseenter", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmouseleave "onmouseleave", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmousemove "onmousemove", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmouseout "onmouseout", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmouseover "onmouseover", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmouseup "onmouseup", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onmousewheel "onmousewheel", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onpause "onpause", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onplay "onplay", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onplaying "onplaying", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onprogress "onprogress", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onratechange "onratechange", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onreset "onreset", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onresize "onresize", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onscroll "onscroll", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onseeked "onseeked", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onseeking "onseeking", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onselect "onselect", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onshow "onshow", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onsort "onsort", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onstalled "onstalled", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onsubmit "onsubmit", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onsuspend "onsuspend", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ontimeupdate "ontimeupdate", // [], // [GlobalAttribute] // [EventHandlerAttribute],
ontoggle "ontoggle", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onvolumechange "onvolumechange", // [], // [GlobalAttribute] // [EventHandlerAttribute],
onwaiting "onwaiting", // [], // [GlobalAttribute] // [EventHandlerAttribute],
// MathML attributes that aren't in HTML
accent "accent",
accentunder "accentunder",
columnalign "columnalign",
columnlines "columnlines",
columnspacing "columnspacing",
columnspan "columnspan",
depth "depth",
display "display",
displaystyle "displaystyle",
fence "fence",
frame "frame",
framespacing "framespacing",
linethickness "linethickness",
lspace "lspace",
mathbackground "mathbackground",
mathcolor "mathcolor",
mathsize "mathsize",
mathvariant "mathvariant",
maxsize "maxsize",
minsize "minsize",
movablelimits "movablelimits",
notation "notation",
rowalign "rowalign",
rowlines "rowlines",
rowspacing "rowspacing",
rspace "rspace",
scriptlevel "scriptlevel",
separator "separator",
stretchy "stretchy",
symmetric "symmetric",
voffset "voffset",
xmlns "xmlns",
}

View file

@ -0,0 +1,242 @@
pub mod aria;
pub mod custom;
pub mod global;
mod key;
mod value;
use crate::{
renderer::Renderer,
view::{Position, ToTemplate},
};
pub use key::*;
use std::{fmt::Debug, marker::PhantomData};
pub use value::*;
pub trait Attribute<R: Renderer> {
const MIN_LENGTH: usize;
type State;
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
);
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State;
fn build(self, el: &R::Element) -> Self::State;
fn rebuild(self, state: &mut Self::State);
}
impl<R> Attribute<R> for ()
where
R: Renderer,
{
const MIN_LENGTH: usize = 0;
type State = ();
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
fn hydrate<const FROM_SERVER: bool>(self, _el: &R::Element) -> Self::State {
}
fn build(self, _el: &R::Element) -> Self::State {}
fn rebuild(self, _state: &mut Self::State) {}
}
#[derive(Debug)]
pub struct Attr<K, V, R>(pub K, pub V, PhantomData<R>)
where
K: AttributeKey,
V: AttributeValue<R>,
R: Renderer;
impl<K, V, R> ToTemplate for Attr<K, V, R>
where
K: AttributeKey,
V: AttributeValue<R>,
R: Renderer,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
V::to_template(K::KEY, buf);
}
}
impl<K, V, R> Attribute<R> for Attr<K, V, R>
where
K: AttributeKey,
V: AttributeValue<R>,
R: Renderer,
{
const MIN_LENGTH: usize = 0;
type State = V::State;
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
self.1.to_html(K::KEY, buf);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
self.1.hydrate::<FROM_SERVER>(K::KEY, el)
}
fn build(self, el: &R::Element) -> Self::State {
V::build(self.1, el, K::KEY)
}
fn rebuild(self, state: &mut Self::State) {
V::rebuild(self.1, K::KEY, state);
}
}
macro_rules! impl_attr_for_tuples {
($first:ident, $($ty:ident),* $(,)?) => {
impl<$first, $($ty),*, Rndr> Attribute<Rndr> for ($first, $($ty,)*)
where
$first: Attribute<Rndr>,
$($ty: Attribute<Rndr>),*,
Rndr: Renderer
{
const MIN_LENGTH: usize = $first::MIN_LENGTH $(+ $ty::MIN_LENGTH)*;
type State = ($first::State, $($ty::State,)*);
fn to_html(self, buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String,) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)* ) = self;
[<$first:lower>].to_html(buf, class, style, inner_html);
$([<$ty:lower>].to_html(buf, class, style, inner_html));*
}
}
fn hydrate<const FROM_SERVER: bool>(self, el: &Rndr::Element) -> Self::State {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)* ) = self;
(
[<$first:lower>].hydrate::<FROM_SERVER>(el),
$([<$ty:lower>].hydrate::<FROM_SERVER>(el)),*
)
}
}
fn build(self, el: &Rndr::Element) -> Self::State {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
(
[<$first:lower>].build(el),
$([<$ty:lower>].build(el)),*
)
}
}
fn rebuild(self, state: &mut Self::State) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].rebuild([<view_ $first:lower>]);
$([<$ty:lower>].rebuild([<view_ $ty:lower>]));*
}
}
}
};
}
impl<A, Rndr> Attribute<Rndr> for (A,)
where
A: Attribute<Rndr>,
Rndr: Renderer,
{
const MIN_LENGTH: usize = A::MIN_LENGTH;
type State = A::State;
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
self.0.to_html(buf, class, style, inner_html);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &Rndr::Element,
) -> Self::State {
self.0.hydrate::<FROM_SERVER>(el)
}
fn build(self, el: &Rndr::Element) -> Self::State {
self.0.build(el)
}
fn rebuild(self, state: &mut Self::State) {
self.0.rebuild(state);
}
}
impl_attr_for_tuples!(A, B);
impl_attr_for_tuples!(A, B, C);
impl_attr_for_tuples!(A, B, C, D);
impl_attr_for_tuples!(A, B, C, D, E);
impl_attr_for_tuples!(A, B, C, D, E, F);
impl_attr_for_tuples!(A, B, C, D, E, F, G);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);

View file

@ -0,0 +1,299 @@
use crate::renderer::Renderer;
use std::borrow::Cow;
pub trait AttributeValue<R: Renderer> {
type State;
fn to_html(self, key: &str, buf: &mut String);
fn to_template(key: &str, buf: &mut String);
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State;
fn build(self, el: &R::Element, key: &str) -> Self::State;
fn rebuild(self, key: &str, state: &mut Self::State);
}
impl<R> AttributeValue<R> for ()
where
R: Renderer,
{
type State = ();
fn to_html(self, _key: &str, _buf: &mut String) {}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(self, _key: &str, _el: &R::Element) {}
fn build(self, _el: &R::Element, _key: &str) -> Self::State {}
fn rebuild(self, _key: &str, _state: &mut Self::State) {}
}
impl<'a, R> AttributeValue<R> for &'a str
where
R: Renderer,
R::Element: Clone,
{
type State = (R::Element, &'a str);
fn to_html(self, key: &str, buf: &mut String) {
buf.push(' ');
buf.push_str(key);
buf.push_str("=\"");
buf.push_str(&escape_attr(self));
buf.push('"');
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
R::set_attribute(el, key, self);
}
(el.clone(), self)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
R::set_attribute(el, key, self);
(el.to_owned(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
R::set_attribute(el, key, self);
}
*prev_value = self;
}
}
#[cfg(feature = "nightly")]
impl<R, const V: &'static str> AttributeValue<R>
for crate::view::static_types::Static<V>
where
R::Element: Clone,
R: Renderer,
{
type State = ();
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue<R>>::to_html(V, key, buf);
}
fn to_template(key: &str, buf: &mut String) {
buf.push(' ');
buf.push_str(key);
buf.push_str("=\"");
buf.push_str(&escape_attr(V));
buf.push('"');
}
fn hydrate<const FROM_SERVER: bool>(
self,
_key: &str,
_el: &R::Element,
) -> Self::State {
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
<&str as AttributeValue<R>>::build(V, el, key);
}
fn rebuild(self, _key: &str, _state: &mut Self::State) {}
}
impl<'a, R> AttributeValue<R> for &'a String
where
R: Renderer,
R::Element: Clone,
{
type State = (R::Element, &'a String);
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue<R>>::to_html(self.as_str(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State {
let (el, _) = <&str as AttributeValue<R>>::hydrate::<FROM_SERVER>(
self.as_str(),
key,
el,
);
(el, self)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
R::set_attribute(el, key, self);
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
R::set_attribute(el, key, self);
}
*prev_value = self;
}
}
impl<R> AttributeValue<R> for String
where
R: Renderer,
R::Element: Clone,
{
type State = (R::Element, String);
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue<R>>::to_html(self.as_str(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State {
let (el, _) = <&str as AttributeValue<R>>::hydrate::<FROM_SERVER>(
self.as_str(),
key,
el,
);
(el, self)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
R::set_attribute(el, key, &self);
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
R::set_attribute(el, key, &self);
}
*prev_value = self;
}
}
impl<R> AttributeValue<R> for bool
where
R: Renderer,
R::Element: Clone,
{
type State = (R::Element, bool);
fn to_html(self, key: &str, buf: &mut String) {
if self {
buf.push(' ');
buf.push_str(key);
}
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
R::set_attribute(el, key, "");
}
(el.clone(), self)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
if self {
R::set_attribute(el, key, "");
}
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
if self {
R::set_attribute(el, key, "");
} else {
R::remove_attribute(el, key);
}
}
*prev_value = self;
}
}
impl<V, R> AttributeValue<R> for Option<V>
where
V: AttributeValue<R>,
R: Renderer,
R::Element: Clone,
{
type State = (R::Element, Option<V::State>);
fn to_html(self, key: &str, buf: &mut String) {
if let Some(v) = self {
v.to_html(key, buf);
}
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &R::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
let state = if !FROM_SERVER {
self.map(|v| v.hydrate::<FROM_SERVER>(key, el))
} else {
None
};
(el.clone(), state)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
let el = el.clone();
let v = self.map(|v| v.build(&el, key));
(el, v)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev) = state;
match (self, prev.as_mut()) {
(None, None) => {}
(None, Some(_)) => R::remove_attribute(el, key),
(Some(value), None) => {
*prev = Some(value.build(el, key));
}
(Some(new), Some(old)) => new.rebuild(key, old),
}
}
}
// TODO
fn escape_attr(value: &str) -> Cow<'_, str> {
value.into()
}

280
tachys/src/html/class.rs Normal file
View file

@ -0,0 +1,280 @@
use super::attribute::Attribute;
use crate::{
renderer::DomRenderer,
view::{Position, ToTemplate},
};
use std::marker::PhantomData;
#[inline(always)]
pub fn class<C, R>(class: C) -> Class<C, R>
where
C: IntoClass<R>,
R: DomRenderer,
{
Class {
class,
rndr: PhantomData,
}
}
pub struct Class<C, R>
where
C: IntoClass<R>,
R: DomRenderer,
{
class: C,
rndr: PhantomData<R>,
}
impl<C, R> Attribute<R> for Class<C, R>
where
C: IntoClass<R>,
R: DomRenderer,
{
const MIN_LENGTH: usize = C::MIN_LENGTH;
type State = C::State;
fn to_html(
self,
_buf: &mut String,
class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
class.push(' ');
self.class.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
self.class.hydrate::<FROM_SERVER>(el)
}
fn build(self, el: &R::Element) -> Self::State {
self.class.build(el)
}
fn rebuild(self, state: &mut Self::State) {
self.class.rebuild(state)
}
}
impl<C, R> ToTemplate for Class<C, R>
where
C: IntoClass<R>,
R: DomRenderer,
{
const CLASS: &'static str = C::TEMPLATE;
fn to_template(
_buf: &mut String,
class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
C::to_template(class);
}
}
pub trait IntoClass<R: DomRenderer> {
const TEMPLATE: &'static str = "";
const MIN_LENGTH: usize = Self::TEMPLATE.len();
type State;
fn to_html(self, class: &mut String);
#[allow(unused)] // it's used with `nightly` feature
fn to_template(class: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State;
fn build(self, el: &R::Element) -> Self::State;
fn rebuild(self, state: &mut Self::State);
}
impl<'a, R> IntoClass<R> for &'a str
where
R: DomRenderer,
R::Element: Clone,
{
type State = (R::Element, &'a str);
fn to_html(self, class: &mut String) {
class.push_str(self);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
if !FROM_SERVER {
R::set_attribute(el, "class", self);
}
(el.clone(), self)
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, "class", self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self != *prev {
R::set_attribute(el, "class", self);
}
*prev = self;
}
}
impl<R> IntoClass<R> for String
where
R: DomRenderer,
R::Element: Clone,
{
type State = (R::Element, String);
fn to_html(self, class: &mut String) {
IntoClass::<R>::to_html(self.as_str(), class);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
if !FROM_SERVER {
R::set_attribute(el, "class", &self);
}
(el.clone(), self)
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, "class", &self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self != *prev {
R::set_attribute(el, "class", &self);
}
*prev = self;
}
}
impl<R> IntoClass<R> for (&'static str, bool)
where
R: DomRenderer,
{
type State = (R::ClassList, bool);
fn to_html(self, class: &mut String) {
let (name, include) = self;
if include {
class.push_str(name);
}
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let (name, include) = self;
let class_list = R::class_list(el);
if !FROM_SERVER && include {
R::add_class(&class_list, name);
}
(class_list, self.1)
}
fn build(self, el: &R::Element) -> Self::State {
let (name, include) = self;
let class_list = R::class_list(el);
if include {
R::add_class(&class_list, name);
}
(class_list, self.1)
}
fn rebuild(self, state: &mut Self::State) {
let (name, include) = self;
let (class_list, prev_include) = state;
if include != *prev_include {
if include {
R::add_class(class_list, name);
} else {
R::remove_class(class_list, name);
}
}
*prev_include = include;
}
}
#[cfg(feature = "nightly")]
impl<R, const V: &'static str> IntoClass<R>
for crate::view::static_types::Static<V>
where
R: DomRenderer,
{
const TEMPLATE: &'static str = V;
type State = ();
fn to_html(self, class: &mut String) {
class.push_str(V);
}
fn to_template(class: &mut String) {
class.push_str(V);
}
fn hydrate<const FROM_SERVER: bool>(self, _el: &R::Element) -> Self::State {
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, "class", V);
}
fn rebuild(self, _state: &mut Self::State) {}
}
/* #[cfg(test)]
mod tests {
use crate::{
html::{
class::class,
element::{p, HtmlElement},
},
renderer::dom::Dom,
view::{Position, PositionState, RenderHtml},
};
#[test]
fn adds_simple_class() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> = p(class("foo bar"), ());
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(html, r#"<p class="foo bar"></p>"#);
}
#[test]
fn adds_class_with_dynamic() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> =
p((class("foo bar"), class(("baz", true))), ());
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(html, r#"<p class="foo bar baz"></p>"#);
}
#[test]
fn adds_class_with_dynamic_and_function() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> = p(
(
class("foo bar"),
class(("baz", || true)),
class(("boo", false)),
),
(),
);
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(html, r#"<p class="foo bar baz"></p>"#);
}
} */

View file

@ -0,0 +1,90 @@
use super::ElementWithChildren;
use crate::{
html::element::{CreateElement, ElementType, HtmlElement},
renderer::{dom::Dom, Renderer},
};
use std::{borrow::Cow, fmt::Debug, marker::PhantomData, rc::Rc, sync::Arc};
// FIXME custom element HTML rendering is broken because tag names aren't static
pub fn custom<E, Rndr>(tag: E) -> HtmlElement<Custom<E>, (), (), Rndr>
where
E: CustomElementKey,
Rndr: Renderer,
{
HtmlElement {
tag: Custom(tag),
rndr: PhantomData,
attributes: (),
children: (),
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Custom<E>(E)
where
E: CustomElementKey;
impl<E> ElementType for Custom<E>
where
E: CustomElementKey,
{
type Output = web_sys::HtmlElement;
const TAG: &'static str = E::KEY;
const SELF_CLOSING: bool = false;
fn tag(&self) -> &str {
self.0.as_ref()
}
}
impl<E> ElementWithChildren for Custom<E> where E: CustomElementKey {}
impl<E> CreateElement<Dom> for Custom<E>
where
E: CustomElementKey,
{
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::intern;
crate::dom::document()
.create_element(intern(self.0.as_ref()))
.unwrap()
}
}
// TODO these are all broken for custom elements
pub trait CustomElementKey: AsRef<str> {
const KEY: &'static str;
}
impl<'a> CustomElementKey for &'a str {
const KEY: &'static str = "";
}
impl<'a> CustomElementKey for Cow<'a, str> {
const KEY: &'static str = "";
}
impl CustomElementKey for &String {
const KEY: &'static str = "";
}
impl CustomElementKey for String {
const KEY: &'static str = "";
}
impl CustomElementKey for Rc<str> {
const KEY: &'static str = "";
}
impl CustomElementKey for Arc<str> {
const KEY: &'static str = "";
}
#[cfg(feature = "nightly")]
impl<const K: &'static str> CustomElementKey
for crate::view::static_types::Static<K>
{
const KEY: &'static str = K;
}

View file

@ -0,0 +1,455 @@
use crate::{
html::{
attribute::{Attr, Attribute, AttributeValue},
element::{
CreateElement, ElementType, ElementWithChildren, HtmlElement,
},
},
renderer::{dom::Dom, Renderer},
view::Render,
};
use next_tuple::TupleBuilder;
use once_cell::unsync::Lazy;
use std::{fmt::Debug, marker::PhantomData};
macro_rules! html_elements {
($(
#[$meta:meta]
$tag:ident $ty:ident [$($attr:ty),*]
),*
$(,)?
) => {
paste::paste! {
$(
#[$meta]
pub fn $tag<Rndr>() -> HtmlElement<[<$tag:camel>], (), (), Rndr>
where
Rndr: Renderer
{
HtmlElement {
tag: [<$tag:camel>],
attributes: (),
children: (),
rndr: PhantomData,
}
}
#[$meta]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct [<$tag:camel>];
// Typed attribute methods
impl<At, Ch, Rndr> HtmlElement<[<$tag:camel>], At, Ch, Rndr>
where
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
$(
#[doc = concat!("The [`", stringify!($attr), "`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($tag), "#", stringify!($attr) ,") attribute on `<", stringify!($tag), ">`.")]
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
Ch, Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
)*
}
impl ElementType for [<$tag:camel>] {
type Output = web_sys::$ty;
const TAG: &'static str = stringify!($tag);
const SELF_CLOSING: bool = false;
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl ElementWithChildren for [<$tag:camel>] {}
impl CreateElement<Dom> for [<$tag:camel>] {
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::JsCast;
thread_local! {
static ELEMENT: Lazy<<Dom as Renderer>::Element> = Lazy::new(|| {
crate::dom::document().create_element(stringify!($tag)).unwrap()
});
}
ELEMENT.with(|e| e.clone_node()).unwrap().unchecked_into()
}
}
)*
}
}
}
macro_rules! html_self_closing_elements {
($(
#[$meta:meta]
$tag:ident $ty:ident [$($attr:ty),*]
),*
$(,)?
) => {
paste::paste! {
$(
#[$meta]
pub fn $tag<Rndr>() -> HtmlElement<[<$tag:camel>], (), (), Rndr>
where
Rndr: Renderer
{
HtmlElement {
attributes: (),
children: (),
rndr: PhantomData,
tag: [<$tag:camel>]
}
}
#[$meta]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct [<$tag:camel>];
// Typed attribute methods
impl<At, Rndr> HtmlElement<[<$tag:camel>], At, (), Rndr>
where
At: Attribute<Rndr>,
Rndr: Renderer,
{
$(
#[doc = concat!("The [`", stringify!($attr), "`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($tag), "#", stringify!($attr) ,") attribute on `<", stringify!($tag), ">`.")]
pub fn $attr<V>(self, value: V) -> HtmlElement<
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
(),
Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
)*
}
impl ElementType for [<$tag:camel>] {
type Output = web_sys::$ty;
const TAG: &'static str = stringify!($tag);
const SELF_CLOSING: bool = true;
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl CreateElement<Dom> for [<$tag:camel>] {
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::JsCast;
thread_local! {
static ELEMENT: Lazy<<Dom as Renderer>::Element> = Lazy::new(|| {
crate::dom::document().create_element(stringify!($tag)).unwrap()
});
}
ELEMENT.with(|e| e.clone_node()).unwrap().unchecked_into()
}
}
)*
}
}
}
html_self_closing_elements! {
/// The `<area>` HTML element defines an area inside an image map that has predefined clickable areas. An image map allows geometric areas on an image to be associated with Hyperlink.
area HtmlAreaElement [alt, coords, download, href, hreflang, ping, rel, shape, target],
/// The `<base>` HTML element specifies the base URL to use for all relative URLs in a document. There can be only one `<base>` element in a document.
base HtmlBaseElement [href, target],
/// The `<br>` HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
br HtmlBrElement [],
/// The `<col>` HTML element defines a column within a table and is used for defining common semantics on all common cells. It is generally found within a colgroup element.
col HtmlTableColElement [span],
/// The `<embed>` HTML element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in.
embed HtmlEmbedElement [height, src, r#type, width],
/// The `<hr>` HTML element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
hr HtmlHrElement [],
/// The `<img>` HTML element embeds an image into the document.
img HtmlImageElement [alt, crossorigin, decoding, height, ismap, sizes, src, srcset, usemap, width],
/// The `<input>` HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The `<input>` element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
input HtmlInputElement [accept, alt, autocomplete, capture, checked, disabled, form, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, name, pattern, placeholder, readonly, required, size, src, step, r#type, value, width],
/// The `<link>` HTML element specifies relationships between the current document and an external resource. This element is most commonly used to link to CSS, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things.
link HtmlLinkElement [r#as, crossorigin, href, hreflang, media, rel, sizes, r#type],
/// The `<meta>` HTML element represents Metadata that cannot be represented by other HTML meta-related elements, like base, link, script, style or title.
meta HtmlMetaElement [charset, content, http_equiv, name],
/// The `<source>` HTML element specifies multiple media resources for the picture, the audio element, or the video element. It is an empty element, meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for image file formats and media file formats.
source HtmlSourceElement [src, r#type],
/// The `<track>` HTML element is used as a child of the media elements, audio and video. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in WebVTT format (.vtt files) — Web Video Text Tracks.
track HtmlTrackElement [default, kind, label, src, srclang],
/// The `<wbr>` HTML element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.
wbr HtmlElement []
}
html_elements! {
/// The `<a>` HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
a HtmlAnchorElement [download, href, hreflang, ping, rel, target, r#type ],
/// The `<abbr>` HTML element represents an abbreviation or acronym; the optional title attribute can provide an expansion or description for the abbreviation. If present, title must contain this full description and nothing else.
abbr HtmlElement [],
/// The `<address>` HTML element indicates that the enclosed HTML provides contact information for a person or people, or for an organization.
address HtmlElement [],
/// The `<article>` HTML element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
article HtmlElement [],
/// The `<aside>` HTML element represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes.
aside HtmlElement [],
/// The `<audio>` HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the source element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream.
audio HtmlAudioElement [autoplay, controls, crossorigin, r#loop, muted, preload, src],
/// The `<b>` HTML element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use `<b>` for styling text; instead, you should use the CSS font-weight property to create boldface text, or the strong element to indicate that text is of special importance.
b HtmlElement [],
/// The `<bdi>` HTML element tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted.
bdi HtmlElement [],
/// The `<bdo>` HTML element overrides the current directionality of text, so that the text within is rendered in a different direction.
bdo HtmlElement [],
/// The `<blockquote>` HTML element indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the cite element.
blockquote HtmlQuoteElement [cite],
/// The `<body>` HTML element represents the content of an HTML document. There can be only one `<body>` element in a document.
body HtmlBodyElement [],
/// The `<button>` HTML element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality.
button HtmlButtonElement [disabled, form, formaction, formenctype, formmethod, formnovalidate, formtarget, name, r#type, value],
/// Use the HTML `<canvas>` element with either the canvas scripting API or the WebGL API to draw graphics and animations.
canvas HtmlCanvasElement [height, width],
/// The `<caption>` HTML element specifies the caption (or title) of a table.
caption HtmlTableCaptionElement [],
/// The `<cite>` HTML element is used to describe a reference to a cited creative work, and must include the title of that work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata.
cite HtmlElement [],
/// The `<code>` HTML element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent default monospace font.
code HtmlElement [],
/// The `<colgroup>` HTML element defines a group of columns within a table.
colgroup HtmlTableColElement [span],
/// The `<data>` HTML element links a given piece of content with a machine-readable translation. If the content is time- or date-related, the time element must be used.
data HtmlDataElement [value],
/// The `<datalist>` HTML element contains a set of option elements that represent the permissible or recommended options available to choose from within other controls.
datalist HtmlDataListElement [],
/// The `<dd>` HTML element provides the description, definition, or value for the preceding term (dt) in a description list (dl).
dd HtmlElement [],
/// The `<del>` HTML element represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The ins element can be used for the opposite purpose: to indicate text that has been added to the document.
del HtmlModElement [cite, datetime],
/// The `<details>` HTML element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the summary element.
details HtmlDetailsElement [open],
/// The `<dfn>` HTML element is used to indicate the term being defined within the context of a definition phrase or sentence. The p element, the dt/dd pairing, or the section element which is the nearest ancestor of the `<dfn>` is considered to be the definition of the term.
dfn HtmlElement [],
/// The `<dialog>` HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.
dialog HtmlDialogElement [open],
/// The `<div>` HTML element is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like Flexbox is applied to its parent element).
div HtmlDivElement [],
/// The `<dl>` HTML element represents a description list. The element encloses a list of groups of terms (specified using the dt element) and descriptions (provided by dd elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).
dl HtmlDListElement [],
/// The `<dt>` HTML element specifies a term in a description or definition list, and as such must be used inside a dl element. It is usually followed by a dd element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next dd element.
dt HtmlElement [],
/// The `<em>` HTML element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis.
em HtmlElement [],
/// The `<fieldset>` HTML element is used to group several controls as well as labels (label) within a web form.
fieldset HtmlFieldSetElement [],
/// The `<figcaption>` HTML element represents a caption or legend describing the rest of the contents of its parent figure element.
figcaption HtmlElement [],
/// The `<figure>` HTML element represents self-contained content, potentially with an optional caption, which is specified using the figcaption element. The figure, its caption, and its contents are referenced as a single unit.
figure HtmlElement [],
/// The `<footer>` HTML element represents a footer for its nearest sectioning content or sectioning root element. A `<footer>` typically contains information about the author of the section, copyright data or links to related documents.
footer HtmlElement [],
/// The `<form>` HTML element represents a document section containing interactive controls for submitting information.
form HtmlFormElement [accept_charset, action, autocomplete, enctype, method, name, novalidate, target],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h1 HtmlHeadingElement [],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h2 HtmlHeadingElement [],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h3 HtmlHeadingElement [],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h4 HtmlHeadingElement [],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h5 HtmlHeadingElement [],
/// The `<h1>` to `<h6>` HTML elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest.
h6 HtmlHeadingElement [],
/// The `<head>` HTML element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets.
head HtmlHeadElement [],
/// The `<header>` HTML element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements.
header HtmlElement [],
/// The `<hgroup>` HTML element represents a heading and related content. It groups a single `<h1><h6>` element with one or more `<p>`.
hgroup HtmlElement [],
/// The `<html>` HTML element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element.
html HtmlHtmlElement [],
/// The `<i>` HTML element represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element.
i HtmlElement [],
/// The `<iframe>` HTML element represents a nested browsing context, embedding another HTML page into the current one.
iframe HtmlIFrameElement [allow, allowfullscreen, allowpaymentrequest, height, name, referrerpolicy, sandbox, src, srcdoc, width],
/// The `<ins>` HTML element represents a range of text that has been added to a document. You can use the del element to similarly represent a range of text that has been deleted from the document.
ins HtmlElement [cite, datetime],
/// The `<kbd>` HTML element represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the user agent defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard.
kbd HtmlElement [],
/// The `<label>` HTML element represents a caption for an item in a user interface.
label HtmlLabelElement [r#for, form],
/// The `<legend>` HTML element represents a caption for the content of its parent fieldset.
legend HtmlLegendElement [],
/// The `<li>` HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list (ol), an unordered list (ul), or a menu (menu). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter.
li HtmlLiElement [value],
/// The `<main>` HTML element represents the dominant content of the body of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.
main HtmlElement [],
/// The `<map>` HTML element is used with area elements to define an image map (a clickable link area).
map HtmlMapElement [name],
/// The `<mark>` HTML element represents text which is marked or highlighted for reference or notation purposes, due to the marked passage's relevance or importance in the enclosing context.
mark HtmlElement [],
/// The `<menu>` HTML element is a semantic alternative to ul. It represents an unordered list of items (represented by li elements), each of these represent a link or other command that the user can activate.
menu HtmlMenuElement [],
/// The `<meter>` HTML element represents either a scalar value within a known range or a fractional value.
meter HtmlMeterElement [value, min, max, low, high, optimum, form],
/// The `<nav>` HTML element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.
nav HtmlElement [],
/// The `<noscript>` HTML element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.
noscript HtmlElement [],
/// The `<object>` HTML element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
object HtmlObjectElement [data, form, height, name, r#type, usemap, width],
/// The `<ol>` HTML element represents an ordered list of items — typically rendered as a numbered list.
ol HtmlOListElement [reversed, start, r#type],
/// The `<optgroup>` HTML element creates a grouping of options within a select element.
optgroup HtmlOptGroupElement [disabled, label],
/// The `<output>` HTML element is a container element into which a site or app can inject the results of a calculation or the outcome of a user action.
output HtmlOutputElement [r#for, form, name],
/// The `<p>` HTML element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields.
p HtmlParagraphElement [],
/// The `<picture>` HTML element contains zero or more source elements and one img element to offer alternative versions of an image for different display/device scenarios.
picture HtmlPictureElement [],
/// The `<portal>` HTML element enables the embedding of another HTML page into the current one for the purposes of allowing smoother navigation into new pages.
portal HtmlElement [referrerpolicy, src],
/// The `<pre>` HTML element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or "monospaced, font. Whitespace inside this element is displayed as written.
pre HtmlPreElement [],
/// The `<progress>` HTML element displays an indicator showing the completion progress of a task, typically displayed as a progress bar.
progress HtmlProgressElement [max, value],
/// The `<q>` HTML element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the blockquote element.
q HtmlQuoteElement [cite],
/// The `<rp>` HTML element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the ruby element. One `<rp>` element should enclose each of the opening and closing parentheses that wrap the rt element that contains the annotation's text.
rp HtmlElement [],
/// The `<rt>` HTML element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The `<rt>` element must always be contained within a ruby element.
rt HtmlElement [],
/// The `<ruby>` HTML element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common.
ruby HtmlElement [],
/// The `<s>` HTML element renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the del and ins elements, as appropriate.
s HtmlElement [],
/// The `<samp>` HTML element is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as Courier or Lucida Console).
samp HtmlElement [],
/// The `<script>` HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.
script HtmlScriptElement [r#async, crossorigin, defer, fetchpriority, integrity, nomodule, referrerpolicy, src, r#type, blocking],
/// The `<search>` HTML element is a container representing the parts of the document or application with form controls or other content related to performing a search or filtering operation.
search HtmlElement [],
/// The `<section>` HTML element represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions.
section HtmlElement [],
/// The `<select>` HTML element represents a control that provides a menu of options:
select HtmlSelectElement [autocomplete, disabled, form, multiple, name, required, size],
/// The `<slot>` HTML element—part of the Web Components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.
slot HtmlSlotElement [name],
/// The `<small>` HTML element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from small to x-small.
small HtmlElement [],
/// The `<span>` HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. `<span>` is very much like a div element, but div is a block-level element whereas a `<span>` is an inline element.
span HtmlSpanElement [],
/// The `<strong>` HTML element indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type.
strong HtmlElement [],
/// The `<style>` HTML element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the `<style>` element.
style HtmlStyleElement [media, blocking],
/// The `<sub>` HTML element specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text.
sub HtmlElement [],
/// The `<summary>` HTML element specifies a summary, caption, or legend for a details element's disclosure box. Clicking the `<summary>` element toggles the state of the parent `<details>` element open and closed.
summary HtmlElement [],
/// The `<sup>` HTML element specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text.
sup HtmlElement [],
/// The `<table>` HTML element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data.
table HtmlTableElement [],
/// The `<tbody>` HTML element encapsulates a set of table rows (tr elements), indicating that they comprise the body of the table (table).
tbody HtmlTableSectionElement [],
/// The `<td>` HTML element defines a cell of a table that contains data. It participates in the table model.
td HtmlTableCellElement [colspan, headers, rowspan],
/// The `<template>` HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript.
template HtmlTemplateElement [],
/// The `<textarea>` HTML element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form.
textarea HtmlTextAreaElement [autocomplete, cols, dirname, disabled, form, maxlength, minlength, name, placeholder, readonly, required, rows, wrap],
/// The `<tfoot>` HTML element defines a set of rows summarizing the columns of the table.
tfoot HtmlTableSectionElement [],
/// The `<th>` HTML element defines a cell as header of a group of table cells. The exact nature of this group is defined by the scope and headers attributes.
th HtmlTableCellElement [abbr, colspan, headers, rowspan, scope],
/// The `<thead>` HTML element defines a set of rows defining the head of the columns of the table.
thead HtmlTableSectionElement [],
/// The `<time>` HTML element represents a specific period in time. It may include the datetime attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders.
time HtmlTimeElement [datetime],
/// The `<title>` HTML element defines the document's title that is shown in a Browser's title bar or a page's tab. It only contains text; tags within the element are ignored.
title HtmlTitleElement [],
/// The `<tr>` HTML element defines a row of cells in a table. The row's cells can then be established using a mix of td (data cell) and th (header cell) elements.
tr HtmlTableRowElement [],
/// The `<u>` HTML element represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation. This is rendered by default as a simple solid underline, but may be altered using CSS.
u HtmlElement [],
/// The `<ul>` HTML element represents an unordered list of items, typically rendered as a bulleted list.
ul HtmlUListElement [],
/// The `<var>` HTML element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent.
var HtmlElement [],
/// The `<video>` HTML element embeds a media player which supports video playback into the document. You can use `<video>` for audio content as well, but the audio element may provide a more appropriate user experience.
video HtmlVideoElement [controls, controlslist, crossorigin, disablepictureinpicture, disableremoteplayback, height, r#loop, muted, playsinline, poster, preload, src, width],
}
pub fn option<Rndr>() -> HtmlElement<Option_, (), (), Rndr>
where
Rndr: Renderer,
{
HtmlElement {
tag: Option_,
rndr: PhantomData,
attributes: (),
children: (),
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Option_;
impl ElementType for Option_ {
type Output = web_sys::HtmlOutputElement;
const TAG: &'static str = "option";
const SELF_CLOSING: bool = false;
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl CreateElement<Dom> for Option_ {
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::JsCast;
thread_local! {
static ELEMENT: Lazy<<Dom as Renderer>::Element> = Lazy::new(|| {
crate::dom::document().create_element("option").unwrap()
});
}
ELEMENT.with(|e| e.clone_node()).unwrap().unchecked_into()
}
}

View file

@ -0,0 +1,101 @@
use super::{ElementWithChildren, HtmlElement};
use crate::{
html::{attribute::Attribute, element::AddAttribute},
prelude::Render,
renderer::{DomRenderer, Renderer},
};
use std::marker::PhantomData;
#[inline(always)]
pub fn inner_html<T, R>(value: T) -> InnerHtml<T, R>
where
T: AsRef<str>,
R: DomRenderer,
{
InnerHtml {
value,
rndr: PhantomData,
}
}
#[derive(Debug, Clone, Copy)]
pub struct InnerHtml<T, R>
where
T: AsRef<str>,
R: Renderer,
{
value: T,
rndr: PhantomData<R>,
}
impl<T, R> Attribute<R> for InnerHtml<T, R>
where
T: AsRef<str> + PartialEq,
R: DomRenderer,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
type State = (R::Element, T);
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
inner_html: &mut String,
) {
inner_html.push_str(self.value.as_ref());
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &<R as Renderer>::Element,
) -> Self::State {
(el.clone(), self.value)
}
fn build(self, el: &<R as Renderer>::Element) -> Self::State {
R::set_inner_html(el, self.value.as_ref());
(el.clone(), self.value)
}
fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self.value != *prev {
R::set_inner_html(el, self.value.as_ref());
*prev = self.value;
}
}
}
pub trait InnerHtmlAttribute<T, Rndr>
where
T: AsRef<str>,
Rndr: DomRenderer,
Self: Sized + AddAttribute<InnerHtml<T, Rndr>, Rndr>,
{
fn inner_html(
self,
value: T,
) -> <Self as AddAttribute<InnerHtml<T, Rndr>, Rndr>>::Output {
self.add_attr(inner_html(value))
}
}
impl<T, E, At, Rndr> InnerHtmlAttribute<T, Rndr>
for HtmlElement<E, At, (), Rndr>
where
Self: AddAttribute<InnerHtml<T, Rndr>, Rndr>,
E: ElementWithChildren,
At: Attribute<Rndr>,
T: AsRef<str>,
Rndr: DomRenderer,
{
fn inner_html(
self,
value: T,
) -> <Self as AddAttribute<InnerHtml<T, Rndr>, Rndr>>::Output {
self.add_attr(inner_html(value))
}
}

View file

@ -0,0 +1,572 @@
use crate::{
html::attribute::Attribute,
hydration::Cursor,
renderer::{CastFrom, Renderer},
ssr::StreamBuilder,
view::{
FallibleRender, Mountable, Position, PositionState, Render, RenderHtml,
ToTemplate,
},
};
use const_str_slice_concat::{
const_concat, const_concat_with_prefix, str_from_buffer,
};
use next_tuple::TupleBuilder;
use std::marker::PhantomData;
mod custom;
mod elements;
mod inner_html;
use super::attribute::global::AddAttribute;
pub use custom::*;
pub use elements::*;
pub use inner_html::*;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct HtmlElement<E, At, Ch, Rndr>
where
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
pub(crate) tag: E,
pub(crate) rndr: PhantomData<Rndr>,
pub(crate) attributes: At,
pub(crate) children: Ch,
}
impl<E, At, Ch, Rndr> HtmlElement<E, At, Ch, Rndr>
where
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
pub fn children(&self) -> &Ch {
&self.children
}
pub fn children_mut(&mut self) -> &mut Ch {
&mut self.children
}
pub fn attributes(&self) -> &At {
&self.attributes
}
pub fn attributes_mut(&mut self) -> &mut At {
&mut self.attributes
}
}
impl<E, At, Ch, NewChild, Rndr> ElementChild<Rndr, NewChild>
for HtmlElement<E, At, Ch, Rndr>
where
E: ElementWithChildren,
At: Attribute<Rndr>,
Ch: Render<Rndr> + TupleBuilder<NewChild>,
<Ch as TupleBuilder<NewChild>>::Output: Render<Rndr>,
Rndr: Renderer,
NewChild: Render<Rndr>,
{
type Output =
HtmlElement<E, At, <Ch as TupleBuilder<NewChild>>::Output, Rndr>;
fn child(self, child: NewChild) -> Self::Output {
let HtmlElement {
tag,
rndr,
attributes,
children,
} = self;
HtmlElement {
tag,
rndr,
attributes,
children: children.next_tuple(child),
}
}
}
impl<E, At, Ch, Rndr, NewAttr> AddAttribute<NewAttr, Rndr>
for HtmlElement<E, At, Ch, Rndr>
where
E: ElementType,
At: Attribute<Rndr> + TupleBuilder<NewAttr>,
<At as TupleBuilder<NewAttr>>::Output: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
type Output =
HtmlElement<E, <At as TupleBuilder<NewAttr>>::Output, Ch, Rndr>;
fn add_attr(self, attr: NewAttr) -> Self::Output {
let HtmlElement {
tag,
attributes,
children,
rndr,
} = self;
HtmlElement {
tag,
attributes: attributes.next_tuple(attr),
children,
rndr,
}
}
}
pub trait ElementChild<Rndr, NewChild>
where
NewChild: Render<Rndr>,
Rndr: Renderer,
{
type Output;
fn child(self, child: NewChild) -> Self::Output;
}
pub trait ElementType {
/// The underlying native widget type that this represents.
type Output;
const TAG: &'static str;
const SELF_CLOSING: bool;
fn tag(&self) -> &str;
}
pub trait ElementWithChildren {}
pub trait CreateElement<R: Renderer> {
fn create_element(&self) -> R::Element;
}
impl<E, At, Ch, Rndr> Render<Rndr> for HtmlElement<E, At, Ch, Rndr>
where
E: CreateElement<Rndr>,
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
type State = ElementState<At::State, Ch::State, Rndr>;
fn rebuild(self, state: &mut Self::State) {
let ElementState {
attrs, children, ..
} = state;
self.attributes.rebuild(attrs);
self.children.rebuild(children);
}
fn build(self) -> Self::State {
let el = Rndr::create_element(self.tag);
let attrs = self.attributes.build(&el);
let mut children = self.children.build();
children.mount(&el, None);
ElementState {
el,
attrs,
children,
rndr: PhantomData,
}
}
}
impl<E, At, Ch, Rndr> FallibleRender<Rndr> for HtmlElement<E, At, Ch, Rndr>
where
E: CreateElement<Rndr>,
At: Attribute<Rndr>,
Ch: FallibleRender<Rndr>,
Rndr: Renderer,
{
type Error = Ch::Error;
type FallibleState = ElementState<At::State, Ch::FallibleState, Rndr>;
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
let el = Rndr::create_element(self.tag);
let attrs = self.attributes.build(&el);
let mut children = self.children.try_build()?;
children.mount(&el, None);
Ok(ElementState {
el,
attrs,
children,
rndr: PhantomData,
})
}
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error> {
let ElementState {
attrs, children, ..
} = state;
self.attributes.rebuild(attrs);
self.children.try_rebuild(children)?;
Ok(())
}
}
impl<E, At, Ch, Rndr> RenderHtml<Rndr> for HtmlElement<E, At, Ch, Rndr>
where
E: ElementType + CreateElement<Rndr>,
At: Attribute<Rndr>,
Ch: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
const MIN_LENGTH: usize = if E::SELF_CLOSING {
3 // < ... />
+ E::TAG.len()
+ At::MIN_LENGTH
} else {
2 // < ... >
+ E::TAG.len()
+ At::MIN_LENGTH
+ Ch::MIN_LENGTH
+ 3 // </ ... >
+ E::TAG.len()
};
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
// opening tag
buf.push('<');
buf.push_str(E::TAG);
// attributes
// `class` and `style` are created first, and pushed later
// this is because they can be filled by a mixture of values that include
// either the whole value (`class="..."` or `style="..."`) and individual
// classes and styles (`class:foo=true` or `style:height="40px"`), so they
// need to be filled during the whole attribute-creation process and then
// added
// String doesn't allocate until the first push, so this is cheap if there
// is no class or style on an element
let mut class = String::new();
let mut style = String::new();
let mut inner_html = String::new();
// inject regular attributes, and fill class and style
self.attributes
.to_html(buf, &mut class, &mut style, &mut inner_html);
if !class.is_empty() {
buf.push(' ');
buf.push_str("class=\"");
buf.push_str(class.trim_start().trim_end());
buf.push('"');
}
if !style.is_empty() {
buf.push(' ');
buf.push_str("style=\"");
buf.push_str(style.trim_start().trim_end());
buf.push('"');
}
buf.push('>');
if !E::SELF_CLOSING {
if !inner_html.is_empty() {
buf.push_str(&inner_html);
} else {
// children
*position = Position::FirstChild;
self.children.to_html_with_buf(buf, position);
}
// closing tag
buf.push_str("</");
buf.push_str(E::TAG);
buf.push('>');
}
*position = Position::NextChild;
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buffer: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
let mut buf = String::with_capacity(Self::MIN_LENGTH);
// opening tag
buf.push('<');
buf.push_str(E::TAG);
// attributes
// `class` and `style` are created first, and pushed later
// this is because they can be filled by a mixture of values that include
// either the whole value (`class="..."` or `style="..."`) and individual
// classes and styles (`class:foo=true` or `style:height="40px"`), so they
// need to be filled during the whole attribute-creation process and then
// added
// String doesn't allocate until the first push, so this is cheap if there
// is no class or style on an element
let mut class = String::new();
let mut style = String::new();
let mut inner_html = String::new();
// inject regular attributes, and fill class and style
self.attributes.to_html(
&mut buf,
&mut class,
&mut style,
&mut inner_html,
);
if !class.is_empty() {
buf.push(' ');
buf.push_str("class=\"");
buf.push_str(class.trim_start().trim_end());
buf.push('"');
}
if !style.is_empty() {
buf.push(' ');
buf.push_str("style=\"");
buf.push_str(style.trim_start().trim_end());
buf.push('"');
}
buf.push('>');
buffer.push_sync(&buf);
if !E::SELF_CLOSING {
// children
*position = Position::FirstChild;
if !inner_html.is_empty() {
buffer.push_sync(&inner_html);
} else {
self.children
.to_html_async_with_buf::<OUT_OF_ORDER>(buffer, position);
}
// closing tag
let mut buf = String::with_capacity(3 + E::TAG.len());
buf.push_str("</");
buf.push_str(E::TAG);
buf.push('>');
buffer.push_sync(&buf);
}
*position = Position::NextChild;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
// non-Static custom elements need special support in templates
// because they haven't been inserted type-wise
if E::TAG.is_empty() && !FROM_SERVER {
todo!()
}
let curr_position = position.get();
if curr_position == Position::FirstChild {
cursor.child();
} else if curr_position != Position::Current {
cursor.sibling();
}
let el = Rndr::Element::cast_from(cursor.current()).unwrap();
let attrs = self.attributes.hydrate::<FROM_SERVER>(&el);
// hydrate children
position.set(Position::FirstChild);
let children = self.children.hydrate::<FROM_SERVER>(cursor, position);
cursor.set(el.as_ref().clone());
// go to next sibling
position.set(Position::NextChild);
ElementState {
el,
attrs,
children,
rndr: PhantomData,
}
}
}
pub struct ElementState<At, Ch, R: Renderer> {
pub el: R::Element,
pub attrs: At,
pub children: Ch,
rndr: PhantomData<R>,
}
impl<At, Ch, R> Mountable<R> for ElementState<At, Ch, R>
where
R: Renderer,
{
fn unmount(&mut self) {
R::remove(self.el.as_ref());
}
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
R::insert_node(parent, self.el.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.el.as_ref()));
true
}
}
impl<E, At, Ch, Rndr> ToTemplate for HtmlElement<E, At, Ch, Rndr>
where
E: ElementType,
At: Attribute<Rndr> + ToTemplate,
Ch: Render<Rndr> + ToTemplate,
Rndr: Renderer,
{
const TEMPLATE: &'static str = str_from_buffer(&const_concat(&[
"<",
E::TAG,
At::TEMPLATE,
str_from_buffer(&const_concat_with_prefix(
&[At::CLASS],
" class=\"",
"\"",
)),
str_from_buffer(&const_concat_with_prefix(
&[At::STYLE],
" style=\"",
"\"",
)),
">",
Ch::TEMPLATE,
"</",
E::TAG,
">",
]));
#[allow(unused)] // the variables `class` and `style` might be used, but only with `nightly` feature
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
// for custom elements without type known at compile time, do nothing
if !E::TAG.is_empty() {
// opening tag and attributes
let mut class = String::new();
let mut style = String::new();
let mut inner_html = String::new();
buf.push('<');
buf.push_str(E::TAG);
<At as ToTemplate>::to_template(
buf,
&mut class,
&mut style,
&mut inner_html,
position,
);
if !class.is_empty() {
buf.push(' ');
buf.push_str("class=\"");
buf.push_str(class.trim_start().trim_end());
buf.push('"');
}
if !style.is_empty() {
buf.push(' ');
buf.push_str("style=\"");
buf.push_str(style.trim_start().trim_end());
buf.push('"');
}
buf.push('>');
// children
*position = Position::FirstChild;
class.clear();
style.clear();
inner_html.clear();
Ch::to_template(
buf,
&mut class,
&mut style,
&mut inner_html,
position,
);
// closing tag
buf.push_str("</");
buf.push_str(E::TAG);
buf.push('>');
*position = Position::NextChild;
}
}
}
#[cfg(test)]
mod tests {
use super::{main, p, HtmlElement};
use crate::{
html::{
attribute::{global::GlobalAttributes, id, src},
class::class,
element::{em, ElementChild, Main},
},
renderer::mock_dom::MockDom,
view::{Render, RenderHtml},
};
#[test]
fn mock_dom_creates_element() {
let el: HtmlElement<Main, _, _, MockDom> =
main().child(p().id("test").lang("en").child("Hello, world!"));
let el = el.build();
assert_eq!(
el.el.to_debug_html(),
"<main><p lang=\"en\" id=\"test\">Hello, world!</p></main>"
);
}
#[test]
fn mock_dom_creates_element_with_several_children() {
let el: HtmlElement<Main, _, _, MockDom> = main().child(p().child((
"Hello, ",
em().child("beautiful"),
" world!",
)));
let el = el.build();
assert_eq!(
el.el.to_debug_html(),
"<main><p>Hello, <em>beautiful</em> world!</p></main>"
);
}
#[cfg(feature = "nightly")]
#[test]
fn html_render_allocates_appropriate_buffer() {
use crate::view::static_types::Static;
let el: HtmlElement<Main, _, _, MockDom> = main().child(p().child((
Static::<"Hello, ">,
em().child(Static::<"beautiful">),
Static::<" world!">,
)));
let allocated_len = el.min_length();
let html = el.to_html();
assert_eq!(
html,
"<main><p>Hello, <em>beautiful</em> world!</p></main>"
);
assert_eq!(html.len(), allocated_len);
}
}

387
tachys/src/html/event.rs Normal file
View file

@ -0,0 +1,387 @@
use crate::{
html::attribute::Attribute,
renderer::DomRenderer,
view::{Position, ToTemplate},
};
use std::{borrow::Cow, fmt::Debug, marker::PhantomData};
use wasm_bindgen::convert::FromWasmAbi;
pub fn on<E, R>(event: E, mut cb: impl FnMut(E::EventType) + 'static) -> On<R>
where
E: EventDescriptor + 'static,
E::EventType: 'static,
R: DomRenderer,
E::EventType: From<R::Event>,
{
On {
name: event.name(),
setup: Box::new(move |el| {
let cb = Box::new(move |ev: R::Event| {
let specific_event = ev.into();
cb(specific_event);
}) as Box<dyn FnMut(R::Event)>;
if E::BUBBLES && cfg!(feature = "delegation") {
R::add_event_listener_delegated(
el,
event.name(),
event.event_delegation_key(),
cb,
)
} else {
R::add_event_listener(el, &event.name(), cb)
}
}),
ty: PhantomData,
}
}
pub struct On<R: DomRenderer> {
name: Cow<'static, str>,
#[allow(clippy::type_complexity)]
setup: Box<dyn FnOnce(&R::Element) -> Box<dyn FnOnce(&R::Element)>>,
ty: PhantomData<R>,
}
impl<R> Debug for On<R>
where
R: DomRenderer,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("On").field(&self.name).finish()
}
}
impl<R> Attribute<R> for On<R>
where
R: DomRenderer,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
// a function that can be called once to remove the event listener
type State = (R::Element, Option<Box<dyn FnOnce(&R::Element)>>);
#[inline(always)]
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
#[inline(always)]
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let cleanup = (self.setup)(el);
(el.clone(), Some(cleanup))
}
#[inline(always)]
fn build(self, el: &R::Element) -> Self::State {
let cleanup = (self.setup)(el);
(el.clone(), Some(cleanup))
}
#[inline(always)]
fn rebuild(self, state: &mut Self::State) {
let (el, prev_cleanup) = state;
if let Some(prev) = prev_cleanup.take() {
prev(el);
}
*prev_cleanup = Some((self.setup)(el));
}
}
impl<R> ToTemplate for On<R>
where
R: DomRenderer,
{
#[inline(always)]
fn to_template(
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
}
}
/// A trait for converting types into [web_sys events](web_sys).
pub trait EventDescriptor: Clone {
/// The [`web_sys`] event type, such as [`web_sys::MouseEvent`].
type EventType: FromWasmAbi;
/// Indicates if this event bubbles. For example, `click` bubbles,
/// but `focus` does not.
///
/// If this is true, then the event will be delegated globally,
/// otherwise, event listeners will be directly attached to the element.
const BUBBLES: bool;
/// The name of the event, such as `click` or `mouseover`.
fn name(&self) -> Cow<'static, str>;
/// The key used for event delegation.
fn event_delegation_key(&self) -> Cow<'static, str>;
/// Return the options for this type. This is only used when you create a [`Custom`] event
/// handler.
#[inline(always)]
fn options(&self) -> &Option<web_sys::AddEventListenerOptions> {
&None
}
}
macro_rules! generate_event_types {
{$(
$( #[$does_not_bubble:ident] )?
$( $event:ident )+ : $web_event:ident
),* $(,)?} => {
::paste::paste! {
$(
#[doc = "The `" [< $($event)+ >] "` event, which receives [" $web_event "](web_sys::" $web_event ") as its argument."]
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
pub struct [<$( $event )+ >];
impl EventDescriptor for [< $($event)+ >] {
type EventType = web_sys::$web_event;
#[inline(always)]
fn name(&self) -> Cow<'static, str> {
stringify!([< $($event)+ >]).into()
}
#[inline(always)]
fn event_delegation_key(&self) -> Cow<'static, str> {
concat!("$$$", stringify!([< $($event)+ >])).into()
}
const BUBBLES: bool = true $(&& generate_event_types!($does_not_bubble))?;
}
)*
}
};
(does_not_bubble) => { false }
}
generate_event_types! {
// =========================================================
// WindowEventHandlersEventMap
// =========================================================
#[does_not_bubble]
after print: Event,
#[does_not_bubble]
before print: Event,
#[does_not_bubble]
before unload: BeforeUnloadEvent,
#[does_not_bubble]
gamepad connected: GamepadEvent,
#[does_not_bubble]
gamepad disconnected: GamepadEvent,
hash change: HashChangeEvent,
#[does_not_bubble]
language change: Event,
#[does_not_bubble]
message: MessageEvent,
#[does_not_bubble]
message error: MessageEvent,
#[does_not_bubble]
offline: Event,
#[does_not_bubble]
online: Event,
#[does_not_bubble]
page hide: PageTransitionEvent,
#[does_not_bubble]
page show: PageTransitionEvent,
pop state: PopStateEvent,
rejection handled: PromiseRejectionEvent,
#[does_not_bubble]
storage: StorageEvent,
#[does_not_bubble]
unhandled rejection: PromiseRejectionEvent,
#[does_not_bubble]
unload: Event,
// =========================================================
// GlobalEventHandlersEventMap
// =========================================================
#[does_not_bubble]
abort: UiEvent,
animation cancel: AnimationEvent,
animation end: AnimationEvent,
animation iteration: AnimationEvent,
animation start: AnimationEvent,
aux click: MouseEvent,
before input: InputEvent,
#[does_not_bubble]
blur: FocusEvent,
#[does_not_bubble]
can play: Event,
#[does_not_bubble]
can play through: Event,
change: Event,
click: MouseEvent,
#[does_not_bubble]
close: Event,
composition end: CompositionEvent,
composition start: CompositionEvent,
composition update: CompositionEvent,
context menu: MouseEvent,
#[does_not_bubble]
cue change: Event,
dbl click: MouseEvent,
drag: DragEvent,
drag end: DragEvent,
drag enter: DragEvent,
drag leave: DragEvent,
drag over: DragEvent,
drag start: DragEvent,
drop: DragEvent,
#[does_not_bubble]
duration change: Event,
#[does_not_bubble]
emptied: Event,
#[does_not_bubble]
ended: Event,
#[does_not_bubble]
error: ErrorEvent,
#[does_not_bubble]
focus: FocusEvent,
#[does_not_bubble]
focus in: FocusEvent,
#[does_not_bubble]
focus out: FocusEvent,
form data: Event, // web_sys does not include `FormDataEvent`
#[does_not_bubble]
got pointer capture: PointerEvent,
input: Event,
#[does_not_bubble]
invalid: Event,
key down: KeyboardEvent,
key press: KeyboardEvent,
key up: KeyboardEvent,
#[does_not_bubble]
load: Event,
#[does_not_bubble]
loaded data: Event,
#[does_not_bubble]
loaded metadata: Event,
#[does_not_bubble]
load start: Event,
lost pointer capture: PointerEvent,
mouse down: MouseEvent,
#[does_not_bubble]
mouse enter: MouseEvent,
#[does_not_bubble]
mouse leave: MouseEvent,
mouse move: MouseEvent,
mouse out: MouseEvent,
mouse over: MouseEvent,
mouse up: MouseEvent,
#[does_not_bubble]
pause: Event,
#[does_not_bubble]
play: Event,
#[does_not_bubble]
playing: Event,
pointer cancel: PointerEvent,
pointer down: PointerEvent,
#[does_not_bubble]
pointer enter: PointerEvent,
#[does_not_bubble]
pointer leave: PointerEvent,
pointer move: PointerEvent,
pointer out: PointerEvent,
pointer over: PointerEvent,
pointer up: PointerEvent,
#[does_not_bubble]
progress: ProgressEvent,
#[does_not_bubble]
rate change: Event,
reset: Event,
#[does_not_bubble]
resize: UiEvent,
#[does_not_bubble]
scroll: Event,
#[does_not_bubble]
scroll end: Event,
security policy violation: SecurityPolicyViolationEvent,
#[does_not_bubble]
seeked: Event,
#[does_not_bubble]
seeking: Event,
select: Event,
#[does_not_bubble]
selection change: Event,
select start: Event,
slot change: Event,
#[does_not_bubble]
stalled: Event,
submit: SubmitEvent,
#[does_not_bubble]
suspend: Event,
#[does_not_bubble]
time update: Event,
#[does_not_bubble]
toggle: Event,
touch cancel: TouchEvent,
touch end: TouchEvent,
touch move: TouchEvent,
touch start: TouchEvent,
transition cancel: TransitionEvent,
transition end: TransitionEvent,
transition run: TransitionEvent,
transition start: TransitionEvent,
#[does_not_bubble]
volume change: Event,
#[does_not_bubble]
waiting: Event,
webkit animation end: Event,
webkit animation iteration: Event,
webkit animation start: Event,
webkit transition end: Event,
wheel: WheelEvent,
// =========================================================
// WindowEventMap
// =========================================================
D O M Content Loaded: Event, // Hack for correct casing
#[does_not_bubble]
device motion: DeviceMotionEvent,
#[does_not_bubble]
device orientation: DeviceOrientationEvent,
#[does_not_bubble]
orientation change: Event,
// =========================================================
// DocumentAndElementEventHandlersEventMap
// =========================================================
copy: Event, // ClipboardEvent is unstable
cut: Event, // ClipboardEvent is unstable
paste: Event, // ClipboardEvent is unstable
// =========================================================
// DocumentEventMap
// =========================================================
fullscreen change: Event,
fullscreen error: Event,
pointer lock change: Event,
pointer lock error: Event,
#[does_not_bubble]
ready state change: Event,
visibility change: Event,
}
// Export `web_sys` event types
pub use web_sys::{
AnimationEvent, BeforeUnloadEvent, CompositionEvent, CustomEvent,
DeviceMotionEvent, DeviceOrientationEvent, DragEvent, ErrorEvent, Event,
FocusEvent, GamepadEvent, HashChangeEvent, InputEvent, KeyboardEvent,
MessageEvent, MouseEvent, PageTransitionEvent, PointerEvent, PopStateEvent,
ProgressEvent, PromiseRejectionEvent, SecurityPolicyViolationEvent,
StorageEvent, SubmitEvent, TouchEvent, TransitionEvent, UiEvent,
WheelEvent,
};

205
tachys/src/html/islands.rs Normal file
View file

@ -0,0 +1,205 @@
use crate::{
hydration::Cursor,
prelude::{Render, RenderHtml},
renderer::Renderer,
ssr::StreamBuilder,
view::{Position, PositionState},
};
use std::marker::PhantomData;
// TODO serialized props, too
pub struct Island<Rndr, View> {
component: &'static str,
view: View,
rndr: PhantomData<Rndr>,
}
const ISLAND_TAG: &'static str = "leptos-island";
const ISLAND_CHILDREN_TAG: &'static str = "leptos-children";
impl<Rndr, View> Island<Rndr, View> {
pub fn new(component: &'static str, view: View) -> Self {
Island {
component,
view,
rndr: PhantomData,
}
}
fn open_tag(component: &'static str, buf: &mut String) {
buf.push('<');
buf.push_str(ISLAND_TAG);
buf.push(' ');
buf.push_str("data-component=\"");
buf.push_str(component);
buf.push_str("\">");
// TODO insert serialized props
}
fn close_tag(buf: &mut String) {
buf.push_str("</");
buf.push_str(ISLAND_TAG);
buf.push('>');
}
}
impl<Rndr, View> Render<Rndr> for Island<Rndr, View>
where
View: Render<Rndr>,
Rndr: Renderer,
{
type State = View::State;
fn build(self) -> Self::State {
self.view.build()
}
fn rebuild(self, state: &mut Self::State) {
self.view.rebuild(state);
}
}
impl<Rndr, View> RenderHtml<Rndr> for Island<Rndr, View>
where
View: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Element: Clone,
Rndr::Node: Clone,
{
const MIN_LENGTH: usize = ISLAND_TAG.len() * 2
+ "<>".len()
+ "</>".len()
+ "data-component".len()
+ View::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
Self::open_tag(self.component, buf);
self.view.to_html_with_buf(buf, position);
Self::close_tag(buf);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
// insert the opening tag synchronously
let mut tag = String::new();
Self::open_tag(self.component, &mut tag);
buf.push_sync(&tag);
// streaming render for the view
self.view
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
// and insert the closing tag synchronously
tag.clear();
Self::close_tag(&mut tag);
buf.push_sync(&tag);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
position.set(Position::FirstChild);
self.view.hydrate::<FROM_SERVER>(cursor, position)
}
}
pub struct IslandChildren<Rndr, View> {
view: View,
rndr: PhantomData<Rndr>,
}
impl<Rndr, View> IslandChildren<Rndr, View> {
pub fn new(view: View) -> Self {
IslandChildren {
view,
rndr: PhantomData,
}
}
fn open_tag(buf: &mut String) {
buf.push('<');
buf.push_str(ISLAND_CHILDREN_TAG);
buf.push('>');
}
fn close_tag(buf: &mut String) {
buf.push_str("</");
buf.push_str(ISLAND_CHILDREN_TAG);
buf.push('>');
}
}
impl<Rndr, View> Render<Rndr> for IslandChildren<Rndr, View>
where
View: Render<Rndr>,
Rndr: Renderer,
{
type State = ();
fn build(self) -> Self::State {}
fn rebuild(self, state: &mut Self::State) {}
}
impl<Rndr, View> RenderHtml<Rndr> for IslandChildren<Rndr, View>
where
View: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Element: Clone,
Rndr::Node: Clone,
{
const MIN_LENGTH: usize = ISLAND_CHILDREN_TAG.len() * 2
+ "<>".len()
+ "</>".len()
+ View::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
Self::open_tag(buf);
self.view.to_html_with_buf(buf, position);
Self::close_tag(buf);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
// insert the opening tag synchronously
let mut tag = String::new();
Self::open_tag(&mut tag);
buf.push_sync(&tag);
// streaming render for the view
self.view
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
// and insert the closing tag synchronously
tag.clear();
Self::close_tag(&mut tag);
buf.push_sync(&tag);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
// island children aren't hydrated
// we update the walk to pass over them
// but we don't hydrate their children
let curr_position = position.get();
if curr_position == Position::FirstChild {
cursor.child();
} else if curr_position != Position::Current {
cursor.sibling();
}
}
}

56
tachys/src/html/mod.rs Normal file
View file

@ -0,0 +1,56 @@
use crate::{
renderer::Renderer,
view::{Position, Render, RenderHtml},
};
use std::marker::PhantomData;
pub mod attribute;
pub mod class;
pub mod element;
pub mod event;
pub mod islands;
pub mod node_ref;
pub mod property;
pub mod style;
pub struct Doctype<R: Renderer> {
value: &'static str,
rndr: PhantomData<R>,
}
pub fn doctype<R: Renderer>(value: &'static str) -> Doctype<R> {
Doctype {
value,
rndr: PhantomData,
}
}
impl<R: Renderer> Render<R> for Doctype<R> {
type State = ();
fn build(self) -> Self::State {}
fn rebuild(self, _state: &mut Self::State) {}
}
impl<R> RenderHtml<R> for Doctype<R>
where
R: Renderer,
R::Element: Clone,
R::Node: Clone,
{
const MIN_LENGTH: usize = "<!DOCTYPE html>".len();
fn to_html_with_buf(self, buf: &mut String, _position: &mut Position) {
buf.push_str("<!DOCTYPE ");
buf.push_str(self.value);
buf.push('>');
}
fn hydrate<const FROM_SERVER: bool>(
self,
_cursor: &crate::hydration::Cursor<R>,
_position: &crate::view::PositionState,
) -> Self::State {
}
}

101
tachys/src/html/node_ref.rs Normal file
View file

@ -0,0 +1,101 @@
use super::{
attribute::{global::AddAttribute, Attribute},
element::ElementType,
};
use crate::{html::element::HtmlElement, prelude::Render, renderer::Renderer};
use std::marker::PhantomData;
pub trait NodeRefContainer<E, Rndr>
where
E: ElementType,
Rndr: Renderer,
{
fn load(self, el: &Rndr::Element);
}
pub struct NodeRefAttr<E, C, Rndr>
where
E: ElementType,
C: NodeRefContainer<E, Rndr>,
Rndr: Renderer,
{
container: C,
ty: PhantomData<E>,
rndr: PhantomData<Rndr>,
}
pub fn node_ref<E, C, Rndr>(container: C) -> NodeRefAttr<E, C, Rndr>
where
E: ElementType,
C: NodeRefContainer<E, Rndr>,
Rndr: Renderer,
{
NodeRefAttr {
container,
ty: PhantomData,
rndr: PhantomData,
}
}
impl<E, C, Rndr> Attribute<Rndr> for NodeRefAttr<E, C, Rndr>
where
E: ElementType,
C: NodeRefContainer<E, Rndr>,
Rndr: Renderer,
Rndr::Element: Clone + PartialEq,
{
const MIN_LENGTH: usize = 0;
type State = ();
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &<Rndr as Renderer>::Element,
) -> Self::State {
self.container.load(el);
}
fn build(self, el: &<Rndr as Renderer>::Element) -> Self::State {
self.container.load(el);
}
fn rebuild(self, _state: &mut Self::State) {}
}
pub trait NodeRefAttribute<E, C, Rndr>
where
E: ElementType,
C: NodeRefContainer<E, Rndr>,
Rndr: Renderer,
{
fn node_ref(
self,
container: C,
) -> <Self as AddAttribute<NodeRefAttr<E, C, Rndr>, Rndr>>::Output
where
Self: Sized + AddAttribute<NodeRefAttr<E, C, Rndr>, Rndr>,
<Self as AddAttribute<NodeRefAttr<E, C, Rndr>, Rndr>>::Output:
Render<Rndr>,
{
self.add_attr(node_ref(container))
}
}
impl<E, At, Ch, C, Rndr> NodeRefAttribute<E, C, Rndr>
for HtmlElement<E, At, Ch, Rndr>
where
E: ElementType,
At: Attribute<Rndr>,
Ch: Render<Rndr>,
C: NodeRefContainer<E, Rndr>,
Rndr: Renderer,
{
}

150
tachys/src/html/property.rs Normal file
View file

@ -0,0 +1,150 @@
use super::attribute::Attribute;
use crate::{
renderer::DomRenderer,
view::{Position, ToTemplate},
};
use std::marker::PhantomData;
use wasm_bindgen::JsValue;
#[inline(always)]
pub fn property<K, P, R>(key: K, value: P) -> Property<K, P, R>
where
K: AsRef<str>,
P: IntoProperty<R>,
R: DomRenderer,
{
Property {
key,
value,
rndr: PhantomData,
}
}
pub struct Property<K, P, R>
where
K: AsRef<str>,
P: IntoProperty<R>,
R: DomRenderer,
{
key: K,
value: P,
rndr: PhantomData<R>,
}
impl<K, P, R> Attribute<R> for Property<K, P, R>
where
K: AsRef<str>,
P: IntoProperty<R>,
R: DomRenderer,
{
const MIN_LENGTH: usize = 0;
type State = P::State;
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
self.value.hydrate::<FROM_SERVER>(el, self.key.as_ref())
}
fn build(self, el: &R::Element) -> Self::State {
self.value.build(el, self.key.as_ref())
}
fn rebuild(self, state: &mut Self::State) {
self.value.rebuild(state, self.key.as_ref())
}
}
impl<K, P, R> ToTemplate for Property<K, P, R>
where
K: AsRef<str>,
P: IntoProperty<R>,
R: DomRenderer,
{
fn to_template(
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
}
}
pub trait IntoProperty<R: DomRenderer> {
type State;
fn hydrate<const FROM_SERVER: bool>(
self,
el: &R::Element,
key: &str,
) -> Self::State;
fn build(self, el: &R::Element, key: &str) -> Self::State;
fn rebuild(self, state: &mut Self::State, key: &str);
}
macro_rules! prop_type {
($prop_type:ty) => {
impl<R> IntoProperty<R> for $prop_type
where
R: DomRenderer,
R::Element: Clone,
{
type State = (R::Element, JsValue);
fn hydrate<const FROM_SERVER: bool>(
self,
el: &R::Element,
key: &str,
) -> Self::State {
let value = self.into();
R::set_property(el, key, &value);
(el.clone(), value)
}
fn build(self, el: &R::Element, key: &str) -> Self::State {
let value = self.into();
R::set_property(el, key, &value);
(el.clone(), value)
}
fn rebuild(self, state: &mut Self::State, key: &str) {
let (el, prev) = state;
let value = self.into();
if value != *prev {
R::set_property(el, key, &value);
}
*prev = value;
}
}
};
}
prop_type!(JsValue);
prop_type!(String);
prop_type!(&String);
prop_type!(&str);
prop_type!(usize);
prop_type!(u8);
prop_type!(u16);
prop_type!(u32);
prop_type!(u64);
prop_type!(u128);
prop_type!(isize);
prop_type!(i8);
prop_type!(i16);
prop_type!(i32);
prop_type!(i64);
prop_type!(i128);
prop_type!(f32);
prop_type!(f64);
prop_type!(bool);

315
tachys/src/html/style.rs Normal file
View file

@ -0,0 +1,315 @@
use super::attribute::Attribute;
use crate::{
renderer::DomRenderer,
view::{Position, ToTemplate},
};
use std::{borrow::Cow, marker::PhantomData};
/// Adds to the style attribute of the parent element.
///
/// This can take a plain string value, which will be assigned to the `style`
#[inline(always)]
pub fn style<S, R>(style: S) -> Style<S, R>
where
S: IntoStyle<R>,
R: DomRenderer,
{
Style {
style,
rndr: PhantomData,
}
}
pub struct Style<S, R>
where
S: IntoStyle<R>,
R: DomRenderer,
{
style: S,
rndr: PhantomData<R>,
}
impl<S, R> Attribute<R> for Style<S, R>
where
S: IntoStyle<R>,
R: DomRenderer,
{
const MIN_LENGTH: usize = 0;
type State = S::State;
fn to_html(
self,
_buf: &mut String,
_style: &mut String,
style: &mut String,
_inner_html: &mut String,
) {
self.style.to_html(style);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
self.style.hydrate::<FROM_SERVER>(el)
}
fn build(self, el: &R::Element) -> Self::State {
self.style.build(el)
}
fn rebuild(self, state: &mut Self::State) {
self.style.rebuild(state)
}
}
impl<S, R> ToTemplate for Style<S, R>
where
S: IntoStyle<R>,
R: DomRenderer,
{
fn to_template(
_buf: &mut String,
_style: &mut String,
_class: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
// TODO: should there be some templating for static styles?
}
}
/// Any type that can be added to the `style` attribute or set as a style in
/// the [`CssStyleDeclaration`]. This could be a plain string, or a property name-value pair.
pub trait IntoStyle<R: DomRenderer> {
type State;
fn to_html(self, style: &mut String);
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State;
fn build(self, el: &R::Element) -> Self::State;
fn rebuild(self, state: &mut Self::State);
}
pub trait StylePropertyValue<R: DomRenderer> {
type State;
fn to_html(self, name: &str, style: &mut String);
fn hydrate<const FROM_SERVER: bool>(
self,
name: Cow<'static, str>,
el: &R::Element,
) -> Self::State;
fn rebuild(self, name: Cow<'static, str>, state: &mut Self::State);
}
impl<'a, R> IntoStyle<R> for &'a str
where
R: DomRenderer,
R::Element: Clone,
{
type State = (R::Element, &'a str);
fn to_html(self, style: &mut String) {
style.push_str(self);
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
(el.clone(), self)
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, "style", self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self != *prev {
R::set_attribute(el, "style", self);
}
*prev = self;
}
}
impl<R> IntoStyle<R> for String
where
R: DomRenderer,
R::Element: Clone,
{
type State = (R::Element, String);
fn to_html(self, style: &mut String) {
style.push_str(&self);
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
(el.clone(), self)
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, "style", &self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
let (el, prev) = state;
if self != *prev {
R::set_attribute(el, "style", &self);
}
*prev = self;
}
}
impl<'a, R> IntoStyle<R> for (&'a str, &'a str)
where
R: DomRenderer,
{
type State = (R::CssStyleDeclaration, &'a str);
fn to_html(self, style: &mut String) {
let (name, value) = self;
style.push_str(name);
style.push(':');
style.push_str(value);
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let style = R::style(el);
(style, self.1)
}
fn build(self, el: &R::Element) -> Self::State {
let (name, value) = self;
let style = R::style(el);
R::set_css_property(&style, name, value);
(style, self.1)
}
fn rebuild(self, state: &mut Self::State) {
let (name, value) = self;
let (style, prev) = state;
if value != *prev {
R::set_css_property(style, name, value);
}
*prev = value;
}
}
impl<'a, R> IntoStyle<R> for (&'a str, String)
where
R: DomRenderer,
{
type State = (R::CssStyleDeclaration, String);
fn to_html(self, style: &mut String) {
let (name, value) = self;
style.push_str(name);
style.push(':');
style.push_str(&value);
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let style = R::style(el);
(style, self.1)
}
fn build(self, el: &R::Element) -> Self::State {
let (name, value) = &self;
let style = R::style(el);
R::set_css_property(&style, name, value);
(style, self.1)
}
fn rebuild(self, state: &mut Self::State) {
let (name, value) = self;
let (style, prev) = state;
if value != *prev {
R::set_css_property(style, name, &value);
}
*prev = value;
}
}
#[cfg(feature = "nightly")]
impl<const V: &'static str, R> IntoStyle<R>
for crate::view::static_types::Static<V>
where
R: DomRenderer,
{
type State = ();
fn to_html(self, style: &mut String) {
style.push_str(V);
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(
self,
_el: &<R>::Element,
) -> Self::State {
}
fn build(self, el: &<R>::Element) -> Self::State {
R::set_attribute(el, "style", V);
}
fn rebuild(self, _state: &mut Self::State) {}
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::{
element::{p, HtmlElement},
style::style,
},
renderer::dom::Dom,
view::{Position, PositionState, RenderHtml},
};
#[test]
fn adds_simple_style() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> = p(style("display: block"), ());
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(html, r#"<p style="display: block;"></p>"#);
}
#[test]
fn mixes_plain_and_specific_styles() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> =
p((style("display: block"), style(("color", "blue"))), ());
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(html, r#"<p style="display: block;color:blue;"></p>"#);
}
#[test]
fn handles_dynamic_styles() {
let mut html = String::new();
let el: HtmlElement<_, _, _, Dom> = p(
(
style("display: block"),
style(("color", "blue")),
style(("font-weight", || "bold".to_string())),
),
(),
);
el.to_html(&mut html, &PositionState::new(Position::FirstChild));
assert_eq!(
html,
r#"<p style="display: block;color:blue;font-weight:bold;"></p>"#
);
}
}
*/

51
tachys/src/hydration.rs Normal file
View file

@ -0,0 +1,51 @@
use crate::renderer::Renderer;
use std::{cell::RefCell, rc::Rc};
#[derive(Debug)]
pub struct Cursor<R: Renderer>(Rc<RefCell<R::Node>>);
impl<R: Renderer> Clone for Cursor<R> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}
impl<R> Cursor<R>
where
R: Renderer,
R::Node: Clone,
R::Element: AsRef<R::Node>,
{
pub fn new(root: R::Element) -> Self {
Self(Rc::new(RefCell::new(root.as_ref().clone())))
}
pub fn current(&self) -> R::Node {
self.0.borrow().clone()
}
pub fn child(&self) {
let mut inner = self.0.borrow_mut();
if let Some(node) = R::first_child(&*inner) {
*inner = node;
}
}
pub fn sibling(&self) {
let mut inner = self.0.borrow_mut();
if let Some(node) = R::next_sibling(&*inner) {
*inner = node;
}
}
pub fn parent(&self) {
let mut inner = self.0.borrow_mut();
if let Some(node) = R::get_parent(&*inner) {
*inner = node;
}
}
pub fn set(&self, node: R::Node) {
*self.0.borrow_mut() = node;
}
}

101
tachys/src/leptos/class.rs Normal file
View file

@ -0,0 +1,101 @@
use crate::{html::class::IntoClass, renderer::DomRenderer};
use leptos_reactive::{create_render_effect, Effect};
impl<F, C, R> IntoClass<R> for F
where
F: Fn() -> C + 'static,
C: IntoClass<R> + 'static,
C::State: 'static,
R: DomRenderer,
R::ClassList: 'static,
R::Element: Clone + 'static,
{
type State = Effect<C::State>;
fn to_html(self, class: &mut String) {
let value = self();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(self, el: &R::Element) -> Self::State {
let el = el.to_owned();
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build(&el)
}
})
}
fn rebuild(self, state: &mut Self::State) {}
}
impl<F, R> IntoClass<R> for (&'static str, F)
where
F: Fn() -> bool + 'static,
R: DomRenderer,
R::ClassList: 'static,
R::Element: Clone,
{
type State = Effect<bool>;
fn to_html(self, class: &mut String) {
let (name, f) = self;
let include = f();
if include {
<&str as IntoClass<R>>::to_html(name, class);
}
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
// TODO FROM_SERVER vs template
let (name, f) = self;
let class_list = R::class_list(el);
create_render_effect(move |prev| {
let include = f();
if Some(include) != prev {
if include {
R::add_class(&class_list, name);
} else {
R::remove_class(&class_list, name);
}
}
include
})
}
fn build(self, el: &R::Element) -> Self::State {
let (name, f) = self;
let class_list = R::class_list(el);
create_render_effect(move |prev| {
let include = f();
if Some(include) != prev {
if include {
R::add_class(&class_list, name);
} else {
R::remove_class(&class_list, name);
}
}
include
})
}
fn rebuild(self, state: &mut Self::State) {}
}

193
tachys/src/leptos/mod.rs Normal file
View file

@ -0,0 +1,193 @@
use crate::{
hydration::Cursor,
renderer::Renderer,
view::{
Mountable, Position, PositionState, Render, RenderHtml, ToTemplate,
},
};
use leptos_reactive::{create_render_effect, Effect, SignalDispose};
mod class;
mod style;
impl<F, V> ToTemplate for F
where
F: Fn() -> V,
V: ToTemplate,
{
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
position: &mut Position,
) {
// FIXME this seems wrong
V::to_template(buf, class, style, position)
}
}
impl<F, V, R> Render<R> for F
where
F: Fn() -> V + 'static,
V: Render<R>,
V::State: 'static,
R: Renderer,
{
type State = Effect<V::State>;
fn build(self) -> Self::State {
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
})
}
#[track_caller]
fn rebuild(self, state: &mut Self::State) {
crate::log(&format!(
"[REBUILDING EFFECT] Is this a mistake? {}",
std::panic::Location::caller(),
));
let old_effect = std::mem::replace(state, self.build());
old_effect.dispose();
}
}
impl<F, V, R> RenderHtml<R> for F
where
F: Fn() -> V + 'static,
V: RenderHtml<R>,
V::State: 'static,
R: Renderer + 'static,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = V::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &PositionState) {
let value = self();
value.to_html_with_buf(buf, position);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let cursor = cursor.clone();
let position = position.clone();
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&cursor, &position)
}
})
}
}
impl<M, R> Mountable<R> for Effect<M>
where
M: Mountable<R> + 'static,
R: Renderer,
{
fn unmount(&mut self) {
self.with_value_mut(|value| {
if let Some(value) = value {
value.unmount()
}
});
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
self.with_value_mut(|value| {
if let Some(state) = value {
state.mount(parent, marker);
}
});
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
self.with_value_mut(|value| {
value
.as_mut()
.map(|value| value.insert_before_this(parent, child))
})
.flatten()
.unwrap_or(false)
}
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::element::{button, main, HtmlElement},
renderer::mock_dom::MockDom,
view::Render,
};
use leptos_reactive::{create_runtime, RwSignal, SignalGet, SignalSet};
#[test]
fn create_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
count.set(1);
assert_eq!(el.el.to_debug_html(), "<button>1</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element_among_siblings() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> = main(
(),
button(
(),
("Hello, my ", move || count.get().to_string(), " friends."),
),
);
let el = app.build();
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 0 friends.</button></main>"
);
count.set(42);
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 42 friends.</button></main>"
);
rt.dispose();
}
}
*/

View file

@ -0,0 +1,87 @@
use crate::{html::style::IntoStyle, renderer::DomRenderer};
use leptos_reactive::{create_render_effect, Effect};
use std::borrow::Cow;
impl<F, S, R> IntoStyle<R> for (&'static str, F)
where
F: Fn() -> S + 'static,
S: Into<Cow<'static, str>>,
R: DomRenderer,
R::CssStyleDeclaration: Clone + 'static,
{
type State = Effect<(R::CssStyleDeclaration, Cow<'static, str>)>;
fn to_html(self, style: &mut String) {
let (name, f) = self;
let value = f();
style.push_str(name);
style.push(':');
style.push_str(&value.into());
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let (name, f) = self;
// TODO FROM_SERVER vs template
let style = R::style(el);
create_render_effect(move |prev| {
let value = f().into();
if let Some(mut state) = prev {
let (style, prev): &mut (
R::CssStyleDeclaration,
Cow<'static, str>,
) = &mut state;
if &value != prev {
R::set_css_property(style, name, &value);
}
*prev = value;
state
} else {
(style.clone(), value)
}
})
}
fn build(self, el: &R::Element) -> Self::State {
todo!()
}
fn rebuild(self, state: &mut Self::State) {}
}
impl<F, C, R> IntoStyle<R> for F
where
F: Fn() -> C + 'static,
C: IntoStyle<R> + 'static,
C::State: 'static,
R: DomRenderer,
R::Element: Clone + 'static,
R::CssStyleDeclaration: Clone + 'static,
{
type State = Effect<C::State>;
fn to_html(self, class: &mut String) {
let value = self();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(self, el: &R::Element) -> Self::State {
todo!()
}
fn rebuild(self, state: &mut Self::State) {}
}

143
tachys/src/lib.rs Normal file
View file

@ -0,0 +1,143 @@
#![allow(incomplete_features)] // yolo
#![cfg_attr(feature = "nightly", feature(adt_const_params))]
pub mod prelude {
pub use crate::{
async_views::FutureViewExt,
html::{
attribute::{
aria::AriaAttributes,
custom::CustomAttribute,
global::{
ClassAttribute, GlobalAttributes, OnAttribute,
PropAttribute, StyleAttribute,
},
},
element::{ElementChild, InnerHtmlAttribute},
node_ref::NodeRefAttribute,
},
renderer::{dom::Dom, Renderer, SpawningRenderer},
view::{
error_boundary::TryCatchBoundary, Mountable, Render, RenderHtml,
},
};
}
use wasm_bindgen::JsValue;
use web_sys::Node;
pub mod async_views;
pub mod dom;
pub mod error;
pub mod html;
pub mod hydration;
pub mod mathml;
pub mod renderer;
pub mod spawner;
pub mod ssr;
pub mod svg;
pub mod view;
#[cfg(feature = "islands")]
pub use wasm_bindgen;
#[cfg(feature = "islands")]
pub use web_sys;
#[cfg(all(feature = "leptos", not(feature = "reaccy")))]
mod leptos;
#[cfg(feature = "reaccy")]
mod tachy_reaccy;
#[cfg(feature = "reaccy")]
pub use tachy_reaccy::node_ref;
pub fn log(text: &str) {
web_sys::console::log_1(&JsValue::from_str(text));
}
pub(crate) trait UnwrapOrDebug {
type Output;
fn or_debug(self, el: &Node, label: &'static str);
fn ok_or_debug(
self,
el: &Node,
label: &'static str,
) -> Option<Self::Output>;
}
impl<T> UnwrapOrDebug for Result<T, JsValue> {
type Output = T;
#[track_caller]
fn or_debug(self, el: &Node, name: &'static str) {
#[cfg(debug_assertions)]
{
if let Err(err) = self {
let location = std::panic::Location::caller();
web_sys::console::warn_3(
&JsValue::from_str(&format!(
"[WARNING] Non-fatal error at {location}, while \
calling {name} on "
)),
el,
&err,
);
}
}
#[cfg(not(debug_assertions))]
{
_ = self;
}
}
#[track_caller]
fn ok_or_debug(
self,
el: &Node,
name: &'static str,
) -> Option<Self::Output> {
#[cfg(debug_assertions)]
{
if let Err(err) = &self {
let location = std::panic::Location::caller();
web_sys::console::warn_3(
&JsValue::from_str(&format!(
"[WARNING] Non-fatal error at {location}, while \
calling {name} on "
)),
el,
err,
);
}
self.ok()
}
#[cfg(not(debug_assertions))]
{
self.ok()
}
}
}
#[macro_export]
macro_rules! or_debug {
($action:expr, $el:expr, $label:literal) => {
if cfg!(debug_assertions) {
$crate::UnwrapOrDebug::or_debug($action, $el, $label);
} else {
_ = $action;
}
};
}
#[macro_export]
macro_rules! ok_or_debug {
($action:expr, $el:expr, $label:literal) => {
if cfg!(debug_assertions) {
$crate::UnwrapOrDebug::ok_or_debug($action, $el, $label)
} else {
$action.ok()
}
};
}

169
tachys/src/mathml/mod.rs Normal file
View file

@ -0,0 +1,169 @@
use crate::{
html::{
attribute::{Attr, Attribute, AttributeValue},
element::{
CreateElement, ElementType, ElementWithChildren, HtmlElement,
},
},
renderer::{dom::Dom, Renderer},
view::Render,
};
use next_tuple::TupleBuilder;
use once_cell::unsync::Lazy;
use std::{fmt::Debug, marker::PhantomData};
macro_rules! mathml_global {
($tag:ty, $attr:ty) => {
paste::paste! {
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
Ch, Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
}
}
}
macro_rules! mathml_elements {
($($tag:ident [$($attr:ty),*]),* $(,)?) => {
paste::paste! {
$(
// `tag()` function
pub fn $tag<Rndr>() -> HtmlElement<[<$tag:camel>], (), (), Rndr>
where
Rndr: Renderer
{
HtmlElement {
tag: [<$tag:camel>],
attributes: (),
children: (),
rndr: PhantomData,
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct [<$tag:camel>];
impl<At, Ch, Rndr> HtmlElement<[<$tag:camel>], At, Ch, Rndr>
where
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
mathml_global!($tag, displaystyle);
mathml_global!($tag, href);
mathml_global!($tag, id);
mathml_global!($tag, mathbackground);
mathml_global!($tag, mathcolor);
mathml_global!($tag, mathsize);
mathml_global!($tag, mathvariant);
mathml_global!($tag, scriptlevel);
$(
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
Ch, Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
)*
}
impl ElementType for [<$tag:camel>] {
type Output = web_sys::Element;
const TAG: &'static str = stringify!($tag);
const SELF_CLOSING: bool = false;
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl ElementWithChildren for [<$tag:camel>] {}
impl CreateElement<Dom> for [<$tag:camel>] {
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::JsCast;
thread_local! {
static ELEMENT: Lazy<<Dom as Renderer>::Element> = Lazy::new(|| {
crate::dom::document().create_element_ns(
Some(wasm_bindgen::intern("http://www.w3.org/1998/Math/MathML")),
stringify!($tag)
).unwrap()
});
}
ELEMENT.with(|e| e.clone_node()).unwrap().unchecked_into()
}
}
)*
}
}
}
mathml_elements![
math [display, xmlns],
mi [],
mn [],
mo [
accent, fence, lspace, maxsize, minsize, movablelimits,
rspace, separator, stretchy, symmetric
],
ms [],
mspace [height, width],
mtext [],
menclose [notation],
merror [],
mfenced [],
mfrac [linethickness],
mpadded [depth, height, voffset, width],
mphantom [],
mroot [],
mrow [],
msqrt [],
mstyle [],
mmultiscripts [],
mover [accent],
mprescripts [],
msub [],
msubsup [],
msup [],
munder [accentunder],
munderover [accent, accentunder],
mtable [
align, columnalign, columnlines, columnspacing, frame,
framespacing, rowalign, rowlines, rowspacing, width
],
mtd [columnalign, columnspan, rowalign, rowspan],
mtr [columnalign, rowalign],
maction [],
annotation [],
semantics [],
];

401
tachys/src/renderer/dom.rs Normal file
View file

@ -0,0 +1,401 @@
#[cfg(any(feature = "tokio", feature = "web"))]
use super::SpawningRenderer;
use super::{CastFrom, DomRenderer, Renderer};
use crate::{
dom::{document, window},
ok_or_debug, or_debug,
view::Mountable,
};
use rustc_hash::FxHashSet;
use std::{borrow::Cow, cell::RefCell};
use wasm_bindgen::{intern, prelude::Closure, JsCast, JsValue};
use web_sys::{
Comment, CssStyleDeclaration, DocumentFragment, DomTokenList, Element,
HtmlElement, Node, Text,
};
pub struct Dom;
thread_local! {
pub(crate) static GLOBAL_EVENTS: RefCell<FxHashSet<Cow<'static, str>>> = Default::default();
}
impl Renderer for Dom {
type Node = Node;
type Text = Text;
type Element = Element;
type Placeholder = Comment;
fn create_text_node(text: &str) -> Self::Text {
document().create_text_node(text)
}
fn create_placeholder() -> Self::Placeholder {
document().create_comment("")
}
fn set_text(node: &Self::Text, text: &str) {
node.set_node_value(Some(text));
}
fn set_attribute(node: &Self::Element, name: &str, value: &str) {
or_debug!(
node.set_attribute(intern(name), value),
node,
"setAttribute"
);
}
fn remove_attribute(node: &Self::Element, name: &str) {
or_debug!(node.remove_attribute(intern(name)), node, "removeAttribute");
}
fn insert_node(
parent: &Self::Element,
new_child: &Self::Node,
anchor: Option<&Self::Node>,
) {
ok_or_debug!(
parent.insert_before(new_child, anchor),
parent,
"insertNode"
);
}
fn remove_node(
parent: &Self::Element,
child: &Self::Node,
) -> Option<Self::Node> {
ok_or_debug!(parent.remove_child(child), parent, "removeNode")
}
fn remove(node: &Self::Node) {
node.unchecked_ref::<Element>().remove();
}
fn get_parent(node: &Self::Node) -> Option<Self::Node> {
node.parent_node()
}
fn first_child(node: &Self::Node) -> Option<Self::Node> {
node.first_child()
}
fn next_sibling(node: &Self::Node) -> Option<Self::Node> {
node.next_sibling()
}
fn log_node(node: &Self::Node) {
web_sys::console::log_1(node);
}
fn clear_children(parent: &Self::Element) {
parent.set_text_content(Some(""));
}
}
impl DomRenderer for Dom {
type Event = JsValue;
type ClassList = DomTokenList;
type CssStyleDeclaration = CssStyleDeclaration;
fn set_property(el: &Self::Element, key: &str, value: &JsValue) {
or_debug!(
js_sys::Reflect::set(
el,
&wasm_bindgen::JsValue::from_str(intern(key)),
value,
),
el,
"setProperty"
);
}
fn add_event_listener(
el: &Self::Element,
name: &str,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)> {
let cb = wasm_bindgen::closure::Closure::wrap(cb);
let name = intern(name);
or_debug!(
el.add_event_listener_with_callback(
name,
cb.as_ref().unchecked_ref()
),
el,
"addEventListener"
);
// return the remover
Box::new({
let name = name.to_owned();
move |el| {
or_debug!(
el.remove_event_listener_with_callback(
intern(&name),
cb.as_ref().unchecked_ref()
),
el,
"removeEventListener"
)
}
})
}
fn add_event_listener_delegated(
el: &Self::Element,
name: Cow<'static, str>,
delegation_key: Cow<'static, str>,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)> {
let cb = Closure::wrap(cb).into_js_value();
let key = intern(&delegation_key);
or_debug!(
js_sys::Reflect::set(el, &JsValue::from_str(key), &cb),
el,
"set property"
);
GLOBAL_EVENTS.with(|global_events| {
let mut events = global_events.borrow_mut();
if !events.contains(&name) {
// create global handler
let key = JsValue::from_str(key);
let handler = move |ev: web_sys::Event| {
let target = ev.target();
let node = ev.composed_path().get(0);
let mut node = if node.is_undefined() || node.is_null() {
JsValue::from(target)
} else {
node
};
// TODO reverse Shadow DOM retargetting
// TODO simulate currentTarget
while !node.is_null() {
let node_is_disabled = js_sys::Reflect::get(
&node,
&JsValue::from_str("disabled"),
)
.unwrap()
.is_truthy();
if !node_is_disabled {
let maybe_handler =
js_sys::Reflect::get(&node, &key).unwrap();
if !maybe_handler.is_undefined() {
let f = maybe_handler
.unchecked_ref::<js_sys::Function>();
let _ = f.call1(&node, &ev);
if ev.cancel_bubble() {
return;
}
}
}
// navigate up tree
if let Some(parent) =
node.unchecked_ref::<web_sys::Node>().parent_node()
{
node = parent.into()
} else if let Some(root) =
node.dyn_ref::<web_sys::ShadowRoot>()
{
node = root.host().unchecked_into();
} else {
node = JsValue::null()
}
}
};
let handler =
Box::new(handler) as Box<dyn FnMut(web_sys::Event)>;
let handler = Closure::wrap(handler).into_js_value();
window()
.add_event_listener_with_callback(
&name,
handler.unchecked_ref(),
)
.unwrap();
// register that we've created handler
events.insert(name);
}
});
// return the remover
Box::new(move |el| {
or_debug!(
js_sys::Reflect::delete_property(
el,
&JsValue::from_str(intern(&delegation_key))
),
el,
"delete property"
);
})
}
fn class_list(el: &Self::Element) -> Self::ClassList {
el.class_list()
}
fn add_class(list: &Self::ClassList, name: &str) {
or_debug!(list.add_1(intern(name)), list.unchecked_ref(), "add()");
}
fn remove_class(list: &Self::ClassList, name: &str) {
or_debug!(
list.remove_1(intern(name)),
list.unchecked_ref(),
"remove()"
);
}
fn style(el: &Self::Element) -> Self::CssStyleDeclaration {
el.unchecked_ref::<HtmlElement>().style()
}
fn set_css_property(
style: &Self::CssStyleDeclaration,
name: &str,
value: &str,
) {
or_debug!(
style.set_property(intern(name), value),
style.unchecked_ref(),
"setProperty"
);
}
fn set_inner_html(el: &Self::Element, html: &str) {
el.set_inner_html(html);
}
}
impl Mountable<Dom> for Node {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
Dom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<Dom as Renderer>::Element,
child: &mut dyn Mountable<Dom>,
) -> bool {
child.mount(parent, Some(self));
true
}
}
impl Mountable<Dom> for Text {
fn unmount(&mut self) {
self.remove();
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
Dom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<Dom as Renderer>::Element,
child: &mut dyn Mountable<Dom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl Mountable<Dom> for Comment {
fn unmount(&mut self) {
self.remove();
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
Dom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<Dom as Renderer>::Element,
child: &mut dyn Mountable<Dom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl Mountable<Dom> for Element {
fn unmount(&mut self) {
self.remove();
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
Dom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<Dom as Renderer>::Element,
child: &mut dyn Mountable<Dom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl Mountable<Dom> for DocumentFragment {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
Dom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<Dom as Renderer>::Element,
child: &mut dyn Mountable<Dom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl CastFrom<Node> for Text {
fn cast_from(node: Node) -> Option<Text> {
node.clone().dyn_into().ok()
}
}
impl CastFrom<Node> for Comment {
fn cast_from(node: Node) -> Option<Comment> {
node.clone().dyn_into().ok()
}
}
impl CastFrom<Node> for Element {
fn cast_from(node: Node) -> Option<Element> {
node.clone().dyn_into().ok()
}
}
#[cfg(feature = "web")]
impl SpawningRenderer for Dom {
type Spawn = crate::spawner::wasm::Wasm;
}
#[cfg(all(feature = "tokio", not(feature = "web")))]
impl SpawningRenderer for Dom {
type Spawn = crate::spawner::tokio::Tokio;
}
/* Event Delegation */

View file

@ -0,0 +1,691 @@
#![allow(unused)]
//! A stupidly-simple mock DOM implementation that can be used for testing.
//!
//! Do not use this for anything real.
use super::{CastFrom, DomRenderer, Renderer};
use crate::{
html::element::{CreateElement, ElementType},
view::Mountable,
};
use slotmap::{new_key_type, SlotMap};
use std::{borrow::Cow, cell::RefCell, collections::HashMap, rc::Rc};
use wasm_bindgen::JsValue;
pub struct MockDom;
new_key_type! {
struct NodeId;
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Node(NodeId);
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Element(Node);
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Text(Node);
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Placeholder(Node);
impl AsRef<Node> for Node {
fn as_ref(&self) -> &Node {
self
}
}
impl AsRef<Node> for Element {
fn as_ref(&self) -> &Node {
&self.0
}
}
impl AsRef<Node> for Text {
fn as_ref(&self) -> &Node {
&self.0
}
}
impl AsRef<Node> for Placeholder {
fn as_ref(&self) -> &Node {
&self.0
}
}
pub fn node_eq(a: impl AsRef<Node>, b: impl AsRef<Node>) -> bool {
a.as_ref() == b.as_ref()
}
impl From<Text> for Node {
fn from(value: Text) -> Self {
Node(value.0 .0)
}
}
impl From<Element> for Node {
fn from(value: Element) -> Self {
Node(value.0 .0)
}
}
impl From<Placeholder> for Node {
fn from(value: Placeholder) -> Self {
Node(value.0 .0)
}
}
impl Element {
pub fn to_debug_html(&self) -> String {
let mut buf = String::new();
self.debug_html(&mut buf);
buf
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct NodeData {
parent: Option<NodeId>,
pub ty: NodeType,
}
trait DebugHtml {
fn debug_html(&self, buf: &mut String);
}
impl DebugHtml for Element {
fn debug_html(&self, buf: &mut String) {
Document::with_node(self.0 .0, |node| {
node.debug_html(buf);
});
}
}
impl DebugHtml for Text {
fn debug_html(&self, buf: &mut String) {
Document::with_node(self.0 .0, |node| {
node.debug_html(buf);
});
}
}
impl DebugHtml for Node {
fn debug_html(&self, buf: &mut String) {
Document::with_node(self.0, |node| {
node.debug_html(buf);
});
}
}
impl DebugHtml for NodeData {
fn debug_html(&self, buf: &mut String) {
match &self.ty {
NodeType::Text(text) => buf.push_str(text),
NodeType::Element {
tag,
attrs,
children,
} => {
buf.push('<');
buf.push_str(tag);
for (k, v) in attrs {
buf.push(' ');
buf.push_str(k);
buf.push_str("=\"");
buf.push_str(v);
buf.push('"');
}
buf.push('>');
for child in children {
child.debug_html(buf);
}
buf.push_str("</");
buf.push_str(tag);
buf.push('>');
}
NodeType::Placeholder => buf.push_str("<!>"),
}
}
}
#[derive(Clone)]
pub struct Document(Rc<RefCell<SlotMap<NodeId, NodeData>>>);
impl Document {
pub fn new() -> Self {
Document(Default::default())
}
fn with_node<U>(id: NodeId, f: impl FnOnce(&NodeData) -> U) -> Option<U> {
DOCUMENT.with(|d| {
let data = d.0.borrow();
let data = data.get(id);
data.map(f)
})
}
fn with_node_mut<U>(
id: NodeId,
f: impl FnOnce(&mut NodeData) -> U,
) -> Option<U> {
DOCUMENT.with(|d| {
let mut data = d.0.borrow_mut();
let data = data.get_mut(id);
data.map(f)
})
}
pub fn reset(&self) {
self.0.borrow_mut().clear();
}
fn create_element(&self, tag: &str) -> Element {
Element(Node(self.0.borrow_mut().insert(NodeData {
parent: None,
ty: NodeType::Element {
tag: tag.to_string().into(),
attrs: HashMap::new(),
children: Vec::new(),
},
})))
}
fn create_text_node(&self, data: &str) -> Text {
Text(Node(self.0.borrow_mut().insert(NodeData {
parent: None,
ty: NodeType::Text(data.to_string()),
})))
}
fn create_placeholder(&self) -> Placeholder {
Placeholder(Node(self.0.borrow_mut().insert(NodeData {
parent: None,
ty: NodeType::Placeholder,
})))
}
}
// TODO!
impl DomRenderer for MockDom {
type Event = ();
type ClassList = ();
type CssStyleDeclaration = ();
fn set_property(el: &Self::Element, key: &str, value: &JsValue) {
todo!()
}
fn add_event_listener(
el: &Self::Element,
name: &str,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)> {
todo!()
}
fn add_event_listener_delegated(
el: &Self::Element,
name: Cow<'static, str>,
delegation_key: Cow<'static, str>,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)> {
todo!()
}
fn class_list(el: &Self::Element) -> Self::ClassList {
todo!()
}
fn add_class(class_list: &Self::ClassList, name: &str) {
todo!()
}
fn remove_class(class_list: &Self::ClassList, name: &str) {
todo!()
}
fn style(el: &Self::Element) -> Self::CssStyleDeclaration {
todo!()
}
fn set_css_property(
style: &Self::CssStyleDeclaration,
name: &str,
value: &str,
) {
todo!()
}
fn set_inner_html(el: &Self::Element, html: &str) {
todo!()
}
}
impl Default for Document {
fn default() -> Self {
Self::new()
}
}
thread_local! {
static DOCUMENT: Document = Document::new();
}
pub fn document() -> Document {
DOCUMENT.with(Clone::clone)
}
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType {
Text(String),
Element {
tag: Cow<'static, str>,
attrs: HashMap<String, String>,
children: Vec<Node>,
},
Placeholder,
}
impl Mountable<MockDom> for Node {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
MockDom::insert_node(parent, self, marker);
}
fn insert_before_this(
&self,
parent: &<MockDom as Renderer>::Element,
child: &mut dyn Mountable<MockDom>,
) -> bool {
child.mount(parent, Some(self));
true
}
}
impl Mountable<MockDom> for Text {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
MockDom::insert_node(parent, self.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<MockDom as Renderer>::Element,
child: &mut dyn Mountable<MockDom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl Mountable<MockDom> for Element {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
MockDom::insert_node(parent, self.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<MockDom as Renderer>::Element,
child: &mut dyn Mountable<MockDom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl Mountable<MockDom> for Placeholder {
fn unmount(&mut self) {
todo!()
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
MockDom::insert_node(parent, self.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<MockDom as Renderer>::Element,
child: &mut dyn Mountable<MockDom>,
) -> bool {
child.mount(parent, Some(self.as_ref()));
true
}
}
impl<E: ElementType> CreateElement<MockDom> for E {
fn create_element(&self) -> <MockDom as Renderer>::Element {
document().create_element(E::TAG)
}
}
impl Renderer for MockDom {
type Node = Node;
type Text = Text;
type Element = Element;
type Placeholder = Placeholder;
fn create_text_node(data: &str) -> Self::Text {
document().create_text_node(data)
}
fn create_placeholder() -> Self::Placeholder {
document().create_placeholder()
}
fn set_text(node: &Self::Text, text: &str) {
Document::with_node_mut(node.0 .0, |node| {
if let NodeType::Text(ref mut node) = node.ty {
*node = text.to_string();
}
});
}
fn set_attribute(node: &Self::Element, name: &str, value: &str) {
Document::with_node_mut(node.0 .0, |node| {
if let NodeType::Element { ref mut attrs, .. } = node.ty {
attrs.insert(name.to_string(), value.to_string());
}
});
}
fn remove_attribute(node: &Self::Element, name: &str) {
Document::with_node_mut(node.0 .0, |node| {
if let NodeType::Element { ref mut attrs, .. } = node.ty {
attrs.remove(name);
}
});
}
fn insert_node(
parent: &Self::Element,
new_child: &Self::Node,
anchor: Option<&Self::Node>,
) {
debug_assert!(&parent.0 != new_child);
// remove if already mounted
if let Some(parent) = MockDom::get_parent(new_child) {
let parent = Element(parent);
MockDom::remove_node(&parent, new_child);
}
// mount on new parent
Document::with_node_mut(parent.0 .0, |parent| {
if let NodeType::Element {
ref mut children, ..
} = parent.ty
{
match anchor {
None => children.push(new_child.clone()),
Some(anchor) => {
let anchor_pos = children
.iter()
.position(|item| item.0 == anchor.0)
.expect("anchor is not a child of the parent");
children.insert(anchor_pos, new_child.clone());
}
}
} else {
panic!("parent is not an element");
}
});
// set parent on child node
Document::with_node_mut(new_child.0, |node| {
node.parent = Some(parent.0 .0)
});
}
fn remove_node(
parent: &Self::Element,
child: &Self::Node,
) -> Option<Self::Node> {
let child = Document::with_node_mut(parent.0 .0, |parent| {
if let NodeType::Element {
ref mut children, ..
} = parent.ty
{
let current_pos = children
.iter()
.position(|item| item.0 == child.0)
.expect("anchor is not a child of the parent");
Some(children.remove(current_pos))
} else {
None
}
})
.flatten()?;
Document::with_node_mut(child.0, |node| {
node.parent = None;
});
Some(child)
}
fn remove(node: &Self::Node) {
let parent = Element(Node(
Self::get_parent(node)
.expect("tried to remove a parentless node")
.0,
));
Self::remove_node(&parent, node);
}
fn get_parent(node: &Self::Node) -> Option<Self::Node> {
Document::with_node(node.0, |node| node.parent)
.flatten()
.map(Node)
}
fn first_child(node: &Self::Node) -> Option<Self::Node> {
Document::with_node(node.0, |node| match &node.ty {
NodeType::Text(_) => None,
NodeType::Element { children, .. } => children.get(0).cloned(),
NodeType::Placeholder => None,
})
.flatten()
}
fn next_sibling(node: &Self::Node) -> Option<Self::Node> {
let node_id = node.0;
Document::with_node(node_id, |node| {
node.parent.and_then(|parent| {
Document::with_node(parent, |parent| match &parent.ty {
NodeType::Element { children, .. } => {
let this = children
.iter()
.position(|check| check == &Node(node_id))?;
children.get(this + 1).cloned()
}
_ => panic!(
"Called next_sibling with parent as a node that's not \
an Element."
),
})
})
})
.flatten()
.flatten()
}
fn log_node(node: &Self::Node) {
println!("{node:?}");
}
fn clear_children(parent: &Self::Element) {
let prev_children =
Document::with_node_mut(parent.0 .0, |node| match node.ty {
NodeType::Element {
ref mut children, ..
} => std::mem::take(children),
_ => panic!("Called clear_children on a non-Element node."),
})
.unwrap_or_default();
for child in prev_children {
Document::with_node_mut(child.0, |node| {
node.parent = None;
});
}
}
}
impl CastFrom<Node> for Text {
fn cast_from(source: Node) -> Option<Self> {
Document::with_node(source.0, |node| {
matches!(node.ty, NodeType::Text(_))
})
.and_then(|matches| matches.then_some(Text(Node(source.0))))
}
}
impl CastFrom<Node> for Element {
fn cast_from(source: Node) -> Option<Self> {
Document::with_node(source.0, |node| {
matches!(node.ty, NodeType::Element { .. })
})
.and_then(|matches| matches.then_some(Element(Node(source.0))))
}
}
impl CastFrom<Node> for Placeholder {
fn cast_from(source: Node) -> Option<Self> {
Document::with_node(source.0, |node| {
matches!(node.ty, NodeType::Placeholder)
})
.and_then(|matches| matches.then_some(Placeholder(Node(source.0))))
}
}
#[cfg(test)]
mod tests {
use super::MockDom;
use crate::{
html::element,
renderer::{mock_dom::node_eq, Renderer},
};
#[test]
fn html_debugging_works() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
MockDom::set_attribute(&p, "id", "foo");
let text = MockDom::create_text_node("Hello, world!");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&p, text.as_ref(), None);
assert_eq!(
main.to_debug_html(),
"<main><p id=\"foo\">Hello, world!</p></main>"
);
}
#[test]
fn remove_attribute_works() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
MockDom::set_attribute(&p, "id", "foo");
let text = MockDom::create_text_node("Hello, world!");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&p, text.as_ref(), None);
MockDom::remove_attribute(&p, "id");
assert_eq!(main.to_debug_html(), "<main><p>Hello, world!</p></main>");
}
#[test]
fn remove_node_works() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
MockDom::set_attribute(&p, "id", "foo");
let text = MockDom::create_text_node("Hello, world!");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&p, text.as_ref(), None);
MockDom::remove_node(&main, p.as_ref());
assert_eq!(main.to_debug_html(), "<main></main>");
}
#[test]
fn insert_before_works() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
let span = MockDom::create_element(element::Span);
let text = MockDom::create_text_node("Hello, world!");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&span, text.as_ref(), None);
MockDom::insert_node(&main, span.as_ref(), Some(p.as_ref()));
assert_eq!(
main.to_debug_html(),
"<main><span>Hello, world!</span><p></p></main>"
);
}
#[test]
fn insert_before_sets_parent() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
MockDom::insert_node(&main, p.as_ref(), None);
let parent =
MockDom::get_parent(p.as_ref()).expect("p should have parent set");
assert!(node_eq(parent, main));
}
#[test]
fn insert_before_moves_node() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
let span = MockDom::create_element(element::Span);
let text = MockDom::create_text_node("Hello, world!");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&span, text.as_ref(), None);
MockDom::insert_node(&main, span.as_ref(), Some(p.as_ref()));
MockDom::insert_node(&main, p.as_ref(), Some(span.as_ref()));
assert_eq!(
main.to_debug_html(),
"<main><p></p><span>Hello, world!</span></main>"
);
}
#[test]
fn first_child_gets_first_child() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
let span = MockDom::create_element(element::Span);
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&p, span.as_ref(), None);
assert_eq!(
MockDom::first_child(main.as_ref()).as_ref(),
Some(p.as_ref())
);
assert_eq!(
MockDom::first_child(&MockDom::first_child(main.as_ref()).unwrap())
.as_ref(),
Some(span.as_ref())
);
}
#[test]
fn next_sibling_gets_next_sibling() {
let main = MockDom::create_element(element::Main);
let p = MockDom::create_element(element::P);
let span = MockDom::create_element(element::Span);
let text = MockDom::create_text_node("foo");
MockDom::insert_node(&main, p.as_ref(), None);
MockDom::insert_node(&main, span.as_ref(), None);
MockDom::insert_node(&main, text.as_ref(), None);
assert_eq!(
MockDom::next_sibling(p.as_ref()).as_ref(),
Some(span.as_ref())
);
assert_eq!(
MockDom::next_sibling(span.as_ref()).as_ref(),
Some(text.as_ref())
);
}
}

164
tachys/src/renderer/mod.rs Normal file
View file

@ -0,0 +1,164 @@
use crate::{html::element::CreateElement, spawner::Spawner, view::Mountable};
use std::borrow::Cow;
use wasm_bindgen::JsValue;
pub mod dom;
#[cfg(feature = "testing")]
pub mod mock_dom;
/// Implements the instructions necessary to render an interface on some platform.
/// By default, this is implemented for the Document Object Model (DOM) in a Web
/// browser, but implementing this trait for some other platform allows you to use
/// the library to render any tree-based UI.
pub trait Renderer: Sized {
/// The basic type of node in the view tree.
type Node: Mountable<Self>;
/// A visible element in the view tree.
type Element: AsRef<Self::Node> + CastFrom<Self::Node> + Mountable<Self>;
/// A text node in the view tree.
type Text: AsRef<Self::Node> + CastFrom<Self::Node> + Mountable<Self>;
/// A placeholder node, which can be inserted into the tree but does not
/// appear (e.g., a comment node in the DOM).
type Placeholder: AsRef<Self::Node>
+ CastFrom<Self::Node>
+ Mountable<Self>
+ Clone;
/// Creates a new element node.
fn create_element<E: CreateElement<Self>>(tag: E) -> Self::Element {
tag.create_element()
}
/// Creates a new text node.
fn create_text_node(text: &str) -> Self::Text;
/// Creates a new placeholder node.
fn create_placeholder() -> Self::Placeholder;
/// Sets the text content of the node. If it's not a text node, this does nothing.
fn set_text(node: &Self::Text, text: &str);
/// Sets the given attribute on the given node by key and value.
fn set_attribute(node: &Self::Element, name: &str, value: &str);
/// Removes the given attribute on the given node.
fn remove_attribute(node: &Self::Element, name: &str);
/// Appends the new child to the parent, before the anchor node. If `anchor` is `None`,
/// append to the end of the parent's children.
fn insert_node(
parent: &Self::Element,
new_child: &Self::Node,
marker: Option<&Self::Node>,
);
/// Mounts the new child before the marker as its sibling.
///
/// ## Panics
/// The default implementation panics if `before` does not have a parent [`R::Element`].
fn mount_before<M>(new_child: &mut M, before: &Self::Node)
where
M: Mountable<Self>,
{
let parent = Self::Element::cast_from(
Self::get_parent(before).expect("node should have parent"),
)
.expect("placeholder parent should be Element");
new_child.mount(&parent, Some(before));
}
/// Removes the child node from the parents, and returns the removed node.
fn remove_node(
parent: &Self::Element,
child: &Self::Node,
) -> Option<Self::Node>;
/// Removes all children from the parent element.
fn clear_children(parent: &Self::Element);
/// Removes the node.
fn remove(node: &Self::Node);
/// Gets the parent of the given node, if any.
fn get_parent(node: &Self::Node) -> Option<Self::Node>;
/// Returns the first child node of the given node, if any.
fn first_child(node: &Self::Node) -> Option<Self::Node>;
/// Returns the next sibling of the given node, if any.
fn next_sibling(node: &Self::Node) -> Option<Self::Node>;
fn log_node(node: &Self::Node);
}
/// Additional rendering behavior that applies only to DOM nodes.
pub trait DomRenderer: Renderer {
/// Generic event type, from which any specific event can be converted.
type Event;
/// The list of CSS classes for an element.
type ClassList;
/// The CSS styles for an element.
type CssStyleDeclaration;
/// Sets a JavaScript object property on a DOM element.
fn set_property(el: &Self::Element, key: &str, value: &JsValue);
/// Adds an event listener to an element.
///
/// Returns a function to remove the listener.
fn add_event_listener(
el: &Self::Element,
name: &str,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)>;
/// Adds an event listener to an element, delegated to the window if possible.
///
/// Returns a function to remove the listener.
fn add_event_listener_delegated(
el: &Self::Element,
name: Cow<'static, str>,
delegation_key: Cow<'static, str>,
cb: Box<dyn FnMut(Self::Event)>,
) -> Box<dyn FnOnce(&Self::Element)>;
/// The list of CSS classes for an element.
fn class_list(el: &Self::Element) -> Self::ClassList;
/// Add a class to the list.
fn add_class(class_list: &Self::ClassList, name: &str);
/// Remove a class from the list.
fn remove_class(class_list: &Self::ClassList, name: &str);
/// The set of styles for an element.
fn style(el: &Self::Element) -> Self::CssStyleDeclaration;
/// Sets a CSS property.
fn set_css_property(
style: &Self::CssStyleDeclaration,
name: &str,
value: &str,
);
/// Sets the `innerHTML` of a DOM element, without escaping any values.
fn set_inner_html(el: &Self::Element, html: &str);
}
/// A renderer that is able to spawn async tasks during rendering.
pub trait SpawningRenderer: Renderer {
type Spawn: Spawner;
}
/// Attempts to cast from one type to another.
///
/// This works in a similar way to `TryFrom`. We implement it as a separate trait
/// simply so we don't have to create wrappers for the `web_sys` types; it can't be
/// implemented on them directly because of the orphan rules.
pub trait CastFrom<T>
where
Self: Sized,
{
fn cast_from(source: T) -> Option<Self>;
}

93
tachys/src/spawner/mod.rs Normal file
View file

@ -0,0 +1,93 @@
use std::future::Future;
/// Allows spawning a [`Future`] to be run in a separate task.
pub trait Spawner {
fn spawn<Fut>(fut: Fut)
where
Fut: Future + Send + Sync + 'static;
fn spawn_local<Fut>(fut: Fut)
where
Fut: Future + 'static;
}
/// A spawner that will block in place when spawning an async task.
///
/// This is mostly useful for testing, and especially for synchronous-only code.
pub struct BlockSpawn;
impl Spawner for BlockSpawn {
fn spawn<Fut>(fut: Fut)
where
Fut: Future + Send + Sync + 'static,
{
futures::executor::block_on(async move {
fut.await;
});
}
fn spawn_local<Fut>(fut: Fut)
where
Fut: Future + 'static,
{
futures::executor::block_on(async move {
fut.await;
});
}
}
#[cfg(feature = "web")]
pub mod wasm {
use super::Spawner;
use wasm_bindgen_futures::spawn_local;
#[derive(Debug, Copy, Clone)]
pub struct Wasm;
impl Spawner for Wasm {
fn spawn<Fut>(fut: Fut)
where
Fut: futures::Future + Send + Sync + 'static,
{
Self::spawn_local(fut);
}
fn spawn_local<Fut>(fut: Fut)
where
Fut: futures::Future + 'static,
{
spawn_local(async move {
fut.await;
});
}
}
}
#[cfg(feature = "tokio")]
pub mod tokio {
use super::Spawner;
use tokio::task::{spawn, spawn_local};
#[derive(Debug, Copy, Clone)]
pub struct Tokio;
impl Spawner for Tokio {
fn spawn<Fut>(fut: Fut)
where
Fut: futures::Future + Send + Sync + 'static,
{
spawn(async move {
fut.await;
});
}
fn spawn_local<Fut>(fut: Fut)
where
Fut: futures::Future + 'static,
{
spawn_local(async move {
fut.await;
});
}
}
}

560
tachys/src/ssr/mod.rs Normal file
View file

@ -0,0 +1,560 @@
use crate::{
renderer::Renderer,
view::{Position, PositionState, RenderHtml},
};
use futures::Stream;
use std::{
collections::VecDeque,
fmt::{Debug, Write},
future::Future,
mem,
pin::Pin,
task::{Context, Poll},
};
#[derive(Default)]
pub struct StreamBuilder {
sync_buf: String,
chunks: VecDeque<StreamChunk>,
pending: Option<ChunkFuture>,
pending_ooo: VecDeque<ChunkFuture>,
id: Option<Vec<u16>>,
}
type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send + Sync>>;
type ChunkFuture = PinnedFuture<VecDeque<StreamChunk>>;
impl StreamBuilder {
pub fn new(id: Option<Vec<u16>>) -> Self {
Self {
id,
..Default::default()
}
}
pub fn push_sync(&mut self, string: &str) {
self.sync_buf.push_str(string);
}
pub fn push_async(
&mut self,
should_block: bool,
fut: impl Future<Output = VecDeque<StreamChunk>> + Send + Sync + 'static,
) {
// flush sync chunk
let sync = mem::take(&mut self.sync_buf);
if !sync.is_empty() {
self.chunks.push_back(StreamChunk::Sync(sync));
}
self.chunks.push_back(StreamChunk::Async {
chunks: Box::pin(fut) as PinnedFuture<VecDeque<StreamChunk>>,
should_block,
});
}
pub fn with_buf(&mut self, fun: impl FnOnce(&mut String)) {
fun(&mut self.sync_buf)
}
pub fn take_chunks(&mut self) -> VecDeque<StreamChunk> {
let sync = mem::take(&mut self.sync_buf);
if !sync.is_empty() {
self.chunks.push_back(StreamChunk::Sync(sync));
}
mem::take(&mut self.chunks)
}
pub fn append(&mut self, mut other: StreamBuilder) {
self.chunks.append(&mut other.chunks);
self.sync_buf.push_str(&other.sync_buf);
}
pub fn finish(mut self) -> Self {
let sync_buf_remaining = mem::take(&mut self.sync_buf);
if sync_buf_remaining.is_empty() {
return self;
} else if let Some(StreamChunk::Sync(buf)) = self.chunks.back_mut() {
buf.push_str(&sync_buf_remaining);
} else {
self.chunks.push_back(StreamChunk::Sync(sync_buf_remaining));
}
self
}
// Out-of-Order Streaming
pub fn push_fallback<View, Rndr>(
&mut self,
fallback: View,
position: &mut Position,
) where
View: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
self.write_chunk_marker(true);
fallback.to_html_with_buf(&mut self.sync_buf, position);
self.write_chunk_marker(false);
*position = Position::NextChild;
}
pub fn next_id(&mut self) {
if let Some(last) = self.id.as_mut().and_then(|ids| ids.last_mut()) {
*last += 1;
}
}
pub fn clone_id(&self) -> Option<Vec<u16>> {
self.id.clone()
}
pub fn child_id(&self) -> Option<Vec<u16>> {
let mut child = self.id.clone();
if let Some(child) = child.as_mut() {
child.push(0);
}
child
}
pub fn write_chunk_marker(&mut self, opening: bool) {
if let Some(id) = &self.id {
self.sync_buf.reserve(11 + (id.len() * 2));
self.sync_buf.push_str("<!--s-");
for piece in id {
write!(&mut self.sync_buf, "{}-", piece).unwrap();
}
if opening {
self.sync_buf.push_str("o-->");
} else {
self.sync_buf.push_str("c-->");
}
}
}
pub fn push_async_out_of_order<View, Rndr>(
&mut self,
should_block: bool,
view: impl Future<Output = View> + Send + Sync + 'static,
position: &mut Position,
) where
View: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
let id = self.clone_id();
// copy so it's not updated by additional iterations
// i.e., restart in the same position we were at when we suspended
let mut position = *position;
self.chunks.push_back(StreamChunk::OutOfOrder {
should_block,
chunks: Box::pin(async move {
let view = view.await;
let mut subbuilder = StreamBuilder::new(id);
let mut id = String::new();
if let Some(ids) = &subbuilder.id {
for piece in ids {
write!(&mut id, "{}-", piece).unwrap();
}
}
subbuilder.sync_buf.reserve(591 + id.len()); // TODO size
subbuilder.sync_buf.push_str("<template id=\"");
subbuilder.sync_buf.push_str(&id);
subbuilder.sync_buf.push('f');
subbuilder.sync_buf.push_str("\">");
if let Some(id) = subbuilder.id.as_mut() {
id.push(0);
}
view.to_html_async_with_buf::<true>(
&mut subbuilder,
&mut position,
);
subbuilder.sync_buf.push_str("<!></template>");
// TODO nonce
subbuilder.sync_buf.push_str("<script");
subbuilder.sync_buf.push_str(r#">(function() { let id = ""#);
subbuilder.sync_buf.push_str(&id);
subbuilder.sync_buf.push_str(
"\";let open = undefined;let close = undefined;let walker \
= document.createTreeWalker(document.body, \
NodeFilter.SHOW_COMMENT);while(walker.nextNode()) \
{if(walker.currentNode.textContent == `s-${id}o`){ \
open=walker.currentNode; } else \
if(walker.currentNode.textContent == `s-${id}c`) { close \
= walker.currentNode;}}let range = new Range(); \
range.setStartBefore(open); range.setEndBefore(close); \
range.deleteContents(); let tpl = \
document.getElementById(`${id}f`); \
close.parentNode.insertBefore(tpl.content.\
cloneNode(true), close);close.remove();})()",
);
subbuilder.sync_buf.push_str("</script>");
subbuilder.finish().take_chunks()
}),
});
}
}
impl Debug for StreamBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StreamBuilderInner")
.field("sync_buf", &self.sync_buf)
.field("chunks", &self.chunks)
.field("pending", &self.pending.is_some())
.finish()
}
}
pub enum StreamChunk {
Sync(String),
Async {
chunks: PinnedFuture<VecDeque<StreamChunk>>,
should_block: bool,
},
OutOfOrder {
chunks: PinnedFuture<VecDeque<StreamChunk>>,
should_block: bool,
},
}
impl Debug for StreamChunk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Sync(arg0) => f.debug_tuple("Sync").field(arg0).finish(),
Self::Async { should_block, .. } => f
.debug_struct("Async")
.field("should_block", should_block)
.finish_non_exhaustive(),
Self::OutOfOrder { should_block, .. } => f
.debug_struct("OutOfOrder")
.field("should_block", should_block)
.finish_non_exhaustive(),
}
}
}
// TODO handle should_block
impl Stream for StreamBuilder {
type Item = String;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut();
let pending = this.pending.take();
if let Some(mut pending) = pending {
match pending.as_mut().poll(cx) {
Poll::Pending => {
this.pending = Some(pending);
Poll::Pending
}
Poll::Ready(chunks) => {
for chunk in chunks.into_iter().rev() {
this.chunks.push_front(chunk);
}
self.poll_next(cx)
}
}
} else {
let next_chunk = this.chunks.pop_front();
match next_chunk {
None => {
let sync_buf = mem::take(&mut this.sync_buf);
if sync_buf.is_empty() {
// now, handle out-of-order chunks
if let Some(mut pending) = this.pending_ooo.pop_front()
{
match pending.as_mut().poll(cx) {
Poll::Ready(chunks) => {
for chunk in chunks.into_iter().rev() {
this.chunks.push_front(chunk);
}
self.poll_next(cx)
}
Poll::Pending => {
this.pending_ooo.push_back(pending);
Poll::Pending
}
}
} else {
Poll::Ready(None)
}
} else {
Poll::Ready(Some(sync_buf))
}
}
Some(StreamChunk::Sync(mut value)) => {
loop {
match this.chunks.pop_front() {
None => break,
Some(StreamChunk::Async {
chunks,
should_block,
}) => {
this.chunks.push_front(StreamChunk::Async {
chunks,
should_block,
});
break;
}
Some(StreamChunk::OutOfOrder {
chunks, ..
}) => {
this.pending_ooo.push_back(chunks);
break;
}
Some(StreamChunk::Sync(next)) => {
value.push_str(&next);
}
}
}
let sync_buf = mem::take(&mut this.sync_buf);
value.push_str(&sync_buf);
Poll::Ready(Some(value))
}
Some(StreamChunk::Async { chunks, .. }) => {
this.pending = Some(chunks);
self.poll_next(cx)
}
Some(StreamChunk::OutOfOrder { chunks, .. }) => {
this.pending_ooo.push_back(chunks);
self.poll_next(cx)
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::{
async_views::{FutureViewExt, Suspend},
html::element::{em, main, p, ElementChild, HtmlElement, Main},
renderer::dom::Dom,
view::RenderHtml,
};
use futures::StreamExt;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::test]
async fn in_order_stream_of_sync_content_ready_immediately() {
let el: HtmlElement<Main, _, _, Dom> = main().child(p().child((
"Hello, ",
em().child("beautiful"),
" world!",
)));
let mut stream = el.to_html_stream_in_order();
let html = stream.next().await.unwrap();
assert_eq!(
html,
"<main><p>Hello, <em>beautiful</em> world!</p></main>"
);
}
#[tokio::test]
async fn in_order_single_async_block_in_stream() {
let el = async {
sleep(Duration::from_millis(250)).await;
"Suspended"
}
.suspend();
let mut stream =
<Suspend<false, _, _> as RenderHtml<Dom>>::to_html_stream_in_order(
el,
);
let html = stream.next().await.unwrap();
assert_eq!(html, "Suspended<!>");
}
#[tokio::test]
async fn in_order_async_with_siblings_in_stream() {
let el = (
"Before Suspense",
async {
sleep(Duration::from_millis(250)).await;
"Suspended"
}
.suspend(),
);
let mut stream =
<(&str, Suspend<false, _, _>) as RenderHtml<Dom>>::to_html_stream_in_order(
el,
);
assert_eq!(stream.next().await.unwrap(), "Before Suspense");
assert_eq!(stream.next().await.unwrap(), "<!>Suspended");
assert!(stream.next().await.is_none());
}
#[tokio::test]
async fn in_order_async_inside_element_in_stream() {
let el: HtmlElement<_, _, _, Dom> = p().child((
"Before Suspense",
async {
sleep(Duration::from_millis(250)).await;
"Suspended"
}
.suspend(),
));
let mut stream = el.to_html_stream_in_order();
assert_eq!(stream.next().await.unwrap(), "<p>Before Suspense");
assert_eq!(stream.next().await.unwrap(), "<!>Suspended</p>");
assert!(stream.next().await.is_none());
}
#[tokio::test]
async fn in_order_nested_async_blocks() {
let el: HtmlElement<_, _, _, Dom> = main().child((
"Before Suspense",
async {
sleep(Duration::from_millis(250)).await;
p().child((
"Before inner Suspense",
async {
sleep(Duration::from_millis(250)).await;
"Inner Suspense"
}
.suspend(),
))
}
.suspend(),
));
let mut stream = el.to_html_stream_in_order();
assert_eq!(stream.next().await.unwrap(), "<main>Before Suspense");
assert_eq!(stream.next().await.unwrap(), "<p>Before inner Suspense");
assert_eq!(
stream.next().await.unwrap(),
"<!>Inner Suspense</p></main>"
);
}
#[tokio::test]
async fn out_of_order_stream_of_sync_content_ready_immediately() {
let el: HtmlElement<Main, _, _, Dom> = main().child(p().child((
"Hello, ",
em().child("beautiful"),
" world!",
)));
let mut stream = el.to_html_stream_out_of_order();
let html = stream.next().await.unwrap();
assert_eq!(
html,
"<main><p>Hello, <em>beautiful</em> world!</p></main>"
);
}
#[tokio::test]
async fn out_of_order_single_async_block_in_stream() {
let el = async {
sleep(Duration::from_millis(250)).await;
"Suspended"
}
.suspend()
.with_fallback("Loading...");
let mut stream =
<Suspend<false, _, _> as RenderHtml<Dom>>::to_html_stream_out_of_order(
el,
);
assert_eq!(
stream.next().await.unwrap(),
"<!--s-1-o-->Loading...<!--s-1-c-->"
);
assert_eq!(
stream.next().await.unwrap(),
"<template id=\"1-f\">Suspended</template><script>(function() { \
let id = \"1-\";let open = undefined;let close = undefined;let \
walker = document.createTreeWalker(document.body, \
NodeFilter.SHOW_COMMENT);while(walker.nextNode()) \
{if(walker.currentNode.textContent == `s-${id}o`){ \
open=walker.currentNode; } else \
if(walker.currentNode.textContent == `s-${id}c`) { close = \
walker.currentNode;}}let range = new Range(); \
range.setStartAfter(open); range.setEndBefore(close); \
range.deleteContents(); let tpl = \
document.getElementById(`${id}f`); \
close.parentNode.insertBefore(tpl.content.cloneNode(true), \
close);})()</script>"
);
}
#[tokio::test]
async fn out_of_order_inside_element_in_stream() {
let el: HtmlElement<_, _, _, Dom> = p().child((
"Before Suspense",
async {
sleep(Duration::from_millis(250)).await;
"Suspended"
}
.suspend()
.with_fallback("Loading..."),
"After Suspense",
));
let mut stream = el.to_html_stream_out_of_order();
assert_eq!(
stream.next().await.unwrap(),
"<p>Before Suspense<!--s-1-o--><!>Loading...<!--s-1-c-->After \
Suspense</p>"
);
assert!(stream.next().await.unwrap().contains("Suspended"));
assert!(stream.next().await.is_none());
}
#[tokio::test]
async fn out_of_order_nested_async_blocks() {
let el: HtmlElement<_, _, _, Dom> = main().child((
"Before Suspense",
async {
sleep(Duration::from_millis(250)).await;
p().child((
"Before inner Suspense",
async {
sleep(Duration::from_millis(250)).await;
"Inner Suspense"
}
.suspend()
.with_fallback("Loading Inner..."),
"After inner Suspense",
))
}
.suspend()
.with_fallback("Loading..."),
"After Suspense",
));
let mut stream = el.to_html_stream_out_of_order();
assert_eq!(
stream.next().await.unwrap(),
"<main>Before Suspense<!--s-1-o--><!>Loading...<!--s-1-c-->After \
Suspense</main>"
);
let loading_inner = stream.next().await.unwrap();
assert!(loading_inner.contains(
"<p>Before inner Suspense<!--s-1-1-o--><!>Loading \
Inner...<!--s-1-1-c-->After inner Suspense</p>"
));
assert!(loading_inner.contains("let id = \"1-\";"));
let inner = stream.next().await.unwrap();
assert!(inner.contains("Inner Suspense"));
assert!(inner.contains("let id = \"1-1-\";"));
assert!(stream.next().await.is_none());
}
}

191
tachys/src/svg/mod.rs Normal file
View file

@ -0,0 +1,191 @@
use crate::{
html::{
attribute::{Attr, Attribute, AttributeValue},
element::{
CreateElement, ElementType, ElementWithChildren, HtmlElement,
},
},
renderer::{dom::Dom, Renderer},
view::Render,
};
use next_tuple::TupleBuilder;
use once_cell::unsync::Lazy;
use std::{fmt::Debug, marker::PhantomData};
macro_rules! svg_global_attr {
($tag:ty, $attr:ty) => {
paste::paste! {
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
Ch, Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
}
}
}
macro_rules! svg_elements {
($($tag:ident [$($attr:ty),*]),* $(,)?) => {
paste::paste! {
$(
// `tag()` function
#[allow(non_snake_case)]
pub fn $tag<Rndr>() -> HtmlElement<[<$tag:camel>], (), (), Rndr>
where
Rndr: Renderer
{
HtmlElement {
tag: [<$tag:camel>],
attributes: (),
children: (),
rndr: PhantomData,
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct [<$tag:camel>];
impl<At, Ch, Rndr> HtmlElement<[<$tag:camel>], At, Ch, Rndr>
where
At: Attribute<Rndr>,
Ch: Render<Rndr>,
Rndr: Renderer,
{
$(
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output,
Ch, Rndr
>
where
V: AttributeValue<Rndr>,
At: TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>,
<At as TupleBuilder<Attr<$crate::html::attribute::[<$attr:camel>], V, Rndr>>>::Output: Attribute<Rndr>,
{
let HtmlElement { tag, rndr, children, attributes } = self;
HtmlElement {
tag,
rndr,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value))
}
}
)*
}
impl ElementType for [<$tag:camel>] {
type Output = web_sys::SvgElement;
const TAG: &'static str = stringify!($tag);
const SELF_CLOSING: bool = false;
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl ElementWithChildren for [<$tag:camel>] {}
impl CreateElement<Dom> for [<$tag:camel>] {
fn create_element(&self) -> <Dom as Renderer>::Element {
use wasm_bindgen::JsCast;
thread_local! {
static ELEMENT: Lazy<<Dom as Renderer>::Element> = Lazy::new(|| {
crate::dom::document().create_element_ns(
Some(wasm_bindgen::intern("http://www.w3.org/2000/svg")),
stringify!($tag)
).unwrap()
});
}
ELEMENT.with(|e| e.clone_node()).unwrap().unchecked_into()
}
}
)*
}
}
}
svg_elements![
a [],
animate [],
animateMotion [],
animateTransform [],
circle [],
clipPath [],
defs [],
desc [],
discard [],
ellipse [],
feBlend [],
feColorMatrix [],
feComponentTransfer [],
feComposite [],
feConvolveMatrix [],
feDiffuseLighting [],
feDisplacementMap [],
feDistantLight [],
feDropShadow [],
feFlood [],
feFuncA [],
feFuncB [],
feFuncG [],
feFuncR [],
feGaussianBlur [],
feImage [],
feMerge [],
feMergeNode [],
feMorphology [],
feOffset [],
fePointLight [],
feSpecularLighting [],
feSpotLight [],
feTile [],
feTurbulence [],
filter [],
foreignObject [],
g [],
hatch [],
hatchpath [],
image [],
line [],
linearGradient [],
marker [],
mask [],
metadata [],
mpath [],
path [],
pattern [],
polygon [],
polyline [],
radialGradient [],
rect [],
script [],
set [],
stop [],
style [],
svg [],
switch [],
symbol [],
text [],
textPath [],
title [],
tspan [],
view [],
];
// TODO <use>

View file

@ -0,0 +1,166 @@
use super::RenderEffectState;
use crate::{html::class::IntoClass, renderer::DomRenderer};
use tachy_reaccy::render_effect::RenderEffect;
impl<F, C, R> IntoClass<R> for F
where
F: FnMut() -> C + 'static,
C: IntoClass<R> + 'static,
C::State: 'static,
R: DomRenderer,
R::ClassList: 'static,
R::Element: Clone + 'static,
{
type State = RenderEffectState<C::State>;
fn to_html(mut self, class: &mut String) {
let value = self();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &R::Element,
) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
.into()
}
fn build(mut self, el: &R::Element) -> Self::State {
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build(&el)
}
})
.into()
}
fn rebuild(mut self, state: &mut Self::State) {
let prev_effect = std::mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
*state = RenderEffect::new_with_value(
move |prev| {
crate::log("rebuilt class");
let value = self();
if let Some(mut state) = prev {
crate::log(" rebuilt it");
value.rebuild(&mut state);
state
} else {
crate::log(" oh no!");
todo!()
}
},
prev_value,
)
.into();
}
}
impl<F, R> IntoClass<R> for (&'static str, F)
where
F: FnMut() -> bool + 'static,
R: DomRenderer,
R::ClassList: Clone + 'static,
R::Element: Clone,
{
type State = RenderEffectState<(R::ClassList, bool)>;
fn to_html(self, class: &mut String) {
let (name, mut f) = self;
let include = f();
if include {
<&str as IntoClass<R>>::to_html(name, class);
}
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
// TODO FROM_SERVER vs template
let (name, mut f) = self;
let class_list = R::class_list(el);
RenderEffect::new(move |prev: Option<(R::ClassList, bool)>| {
let include = f();
if let Some((class_list, prev)) = prev {
if include {
if !prev {
R::add_class(&class_list, name);
}
} else if prev {
R::remove_class(&class_list, name);
}
}
(class_list.clone(), include)
})
.into()
}
fn build(self, el: &R::Element) -> Self::State {
let (name, mut f) = self;
let class_list = R::class_list(el);
RenderEffect::new(move |prev: Option<(R::ClassList, bool)>| {
let include = f();
match prev {
Some((class_list, prev)) => {
if include {
if !prev {
R::add_class(&class_list, name);
}
} else if prev {
R::remove_class(&class_list, name);
}
}
None => {
if include {
R::add_class(&class_list, name);
}
}
}
(class_list.clone(), include)
})
.into()
}
fn rebuild(self, state: &mut Self::State) {
// TODO
/* let (name, mut f) = self;
let prev_effect = std::mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
*state = RenderEffect::new_with_value(
move |prev| {
let include = f();
match prev {
Some((class_list, prev)) => {
if include {
if !prev {
R::add_class(&class_list, name);
}
} else if prev {
R::remove_class(&class_list, name);
}
(class_list.clone(), include)
}
None => unreachable!(),
}
},
prev_value,
)
.into(); */
}
}

View file

@ -0,0 +1,465 @@
use crate::{
async_views::Suspend,
html::{attribute::AttributeValue, property::IntoProperty},
hydration::Cursor,
renderer::{DomRenderer, Renderer},
ssr::StreamBuilder,
view::{
FallibleRender, InfallibleRender, Mountable, Position, PositionState,
Render, RenderHtml, ToTemplate,
},
};
use std::mem;
use tachy_reaccy::{async_signal::ScopedFuture, render_effect::RenderEffect};
mod class;
pub mod node_ref;
mod style;
impl<F, V> ToTemplate for F
where
F: FnMut() -> V,
V: ToTemplate,
{
const TEMPLATE: &'static str = V::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
// FIXME this seems wrong
V::to_template(buf, class, style, inner_html, position)
}
}
impl<F, V, R> Render<R> for F
where
F: FnMut() -> V + 'static,
V: Render<R>,
V::State: 'static,
R: Renderer,
{
type State = RenderEffectState<V::State>;
#[track_caller]
fn build(mut self) -> Self::State {
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
})
.into()
}
#[track_caller]
fn rebuild(mut self, state: &mut Self::State) {
// TODO
/* let prev_effect = mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
*state = RenderEffect::new_with_value(
move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
},
prev_value,
)
.into(); */
}
}
pub struct RenderEffectState<T: 'static>(Option<RenderEffect<T>>);
impl<T> From<RenderEffect<T>> for RenderEffectState<T> {
fn from(value: RenderEffect<T>) -> Self {
Self(Some(value))
}
}
impl<T, R> Mountable<R> for RenderEffectState<T>
where
T: Mountable<R>,
R: Renderer,
{
fn unmount(&mut self) {
if let Some(ref mut inner) = self.0 {
inner.unmount();
}
}
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
if let Some(ref mut inner) = self.0 {
inner.mount(parent, marker);
}
}
fn insert_before_this(
&self,
parent: &R::Element,
child: &mut dyn Mountable<R>,
) -> bool {
if let Some(inner) = &self.0 {
inner.insert_before_this(parent, child)
} else {
false
}
}
}
impl<F, V> InfallibleRender for F where F: FnMut() -> V + 'static {}
/* impl<F, V, R> FallibleRender<R> for F
where
F: FnMut() -> V + 'static,
V: FallibleRender<R>,
V::State: 'static,
R: Renderer,
{
type FallibleState = V::FallibleState;
type Error = V::Error;
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
todo!()
}
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error> {
todo!()
}
} */
impl<F, V, R> RenderHtml<R> for F
where
F: FnMut() -> V + 'static,
V: RenderHtml<R>,
V::State: 'static,
R: Renderer + 'static,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(mut self, buf: &mut String, position: &mut Position) {
let value = self();
value.to_html_with_buf(buf, position)
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
mut self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
let value = self();
value.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let cursor = cursor.clone();
let position = position.clone();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&cursor, &position)
}
})
.into()
}
}
impl<M, R> Mountable<R> for RenderEffect<M>
where
M: Mountable<R> + 'static,
R: Renderer,
{
fn unmount(&mut self) {
self.with_value_mut(|state| state.unmount());
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
self.with_value_mut(|state| {
state.mount(parent, marker);
});
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
self.with_value_mut(|value| value.insert_before_this(parent, child))
.unwrap_or(false)
}
}
// Extends to track suspense
impl<const TRANSITION: bool, Fal, Fut> Suspend<TRANSITION, Fal, Fut> {
pub fn track(self) -> Suspend<TRANSITION, Fal, ScopedFuture<Fut>> {
let Suspend { fallback, fut } = self;
Suspend {
fallback,
fut: ScopedFuture::new(fut),
}
}
}
// Dynamic attributes
impl<F, V, R> AttributeValue<R> for F
where
F: FnMut() -> V + 'static,
V: AttributeValue<R>,
V::State: 'static,
R: Renderer,
R::Element: Clone + 'static,
{
type State = RenderEffectState<V::State>;
fn to_html(mut self, key: &str, buf: &mut String) {
let value = self();
value.to_html(key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
mut self,
key: &str,
el: &<R as Renderer>::Element,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&key, &el)
}
})
.into()
}
fn build(
mut self,
el: &<R as Renderer>::Element,
key: &str,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
value.build(&el, &key)
}
})
.into()
}
fn rebuild(mut self, key: &str, state: &mut Self::State) {
// TODO
/* let prev_effect = mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
let key = key.to_owned();
*state = RenderEffect::new_with_value(
move |prev| {
crate::log(&format!(
"inside here, prev is some? {}",
prev.is_some()
));
let value = self();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
unreachable!()
}
},
prev_value,
)
.into(); */
}
/* fn build(self) -> Self::State {
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
})
}
#[track_caller]
fn rebuild(self, state: &mut Self::State) {
/* crate::log(&format!(
"[REBUILDING EFFECT] Is this a mistake? {}",
std::panic::Location::caller(),
)); */
let old_effect = std::mem::replace(state, self.build());
} */
}
// Dynamic properties
// These do update during hydration because properties don't exist in the DOM
impl<F, V, R> IntoProperty<R> for F
where
F: FnMut() -> V + 'static,
V: IntoProperty<R>,
V::State: 'static,
R: DomRenderer,
R::Element: Clone + 'static,
{
type State = RenderEffectState<V::State>;
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &<R as Renderer>::Element,
key: &str,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
value.hydrate::<FROM_SERVER>(&el, &key)
}
})
.into()
}
fn build(
mut self,
el: &<R as Renderer>::Element,
key: &str,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
value.build(&el, &key)
}
})
.into()
}
fn rebuild(mut self, state: &mut Self::State, key: &str) {
// TODO
/* let prev_effect = mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
let key = key.to_owned();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
unreachable!()
}
},
prev_value,
)
.into(); */
}
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::element::{button, main, HtmlElement},
renderer::mock_dom::MockDom,
view::Render,
};
use leptos_reactive::{create_runtime, RwSignal, SignalGet, SignalSet};
#[test]
fn create_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
count.set(1);
assert_eq!(el.el.to_debug_html(), "<button>1</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element_among_siblings() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> = main(
(),
button(
(),
("Hello, my ", move || count.get().to_string(), " friends."),
),
);
let el = app.build();
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 0 friends.</button></main>"
);
count.set(42);
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 42 friends.</button></main>"
);
rt.dispose();
}
}
*/

View file

@ -0,0 +1,101 @@
use crate::{
html::{element::ElementType, node_ref::NodeRefContainer},
renderer::{dom::Dom, Renderer},
};
use send_wrapper::SendWrapper;
use tachy_reaccy::{
signal::RwSignal,
signal_traits::{DefinedAt, SignalSet, SignalWithUntracked, Track},
};
use wasm_bindgen::JsCast;
#[derive(Debug)]
pub struct NodeRef<E>(RwSignal<Option<SendWrapper<E::Output>>>)
where
E: ElementType,
E::Output: 'static;
impl<E> NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
#[track_caller]
pub fn new() -> Self {
Self(RwSignal::new(None))
}
}
impl<E> Default for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<E> Clone for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<E> Copy for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
}
impl<E> NodeRefContainer<E, Dom> for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn load(self, el: &<Dom as Renderer>::Element) {
self.0
.set(Some(SendWrapper::new(el.clone().unchecked_into())));
}
}
impl<E> DefinedAt for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn defined_at(&self) -> Option<&'static std::panic::Location<'static>> {
self.0.defined_at()
}
}
impl<E> SignalWithUntracked for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
type Value = Option<E::Output>;
fn try_with_untracked<U>(
&self,
fun: impl FnOnce(&Self::Value) -> U,
) -> Option<U> {
self.0
.try_with_untracked(|inner| fun(&inner.as_deref().cloned()))
}
}
impl<E> Track for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn track(&self) {
self.0.track();
}
}

View file

@ -0,0 +1,140 @@
use super::RenderEffectState;
use crate::{html::style::IntoStyle, renderer::DomRenderer};
use std::borrow::Cow;
use tachy_reaccy::render_effect::RenderEffect;
impl<F, S, R> IntoStyle<R> for (&'static str, F)
where
F: FnMut() -> S + 'static,
S: Into<Cow<'static, str>>,
R: DomRenderer,
R::CssStyleDeclaration: Clone + 'static,
{
type State = RenderEffectState<(R::CssStyleDeclaration, Cow<'static, str>)>;
fn to_html(self, style: &mut String) {
let (name, mut f) = self;
let value = f();
style.push_str(name);
style.push(':');
style.push_str(&value.into());
style.push(';');
}
fn hydrate<const FROM_SERVER: bool>(self, el: &R::Element) -> Self::State {
let (name, mut f) = self;
// TODO FROM_SERVER vs template
let style = R::style(el);
RenderEffect::new(move |prev| {
let value = f().into();
if let Some(mut state) = prev {
let (style, prev): &mut (
R::CssStyleDeclaration,
Cow<'static, str>,
) = &mut state;
if &value != prev {
R::set_css_property(style, name, &value);
}
*prev = value;
state
} else {
// only set the style in template mode
// in server mode, it's already been set
if !FROM_SERVER {
R::set_css_property(&style, name, &value);
}
(style.clone(), value)
}
})
.into()
}
fn build(self, el: &R::Element) -> Self::State {
let (name, mut f) = self;
let style = R::style(el);
RenderEffect::new(move |prev| {
let value = f().into();
if let Some(mut state) = prev {
let (style, prev): &mut (
R::CssStyleDeclaration,
Cow<'static, str>,
) = &mut state;
if &value != prev {
R::set_css_property(style, name, &value);
}
*prev = value;
state
} else {
// always set the style initially without checking
R::set_css_property(&style, name, &value);
(style.clone(), value)
}
})
.into()
}
fn rebuild(self, state: &mut Self::State) {
// TODO
/* let (name, mut f) = self;
let prev_effect = std::mem::take(&mut state.0);
let prev_value = prev_effect.as_ref().and_then(|e| e.take_value());
drop(prev_effect);
*state = RenderEffect::new_with_value(
move |prev| {
let value = f().into();
if let Some(mut state) = prev {
let (style, prev) = &mut state;
if &value != prev {
R::set_css_property(&style, name, &value);
}
*prev = value;
state
} else {
todo!()
}
},
prev_value,
)
.into(); */
}
}
impl<F, C, R> IntoStyle<R> for F
where
F: FnMut() -> C + 'static,
C: IntoStyle<R> + 'static,
C::State: 'static,
R: DomRenderer,
R::Element: Clone + 'static,
R::CssStyleDeclaration: Clone + 'static,
{
type State = RenderEffect<C::State>;
fn to_html(mut self, class: &mut String) {
let value = self();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &R::Element,
) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
RenderEffect::new(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(self, el: &R::Element) -> Self::State {
todo!()
}
fn rebuild(self, state: &mut Self::State) {}
}

279
tachys/src/view/any_view.rs Normal file
View file

@ -0,0 +1,279 @@
use super::{Mountable, Position, PositionState, Render, RenderHtml};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
};
use std::{
any::{Any, TypeId},
marker::PhantomData,
};
pub struct AnyView<R>
where
R: Renderer,
{
type_id: TypeId,
value: Box<dyn Any>,
to_html: fn(Box<dyn Any>, &mut String, &mut Position),
build: fn(Box<dyn Any>) -> AnyViewState<R>,
rebuild: fn(TypeId, Box<dyn Any>, &mut AnyViewState<R>),
#[allow(clippy::type_complexity)]
hydrate_from_server:
fn(Box<dyn Any>, &Cursor<R>, &PositionState) -> AnyViewState<R>,
#[allow(clippy::type_complexity)]
hydrate_from_template:
fn(Box<dyn Any>, &Cursor<R>, &PositionState) -> AnyViewState<R>,
}
pub struct AnyViewState<R>
where
R: Renderer,
{
type_id: TypeId,
state: Box<dyn Any>,
unmount: fn(&mut dyn Any),
mount: fn(&mut dyn Any, parent: &R::Element, marker: Option<&R::Node>),
insert_before_this:
fn(&dyn Any, parent: &R::Element, child: &mut dyn Mountable<R>) -> bool,
rndr: PhantomData<R>,
}
pub trait IntoAny<R>
where
R: Renderer,
{
fn into_any(self) -> AnyView<R>;
}
fn mount_any<R, T>(
state: &mut dyn Any,
parent: &R::Element,
marker: Option<&R::Node>,
) where
T: Render<R>,
T::State: 'static,
R: Renderer,
{
let state = state
.downcast_mut::<T::State>()
.expect("AnyViewState::as_mountable couldn't downcast state");
state.mount(parent, marker)
}
fn unmount_any<R, T>(state: &mut dyn Any)
where
T: Render<R>,
T::State: 'static,
R: Renderer,
{
let state = state
.downcast_mut::<T::State>()
.expect("AnyViewState::unmount couldn't downcast state");
state.unmount();
}
fn insert_before_this<R, T>(
state: &dyn Any,
parent: &R::Element,
child: &mut dyn Mountable<R>,
) -> bool
where
T: Render<R>,
T::State: 'static,
R: Renderer + 'static,
{
let state = state
.downcast_ref::<T::State>()
.expect("AnyViewState::opening_node couldn't downcast state");
state.insert_before_this(parent, child)
}
impl<T, R> IntoAny<R> for T
where
T: RenderHtml<R> + 'static,
T::State: 'static,
R: Renderer + 'static,
R::Node: Clone,
R::Element: Clone,
{
// inlining allows the compiler to remove the unused functions
// i.e., doesn't ship HTML-generating code that isn't used
#[inline(always)]
fn into_any(self) -> AnyView<R> {
let value = Box::new(self) as Box<dyn Any>;
let to_html =
|value: Box<dyn Any>, buf: &mut String, position: &mut Position| {
let value = value
.downcast::<T>()
.expect("AnyView::to_html could not be downcast");
value.to_html_with_buf(buf, position);
};
let build = |value: Box<dyn Any>| {
let value = value
.downcast::<T>()
.expect("AnyView::build couldn't downcast");
let state = Box::new(value.build());
AnyViewState {
type_id: TypeId::of::<T>(),
state,
rndr: PhantomData,
mount: mount_any::<R, T>,
unmount: unmount_any::<R, T>,
insert_before_this: insert_before_this::<R, T>,
}
};
let hydrate_from_server =
|value: Box<dyn Any>,
cursor: &Cursor<R>,
position: &PositionState| {
let value = value
.downcast::<T>()
.expect("AnyView::hydrate_from_server couldn't downcast");
let state = Box::new(value.hydrate::<true>(cursor, position));
AnyViewState {
type_id: TypeId::of::<T>(),
state,
rndr: PhantomData,
mount: mount_any::<R, T>,
unmount: unmount_any::<R, T>,
insert_before_this: insert_before_this::<R, T>,
}
};
let hydrate_from_template =
|value: Box<dyn Any>,
cursor: &Cursor<R>,
position: &PositionState| {
let value = value
.downcast::<T>()
.expect("AnyView::hydrate_from_server couldn't downcast");
let state = Box::new(value.hydrate::<true>(cursor, position));
AnyViewState {
type_id: TypeId::of::<T>(),
state,
rndr: PhantomData,
mount: mount_any::<R, T>,
unmount: unmount_any::<R, T>,
insert_before_this: insert_before_this::<R, T>,
}
};
let rebuild = |new_type_id: TypeId,
value: Box<dyn Any>,
state: &mut AnyViewState<R>| {
let value = value
.downcast::<T>()
.expect("AnyView::rebuild couldn't downcast value");
if new_type_id == state.type_id {
let state = state
.state
.downcast_mut()
.expect("AnyView::rebuild couldn't downcast state");
value.rebuild(state);
} else {
let mut new = value.into_any().build();
// TODO mount new state
/*R::mount_before(&mut new, state.placeholder.as_ref());*/
state.unmount();
*state = new;
}
};
AnyView {
type_id: TypeId::of::<T>(),
value,
to_html,
build,
rebuild,
hydrate_from_server,
hydrate_from_template,
}
}
}
impl<R> Render<R> for AnyView<R>
where
R: Renderer + 'static,
{
type State = AnyViewState<R>;
fn build(self) -> Self::State {
(self.build)(self.value)
}
fn rebuild(self, state: &mut Self::State) {
(self.rebuild)(self.type_id, self.value, state)
}
}
impl<R> RenderHtml<R> for AnyView<R>
where
R: Renderer + 'static,
R::Element: Clone,
R::Node: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
(self.to_html)(self.value, buf, position);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
if FROM_SERVER {
(self.hydrate_from_server)(self.value, cursor, position)
} else {
(self.hydrate_from_template)(self.value, cursor, position)
}
}
}
impl<R> Mountable<R> for AnyViewState<R>
where
R: Renderer + 'static,
{
fn unmount(&mut self) {
(self.unmount)(&mut *self.state)
}
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
(self.mount)(&mut *self.state, parent, marker)
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
(self.insert_before_this)(self, parent, child)
}
}
/*
#[cfg(test)]
mod tests {
use super::IntoAny;
use crate::{
html::element::{p, span},
renderer::mock_dom::MockDom,
view::{any_view::AnyView, RenderHtml},
};
#[test]
fn should_handle_html_creation() {
let x = 1;
let mut buf = String::new();
let view: AnyView<MockDom> = if x == 0 {
p((), "foo").into_any()
} else {
span((), "bar").into_any()
};
view.to_html(&mut buf, &Default::default());
assert_eq!(buf, "<span>bar</span><!>");
}
}
*/

162
tachys/src/view/dynamic.rs Normal file
View file

@ -0,0 +1,162 @@
use super::{Mountable, PositionState, Render, RenderHtml, ToTemplate};
use crate::{hydration::Cursor, renderer::Renderer};
use leptos_reactive::{create_render_effect, Effect, SignalDispose};
impl<F, V> ToTemplate for F
where
F: Fn() -> V,
V: ToTemplate,
{
fn to_template(buf: &mut String, position: &mut super::Position) {
V::to_template(buf, position)
}
}
impl<F, V, R> Render<R> for F
where
F: Fn() -> V + 'static,
V: Render<R>,
V::State: 'static,
R: Renderer,
{
type State = Effect<V::State>;
fn build(self) -> Self::State {
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
})
}
#[track_caller]
fn rebuild(self, state: &mut Self::State) {
crate::log(&format!(
"[REBUILDING EFFECT] Is this a mistake? {}",
std::panic::Location::caller(),
));
let old_effect = std::mem::replace(state, self.build());
old_effect.dispose();
}
}
impl<F, V, R> RenderHtml<R> for F
where
F: Fn() -> V + 'static,
V: RenderHtml<R>,
V::State: 'static,
R: Renderer + 'static,
R::Node: Clone,
R::Element: Clone,
{
fn to_html(self, buf: &mut String, position: &PositionState) {
let value = self();
value.to_html(buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let cursor = cursor.clone();
let position = position.clone();
create_render_effect(move |prev| {
let value = self();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&cursor, &position)
}
})
}
}
impl<M, R> Mountable<R> for Effect<M>
where
M: Mountable<R> + 'static,
R: Renderer,
{
fn unmount(&mut self) {
self.with_value_mut(|value| {
if let Some(value) = value {
value.unmount()
}
});
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
self.with_value_mut(|value| {
if let Some(state) = value {
state.mount(parent, marker);
}
});
}
}
#[cfg(test)]
mod tests {
use crate::{
html::element::{button, main, HtmlElement},
renderer::mock_dom::MockDom,
view::Render,
};
use leptos_reactive::{create_runtime, RwSignal, SignalGet, SignalSet};
#[test]
fn create_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
count.set(1);
assert_eq!(el.el.to_debug_html(), "<button>1</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element_among_siblings() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> = main(
(),
button(
(),
("Hello, my ", move || count.get().to_string(), " friends."),
),
);
let el = app.build();
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 0 friends.</button></main>"
);
count.set(42);
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 42 friends.</button></main>"
);
rt.dispose();
}
}

332
tachys/src/view/either.rs Normal file
View file

@ -0,0 +1,332 @@
use super::{Mountable, Position, PositionState, Render, RenderHtml};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
ssr::StreamBuilder,
};
pub enum Either<A, B> {
Left(A),
Right(B),
}
pub struct EitherState<A, B, Rndr>
where
A: Render<Rndr>,
B: Render<Rndr>,
Rndr: Renderer,
{
state: Either<A::State, B::State>,
marker: Rndr::Placeholder,
}
impl<A, B, Rndr> Render<Rndr> for Either<A, B>
where
A: Render<Rndr>,
B: Render<Rndr>,
Rndr: Renderer,
{
type State = EitherState<A, B, Rndr>;
fn build(self) -> Self::State {
let marker = Rndr::create_placeholder();
match self {
Either::Left(left) => EitherState {
state: Either::Left(left.build()),
marker,
},
Either::Right(right) => EitherState {
state: Either::Right(right.build()),
marker,
},
}
}
// TODO hold onto old states to avoid rerendering them?
fn rebuild(self, state: &mut Self::State) {
let marker = state.marker.as_ref();
match (self, &mut state.state) {
(Either::Left(new), Either::Left(old)) => new.rebuild(old),
(Either::Right(new), Either::Right(old)) => new.rebuild(old),
(Either::Right(new), Either::Left(old)) => {
old.unmount();
let mut new_state = new.build();
Rndr::mount_before(&mut new_state, marker);
state.state = Either::Right(new_state);
}
(Either::Left(new), Either::Right(old)) => {
old.unmount();
let mut new_state = new.build();
Rndr::mount_before(&mut new_state, marker);
state.state = Either::Left(new_state);
}
}
}
}
impl<A, B, Rndr> Mountable<Rndr> for EitherState<A, B, Rndr>
where
A: Render<Rndr>,
B: Render<Rndr>,
Rndr: Renderer,
{
fn unmount(&mut self) {
match &mut self.state {
Either::Left(left) => left.unmount(),
Either::Right(right) => right.unmount(),
}
self.marker.unmount();
}
fn mount(
&mut self,
parent: &<Rndr as Renderer>::Element,
marker: Option<&<Rndr as Renderer>::Node>,
) {
self.marker.mount(parent, marker);
match &mut self.state {
Either::Left(left) => {
left.mount(parent, Some(self.marker.as_ref()))
}
Either::Right(right) => {
right.mount(parent, Some(self.marker.as_ref()))
}
}
}
fn insert_before_this(
&self,
parent: &<Rndr as Renderer>::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
match &self.state {
Either::Left(left) => left.insert_before_this(parent, child),
Either::Right(right) => right.insert_before_this(parent, child),
}
}
}
impl<A, B, Rndr> RenderHtml<Rndr> for Either<A, B>
where
A: RenderHtml<Rndr>,
B: RenderHtml<Rndr>,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
const MIN_LENGTH: usize = min_usize(&[A::MIN_LENGTH, B::MIN_LENGTH]);
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
match self {
Either::Left(left) => left.to_html_with_buf(buf, position),
Either::Right(right) => right.to_html_with_buf(buf, position),
}
buf.push_str("<!>");
*position = Position::NextChild;
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
match self {
Either::Left(left) => {
left.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position)
}
Either::Right(right) => {
right.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position)
}
}
buf.push_sync("<!>");
*position = Position::NextChild;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
let state = match self {
Either::Left(left) => {
Either::Left(left.hydrate::<FROM_SERVER>(cursor, position))
}
Either::Right(right) => {
Either::Right(right.hydrate::<FROM_SERVER>(cursor, position))
}
};
cursor.sibling();
let marker = cursor.current().to_owned();
let marker = Rndr::Placeholder::cast_from(marker).unwrap();
position.set(Position::NextChild);
EitherState { state, marker }
}
}
const fn min_usize(vals: &[usize]) -> usize {
let mut min = usize::MAX;
let len = vals.len();
let mut i = 0;
while i < len {
if vals[i] < min {
min = vals[i];
}
i += 1;
}
min
}
macro_rules! tuples {
($num:literal => $($ty:ident),*) => {
paste::paste! {
pub enum [<EitherOf $num>]<$($ty,)*> {
$($ty ($ty),)*
}
pub struct [<EitherOf $num State>]<$($ty,)* Rndr>
where
$($ty: Render<Rndr>,)*
Rndr: Renderer
{
state: [<EitherOf $num>]<$($ty::State,)*>,
marker: Rndr::Placeholder,
}
impl<$($ty,)* Rndr> Mountable<Rndr> for [<EitherOf $num State>]<$($ty,)* Rndr>
where
$($ty: Render<Rndr>,)*
Rndr: Renderer
{
fn unmount(&mut self) {
match &mut self.state {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.unmount()),)*
};
self.marker.unmount();
}
fn mount(
&mut self,
parent: &<Rndr as Renderer>::Element,
marker: Option<&<Rndr as Renderer>::Node>,
) {
self.marker.mount(parent, marker);
match &mut self.state {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.mount(parent, Some(self.marker.as_ref()))),)*
};
}
fn insert_before_this(
&self,
parent: &<Rndr as Renderer>::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
match &self.state {
$([<EitherOf $num>]::$ty(this) =>this.insert_before_this(parent, child),)*
}
}
}
impl<Rndr, $($ty,)*> Render<Rndr> for [<EitherOf $num>]<$($ty,)*>
where
$($ty: Render<Rndr>,)*
Rndr: Renderer
{
type State = [<EitherOf $num State>]<$($ty,)* Rndr>;
fn build(self) -> Self::State {
let marker = Rndr::create_placeholder();
let state = match self {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.build()),)*
};
Self::State { marker, state }
}
fn rebuild(self, state: &mut Self::State) {
let marker = state.marker.as_ref();
let new_state = match (self, &mut state.state) {
// rebuild same state and return early
$(([<EitherOf $num>]::$ty(new), [<EitherOf $num>]::$ty(old)) => { return new.rebuild(old); },)*
// or mount new state
$(([<EitherOf $num>]::$ty(new), _) => {
let mut new = new.build();
Rndr::mount_before(&mut new, marker);
[<EitherOf $num>]::$ty(new)
},)*
};
// and then unmount old state
match &mut state.state {
$([<EitherOf $num>]::$ty(this) => this.unmount(),)*
};
// and store the new state
state.state = new_state;
}
}
impl<Rndr, $($ty,)*> RenderHtml<Rndr> for [<EitherOf $num>]<$($ty,)*>
where
$($ty: RenderHtml<Rndr>,)*
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
const MIN_LENGTH: usize = min_usize(&[$($ty ::MIN_LENGTH,)*]);
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
match self {
$([<EitherOf $num>]::$ty(this) => this.to_html_with_buf(buf, position),)*
}
buf.push_str("<!>");
*position = Position::NextChild;
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
match self {
$([<EitherOf $num>]::$ty(this) => this.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position),)*
}
buf.push_sync("<!>");
*position = Position::NextChild;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
let state = match self {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.hydrate::<FROM_SERVER>(cursor, position)),)*
};
cursor.sibling();
let marker = cursor.current().to_owned();
let marker = Rndr::Placeholder::cast_from(marker).unwrap();
position.set(Position::NextChild);
Self::State { marker, state }
}
}
}
}
}
tuples!(3 => A, B, C);
tuples!(4 => A, B, C, D);
tuples!(5 => A, B, C, D, E);
tuples!(6 => A, B, C, D, E, F);
tuples!(7 => A, B, C, D, E, F, G);
tuples!(8 => A, B, C, D, E, F, G, H);
tuples!(9 => A, B, C, D, E, F, G, H, I);
tuples!(10 => A, B, C, D, E, F, G, H, I, J);
tuples!(11 => A, B, C, D, E, F, G, H, I, J, K);
tuples!(12 => A, B, C, D, E, F, G, H, I, J, K, L);
tuples!(13 => A, B, C, D, E, F, G, H, I, J, K, L, M);
tuples!(14 => A, B, C, D, E, F, G, H, I, J, K, L, M, N);
tuples!(15 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
tuples!(16 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

View file

@ -0,0 +1,188 @@
use super::either::Either;
use crate::view::{FallibleRender, Mountable, Render, Renderer};
use std::marker::PhantomData;
impl<R, T, E> Render<R> for Result<T, E>
where
T: Render<R>,
R: Renderer,
{
type State = <Option<T> as Render<R>>::State;
fn build(self) -> Self::State {
self.ok().build()
}
fn rebuild(self, state: &mut Self::State) {
self.ok().rebuild(state);
}
}
impl<R, T, E> FallibleRender<R> for Result<T, E>
where
T: Render<R>,
R: Renderer,
{
type FallibleState = T::State;
type Error = E;
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
let inner = self?;
let state = inner.build();
Ok(state)
}
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error> {
let inner = self?;
inner.rebuild(state);
Ok(())
}
}
pub trait TryCatchBoundary<Fal, FalFn, Rndr>
where
Self: Sized + FallibleRender<Rndr>,
Fal: Render<Rndr>,
FalFn: FnMut(Self::Error) -> Fal,
Rndr: Renderer,
{
fn catch(self, fallback: FalFn) -> Try<Self, Fal, FalFn, Rndr>;
}
impl<T, Fal, FalFn, Rndr> TryCatchBoundary<Fal, FalFn, Rndr> for T
where
T: Sized + FallibleRender<Rndr>,
Fal: Render<Rndr>,
FalFn: FnMut(Self::Error) -> Fal,
Rndr: Renderer,
{
fn catch(self, fallback: FalFn) -> Try<Self, Fal, FalFn, Rndr> {
Try::new(fallback, self)
}
}
pub struct Try<T, Fal, FalFn, Rndr>
where
T: FallibleRender<Rndr>,
Fal: Render<Rndr>,
FalFn: FnMut(T::Error) -> Fal,
Rndr: Renderer,
{
child: T,
fal: FalFn,
ty: PhantomData<Rndr>,
}
impl<T, Fal, FalFn, Rndr> Try<T, Fal, FalFn, Rndr>
where
T: FallibleRender<Rndr>,
Fal: Render<Rndr>,
FalFn: FnMut(T::Error) -> Fal,
Rndr: Renderer,
{
pub fn new(fallback: FalFn, child: T) -> Self {
Self {
child,
fal: fallback,
ty: PhantomData,
}
}
}
impl<T, Fal, FalFn, Rndr> Render<Rndr> for Try<T, Fal, FalFn, Rndr>
where
T: FallibleRender<Rndr>,
Fal: Render<Rndr>,
FalFn: FnMut(T::Error) -> Fal,
Rndr: Renderer,
{
type State = TryState<T, Fal, Rndr>;
fn build(mut self) -> Self::State {
let state = match self.child.try_build() {
Ok(inner) => Either::Left(inner),
Err(e) => Either::Right((self.fal)(e).build()),
};
let marker = Rndr::create_placeholder();
TryState { state, marker }
}
fn rebuild(mut self, state: &mut Self::State) {
let marker = state.marker.as_ref();
match &mut state.state {
Either::Left(ref mut old) => {
if let Err(e) = self.child.try_rebuild(old) {
old.unmount();
let mut new_state = (self.fal)(e).build();
Rndr::mount_before(&mut new_state, marker);
state.state = Either::Right(new_state);
}
}
Either::Right(old) => match self.child.try_build() {
Ok(mut new_state) => {
old.unmount();
Rndr::mount_before(&mut new_state, marker);
state.state = Either::Left(new_state);
}
Err(e) => {
(self.fal)(e).rebuild(old);
}
},
}
}
}
pub struct TryState<T, Fal, Rndr>
where
T: FallibleRender<Rndr>,
Fal: Render<Rndr>,
Rndr: Renderer,
{
state: Either<T::FallibleState, Fal::State>,
marker: Rndr::Placeholder,
}
impl<T, Fal, Rndr> Mountable<Rndr> for TryState<T, Fal, Rndr>
where
T: FallibleRender<Rndr>,
Fal: Render<Rndr>,
Rndr: Renderer,
{
fn unmount(&mut self) {
match &mut self.state {
Either::Left(left) => left.unmount(),
Either::Right(right) => right.unmount(),
}
self.marker.unmount();
}
fn mount(
&mut self,
parent: &<Rndr as Renderer>::Element,
marker: Option<&<Rndr as Renderer>::Node>,
) {
self.marker.mount(parent, marker);
match &mut self.state {
Either::Left(left) => {
left.mount(parent, Some(self.marker.as_ref()))
}
Either::Right(right) => {
right.mount(parent, Some(self.marker.as_ref()))
}
}
}
fn insert_before_this(
&self,
parent: &<Rndr as Renderer>::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
match &self.state {
Either::Left(left) => left.insert_before_this(parent, child),
Either::Right(right) => right.insert_before_this(parent, child),
}
}
}

View file

@ -0,0 +1,410 @@
use super::{Mountable, Position, PositionState, Render, RenderHtml};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
ssr::StreamBuilder,
};
use itertools::Itertools;
impl<T, R> Render<R> for Option<T>
where
T: Render<R>,
R: Renderer,
{
type State = OptionState<T, R>;
fn build(self) -> Self::State {
let placeholder = R::create_placeholder();
OptionState {
placeholder,
state: self.map(T::build),
}
}
fn rebuild(self, state: &mut Self::State) {
match (&mut state.state, self) {
// both None: no need to do anything
(None, None) => {}
// both Some: need to rebuild child
(Some(old), Some(new)) => {
T::rebuild(new, old);
}
// Some => None: unmount replace with marker
(Some(old), None) => {
old.unmount();
state.state = None;
} // None => Some: build
(None, Some(new)) => {
let mut new_state = new.build();
R::mount_before(&mut new_state, state.placeholder.as_ref());
state.state = Some(new_state);
}
}
}
}
impl<T, R> RenderHtml<R> for Option<T>
where
T: RenderHtml<R>,
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
if let Some(value) = self {
value.to_html_with_buf(buf, position);
}
// placeholder
buf.push_str("<!>");
*position = Position::NextChild;
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
if let Some(value) = self {
value.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
// placeholder
buf.push_sync("<!>");
*position = Position::NextChild;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
// hydrate the state, if it exists
let state = self.map(|s| s.hydrate::<FROM_SERVER>(cursor, position));
// pull the placeholder
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
let placeholder = cursor.current().to_owned();
let placeholder = R::Placeholder::cast_from(placeholder).unwrap();
position.set(Position::NextChild);
OptionState { placeholder, state }
}
}
/// View state for an optional view.
pub struct OptionState<T, R>
where
T: Render<R>,
R: Renderer,
{
/// Marks the location of this view.
placeholder: R::Placeholder,
/// The view state.
state: Option<T::State>,
}
impl<T, R> Mountable<R> for OptionState<T, R>
where
T: Render<R>,
R: Renderer,
{
fn unmount(&mut self) {
if let Some(ref mut state) = self.state {
state.unmount();
}
R::remove(self.placeholder.as_ref());
}
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
if let Some(ref mut state) = self.state {
state.mount(parent, marker);
}
self.placeholder.mount(parent, marker);
}
fn insert_before_this(
&self,
parent: &R::Element,
child: &mut dyn Mountable<R>,
) -> bool {
if self
.state
.as_ref()
.map(|n| n.insert_before_this(parent, child))
== Some(true)
{
true
} else {
self.placeholder.insert_before_this(parent, child)
}
}
}
impl<T, R> Render<R> for Vec<T>
where
T: Render<R>,
R: Renderer,
R::Element: Clone,
R::Node: Clone,
{
type State = VecState<T, R>;
fn build(self) -> Self::State {
VecState {
states: self.into_iter().map(T::build).collect(),
parent: None,
marker: None,
}
}
fn rebuild(self, state: &mut Self::State) {
let VecState {
states,
parent,
marker,
} = state;
let old = states;
// this is an unkeyed diff
if old.is_empty() {
let mut new = self.build().states;
if let Some(parent) = parent {
for item in new.iter_mut() {
item.mount(parent, (*marker).as_ref());
}
}
*old = new;
} else if self.is_empty() {
// TODO fast path for clearing
for item in old.iter_mut() {
item.unmount();
}
old.clear();
} else {
let mut adds = vec![];
let mut removes_at_end = 0;
for item in self.into_iter().zip_longest(old.iter_mut()) {
match item {
itertools::EitherOrBoth::Both(new, old) => {
T::rebuild(new, old)
}
itertools::EitherOrBoth::Left(new) => {
let mut new_state = new.build();
if let Some(parent) = parent {
new_state.mount(parent, (*marker).as_ref());
}
adds.push(new_state);
}
itertools::EitherOrBoth::Right(old) => {
removes_at_end += 1;
old.unmount()
}
}
}
old.truncate(old.len() - removes_at_end);
old.append(&mut adds);
}
}
}
pub struct VecState<T, R>
where
T: Render<R>,
R: Renderer,
{
states: Vec<T::State>,
parent: Option<R::Element>,
marker: Option<R::Node>,
}
impl<T, R> Mountable<R> for VecState<T, R>
where
T: Render<R>,
R: Renderer,
R::Element: Clone,
R::Node: Clone,
{
fn unmount(&mut self) {
for state in self.states.iter_mut() {
state.unmount();
}
self.parent = None;
self.marker = None;
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
for state in self.states.iter_mut() {
state.mount(parent, marker);
}
self.parent = Some(parent.clone());
self.marker = marker.cloned();
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
if let Some(first) = self.states.get(0) {
first.insert_before_this(parent, child)
} else {
false
}
}
}
impl<T, R> RenderHtml<R> for Vec<T>
where
T: RenderHtml<R>,
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
let mut children = self.into_iter();
if let Some(first) = children.next() {
first.to_html_with_buf(buf, position);
}
for child in children {
child.to_html_with_buf(buf, position);
}
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
let mut children = self.into_iter();
if let Some(first) = children.next() {
first.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
for child in children {
child.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
// TODO does this make sense for hydration from template?
VecState {
states: self
.into_iter()
.map(|child| child.hydrate::<FROM_SERVER>(cursor, position))
.collect(),
parent: None,
marker: None,
}
}
}
/*
pub trait IterView<R: Renderer> {
type Iterator: Iterator<Item = Self::View>;
type View: Render<R>;
fn iter_view(self) -> RenderIter<Self::Iterator, Self::View, R>;
}
impl<I, V, R> IterView<R> for I
where
I: Iterator<Item = V>,
V: Render<R>,
R: Renderer,
{
type Iterator = I;
type View = V;
fn iter_view(self) -> RenderIter<Self::Iterator, Self::View, R> {
RenderIter {
inner: self,
rndr: PhantomData,
}
}
}
pub struct RenderIter<I, V, R>
where
I: Iterator<Item = V>,
V: Render<R>,
R: Renderer,
{
inner: I,
rndr: PhantomData<R>,
}
impl<I, V, R> Render<R> for RenderIter<I, V, R>
where
I: Iterator<Item = V>,
V: Render<R>,
R: Renderer,
{
type State = ();
fn build(self) -> Self::State {
todo!()
}
fn rebuild(self, state: &mut Self::State) {
todo!()
}
}
impl<I, V, R> RenderHtml<R> for RenderIter<I, V, R>
where
I: Iterator<Item = V>,
V: RenderHtml<R>,
R: Renderer,
R::Node: Clone,
{
fn to_html(self, buf: &mut String, position: &PositionState) {
for mut next in self.0.by_ref() {
next.to_html(buf, position);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
todo!()
}
}
#[cfg(test)]
mod tests {
use super::IterView;
use crate::view::{Render, RenderHtml};
#[test]
fn iter_view_takes_iterator() {
let strings = vec!["a", "b", "c"];
let mut iter_view = strings
.into_iter()
.map(|n| n.to_ascii_uppercase())
.iter_view();
let mut buf = String::new();
iter_view.to_html(&mut buf, &Default::default());
assert_eq!(buf, "ABC");
}
}
*/

696
tachys/src/view/keyed.rs Normal file
View file

@ -0,0 +1,696 @@
use super::{Mountable, Position, PositionState, Render, RenderHtml};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
ssr::StreamBuilder,
};
use drain_filter_polyfill::VecExt as VecDrainFilterExt;
use indexmap::IndexSet;
use rustc_hash::FxHasher;
use std::{
hash::{BuildHasherDefault, Hash},
marker::PhantomData,
};
type FxIndexSet<T> = IndexSet<T, BuildHasherDefault<FxHasher>>;
pub fn keyed<T, I, K, KF, VF, V, Rndr>(
items: I,
key_fn: KF,
view_fn: VF,
) -> Keyed<T, I, K, KF, VF, V, Rndr>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + 'static,
KF: Fn(&T) -> K,
V: Render<Rndr>,
VF: Fn(T) -> V,
Rndr: Renderer,
{
Keyed {
items,
key_fn,
view_fn,
rndr: PhantomData,
}
}
pub struct Keyed<T, I, K, KF, VF, V, Rndr>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + 'static,
KF: Fn(&T) -> K,
V: Render<Rndr>,
VF: Fn(T) -> V,
Rndr: Renderer,
{
items: I,
key_fn: KF,
view_fn: VF,
rndr: PhantomData<Rndr>,
}
pub struct KeyedState<K, V, Rndr>
where
K: Eq + Hash + 'static,
V: Render<Rndr>,
Rndr: Renderer,
{
parent: Option<Rndr::Element>,
marker: Option<Rndr::Node>,
hashed_items: IndexSet<K, BuildHasherDefault<FxHasher>>,
rendered_items: Vec<Option<V::State>>,
}
impl<T, I, K, KF, VF, V, Rndr> Render<Rndr> for Keyed<T, I, K, KF, VF, V, Rndr>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + 'static,
KF: Fn(&T) -> K,
V: Render<Rndr>,
VF: Fn(T) -> V,
Rndr: Renderer,
Rndr::Element: Clone,
{
type State = KeyedState<K, V, Rndr>;
fn build(self) -> Self::State {
let items = self.items.into_iter();
let (capacity, _) = items.size_hint();
let mut hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut rendered_items = Vec::new();
for item in items {
hashed_items.insert((self.key_fn)(&item));
let view = (self.view_fn)(item);
rendered_items.push(Some(view.build()));
}
KeyedState {
parent: None,
marker: None,
hashed_items,
rendered_items,
}
}
fn rebuild(self, state: &mut Self::State) {
let KeyedState {
parent,
marker,
hashed_items,
ref mut rendered_items,
} = state;
let new_items = self.items.into_iter();
let (capacity, _) = new_items.size_hint();
let mut new_hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut items = Vec::new();
for item in new_items {
new_hashed_items.insert((self.key_fn)(&item));
items.push(Some(item));
}
let cmds = diff(hashed_items, &new_hashed_items);
apply_diff(
parent
.as_ref()
.expect("Keyed list rebuilt before being mounted."),
marker,
cmds,
rendered_items,
&self.view_fn,
items,
);
*hashed_items = new_hashed_items;
}
}
impl<T, I, K, KF, VF, V, Rndr> RenderHtml<Rndr>
for Keyed<T, I, K, KF, VF, V, Rndr>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + 'static,
KF: Fn(&T) -> K,
V: RenderHtml<Rndr>,
VF: Fn(T) -> V,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
for item in self.items.into_iter() {
let item = (self.view_fn)(item);
item.to_html_with_buf(buf, position);
*position = Position::NextChild;
}
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) {
for item in self.items.into_iter() {
let item = (self.view_fn)(item);
item.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
*position = Position::NextChild;
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Rndr>,
position: &PositionState,
) -> Self::State {
// get parent and position
let current = cursor.current();
let parent = if position.get() == Position::FirstChild {
current
} else {
Rndr::get_parent(&current)
.expect("first child of keyed list has no parent")
};
let parent = Rndr::Element::cast_from(parent)
.expect("parent of keyed list should be an element");
// build list
let items = self.items.into_iter();
let (capacity, _) = items.size_hint();
let mut hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut rendered_items = Vec::new();
for item in items {
hashed_items.insert((self.key_fn)(&item));
let view = (self.view_fn)(item);
let item = view.hydrate::<FROM_SERVER>(cursor, position);
rendered_items.push(Some(item));
}
KeyedState {
parent: Some(parent),
marker: None, // TODO?
hashed_items,
rendered_items,
}
}
}
impl<K, V, Rndr> Mountable<Rndr> for KeyedState<K, V, Rndr>
where
K: Eq + Hash + 'static,
V: Render<Rndr>,
Rndr: Renderer,
Rndr::Element: Clone,
{
fn mount(&mut self, parent: &Rndr::Element, marker: Option<&Rndr::Node>) {
self.parent = Some(parent.clone());
for item in self.rendered_items.iter_mut().flatten() {
item.mount(parent, marker);
}
}
fn unmount(&mut self) {
for item in self.rendered_items.iter_mut().flatten() {
item.unmount();
}
}
fn insert_before_this(
&self,
parent: &<Rndr as Renderer>::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
self.rendered_items
.get(0)
.map(|n| n.insert_before_this(parent, child))
.unwrap_or(false)
}
}
trait VecExt<T> {
fn get_next_closest_mounted_sibling(
&self,
start_at: usize,
) -> Option<&Option<T>>;
}
impl<T> VecExt<T> for Vec<Option<T>> {
fn get_next_closest_mounted_sibling(
&self,
start_at: usize,
) -> Option<&Option<T>> {
self[start_at..].iter().find(|s| s.is_some())
}
}
/// Calculates the operations needed to get from `from` to `to`.
fn diff<K: Eq + Hash>(from: &FxIndexSet<K>, to: &FxIndexSet<K>) -> Diff {
if from.is_empty() && to.is_empty() {
return Diff::default();
} else if to.is_empty() {
return Diff {
clear: true,
..Default::default()
};
} else if from.is_empty() {
return Diff {
added: to
.iter()
.enumerate()
.map(|(at, _)| DiffOpAdd {
at,
mode: DiffOpAddMode::Append,
})
.collect(),
..Default::default()
};
}
let mut removed = vec![];
let mut moved = vec![];
let mut added = vec![];
let max_len = std::cmp::max(from.len(), to.len());
for index in 0..max_len {
let from_item = from.get_index(index);
let to_item = to.get_index(index);
// if they're the same, do nothing
if from_item != to_item {
// if it's only in old, not new, remove it
if from_item.is_some() && !to.contains(from_item.unwrap()) {
let op = DiffOpRemove { at: index };
removed.push(op);
}
// if it's only in new, not old, add it
if to_item.is_some() && !from.contains(to_item.unwrap()) {
let op = DiffOpAdd {
at: index,
mode: DiffOpAddMode::Normal,
};
added.push(op);
}
// if it's in both old and new, it can either
// 1) be moved (and need to move in the DOM)
// 2) be moved (but not need to move in the DOM)
// * this would happen if, for example, 2 items
// have been added before it, and it has moved by 2
if let Some(from_item) = from_item {
if let Some(to_item) = to.get_full(from_item) {
let moves_forward_by = (to_item.0 as i32) - (index as i32);
let move_in_dom = moves_forward_by
!= (added.len() as i32) - (removed.len() as i32);
let op = DiffOpMove {
from: index,
len: 1,
to: to_item.0,
move_in_dom,
};
moved.push(op);
}
}
}
}
moved = group_adjacent_moves(moved);
Diff {
removed,
items_to_move: moved.iter().map(|m| m.len).sum(),
moved,
added,
clear: false,
}
}
/// Group adjacent items that are being moved as a group.
/// For example from `[2, 3, 5, 6]` to `[1, 2, 3, 4, 5, 6]` should result
/// in a move for `2,3` and `5,6` rather than 4 individual moves.
fn group_adjacent_moves(moved: Vec<DiffOpMove>) -> Vec<DiffOpMove> {
let mut prev: Option<DiffOpMove> = None;
let mut new_moved = Vec::with_capacity(moved.len());
for m in moved {
match prev {
Some(mut p) => {
if (m.from == p.from + p.len) && (m.to == p.to + p.len) {
p.len += 1;
prev = Some(p);
} else {
new_moved.push(prev.take().unwrap());
prev = Some(m);
}
}
None => prev = Some(m),
}
}
if let Some(prev) = prev {
new_moved.push(prev)
}
new_moved
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Diff {
removed: Vec<DiffOpRemove>,
moved: Vec<DiffOpMove>,
items_to_move: usize,
added: Vec<DiffOpAdd>,
clear: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DiffOpMove {
/// The index this range is starting relative to `from`.
from: usize,
/// The number of elements included in this range.
len: usize,
/// The starting index this range will be moved to relative to `to`.
to: usize,
/// Marks this move to be applied to the DOM, or just to the underlying
/// storage
move_in_dom: bool,
}
impl Default for DiffOpMove {
fn default() -> Self {
Self {
from: 0,
to: 0,
len: 1,
move_in_dom: true,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct DiffOpAdd {
at: usize,
mode: DiffOpAddMode,
}
#[derive(Debug, PartialEq, Eq)]
struct DiffOpRemove {
at: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DiffOpAddMode {
Normal,
Append,
}
impl Default for DiffOpAddMode {
fn default() -> Self {
Self::Normal
}
}
fn apply_diff<T, V, Rndr>(
parent: &Rndr::Element,
marker: &Option<Rndr::Node>,
diff: Diff,
children: &mut Vec<Option<V::State>>,
view_fn: impl Fn(T) -> V,
mut items: Vec<Option<T>>,
) where
V: Render<Rndr>,
Rndr: Renderer,
{
// The order of cmds needs to be:
// 1. Clear
// 2. Removals
// 3. Move out
// 4. Resize
// 5. Move in
// 6. Additions
// 7. Removes holes
if diff.clear {
// TODO fix
Rndr::clear_children(parent);
children.clear();
if diff.added.is_empty() {
return;
}
}
for DiffOpRemove { at } in &diff.removed {
let mut item_to_remove = children[*at].take().unwrap();
item_to_remove.unmount();
}
let (move_cmds, add_cmds) = unpack_moves(&diff);
let mut moved_children = move_cmds
.iter()
.map(|move_| children[move_.from].take())
.collect::<Vec<_>>();
children.resize_with(children.len() + diff.added.len(), || None);
for (i, DiffOpMove { to, .. }) in move_cmds
.iter()
.enumerate()
.filter(|(_, move_)| !move_.move_in_dom)
{
children[*to] = moved_children[i].take();
}
for (i, DiffOpMove { to, .. }) in move_cmds
.into_iter()
.enumerate()
.filter(|(_, move_)| move_.move_in_dom)
{
let mut each_item = moved_children[i].take().unwrap();
if let Some(Some(state)) = children.get_next_closest_mounted_sibling(to)
{
state.insert_before_this_or_marker(
parent,
&mut each_item,
marker.as_ref(),
)
} else {
each_item.mount(parent, marker.as_ref());
}
children[to] = Some(each_item);
}
for DiffOpAdd { at, mode } in add_cmds {
let item = items[at].take().unwrap();
let item = view_fn(item);
let mut item = item.build();
match mode {
DiffOpAddMode::Normal => {
if let Some(Some(state)) =
children.get_next_closest_mounted_sibling(at)
{
state.insert_before_this_or_marker(
parent,
&mut item,
marker.as_ref(),
)
} else {
item.mount(parent, marker.as_ref());
}
}
DiffOpAddMode::Append => {
item.mount(parent, None);
}
}
children[at] = Some(item);
}
#[allow(unstable_name_collisions)]
children.drain_filter(|c| c.is_none());
}
fn unpack_moves(diff: &Diff) -> (Vec<DiffOpMove>, Vec<DiffOpAdd>) {
let mut moves = Vec::with_capacity(diff.items_to_move);
let mut adds = Vec::with_capacity(diff.added.len());
let mut removes_iter = diff.removed.iter();
let mut adds_iter = diff.added.iter();
let mut moves_iter = diff.moved.iter();
let mut removes_next = removes_iter.next();
let mut adds_next = adds_iter.next();
let mut moves_next = moves_iter.next().copied();
for i in 0..diff.items_to_move + diff.added.len() + diff.removed.len() {
if let Some(DiffOpRemove { at, .. }) = removes_next {
if i == *at {
removes_next = removes_iter.next();
continue;
}
}
match (adds_next, &mut moves_next) {
(Some(add), Some(move_)) => {
if add.at == i {
adds.push(*add);
adds_next = adds_iter.next();
} else {
let mut single_move = *move_;
single_move.len = 1;
moves.push(single_move);
move_.len -= 1;
move_.from += 1;
move_.to += 1;
if move_.len == 0 {
moves_next = moves_iter.next().copied();
}
}
}
(Some(add), None) => {
adds.push(*add);
adds_next = adds_iter.next();
}
(None, Some(move_)) => {
let mut single_move = *move_;
single_move.len = 1;
moves.push(single_move);
move_.len -= 1;
move_.from += 1;
move_.to += 1;
if move_.len == 0 {
moves_next = moves_iter.next().copied();
}
}
(None, None) => break,
}
}
(moves, adds)
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::element::{li, ul, HtmlElement, Li},
renderer::mock_dom::MockDom,
view::{keyed::keyed, Render},
};
fn item(key: usize) -> HtmlElement<Li, (), String, MockDom> {
li((), key.to_string())
}
#[test]
fn keyed_creates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let el_state = el.build();
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li></ul>"
);
}
#[test]
fn adding_items_updates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed(1..=5, |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>"
);
}
#[test]
fn removing_items_updates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed(1..=2, |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li></ul>"
);
}
#[test]
fn swapping_items_updates_list() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([1, 4, 3, 2, 5], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>4</li><li>3</li><li>2</li><li>5</li></ul>"
);
}
#[test]
fn swapping_and_removing_orders_correctly() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([1, 4, 3, 5], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>4</li><li>3</li><li>5</li></ul>"
);
}
#[test]
fn arbitrarily_hard_adjustment() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([2, 4, 3], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>2</li><li>4</li><li>3</li></ul>"
);
}
#[test]
fn a_series_of_moves() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([2, 4, 3], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([1, 7, 5, 11, 13, 17], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([2, 6, 8, 7, 13], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([13, 4, 5, 3], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([1, 2, 3, 4], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>"
);
}
#[test]
fn clearing_works() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(el_state.el.to_debug_html(), "<ul></ul>");
}
}
*/

340
tachys/src/view/mod.rs Normal file
View file

@ -0,0 +1,340 @@
use crate::{hydration::Cursor, renderer::Renderer, ssr::StreamBuilder};
use parking_lot::RwLock;
use std::sync::Arc;
pub mod any_view;
pub mod either;
pub mod error_boundary;
pub mod iterators;
pub mod keyed;
mod primitives;
#[cfg(feature = "nightly")]
pub mod static_types;
pub mod strings;
pub mod template;
pub mod tuples;
/// The `Render` trait allows rendering something as part of the user interface.
///
/// It is generic over the renderer itself, as long as that implements the [`Renderer`]
/// trait.
pub trait Render<R: Renderer> {
/// The “view state” for this type, which can be retained between updates.
///
/// For example, for a text node, `State` might be the actual DOM text node
/// and the previous string, to allow for diffing between updates.
type State: Mountable<R>;
/// Creates the view for the first time, without hydrating from existing HTML.
fn build(self) -> Self::State;
/// Updates the view with new data.
fn rebuild(self, state: &mut Self::State);
}
pub trait InfallibleRender {}
pub trait FallibleRender<R>: Sized + Render<R>
where
R: Renderer,
{
type FallibleState: Mountable<R>;
type Error;
/// Creates the view fallibly, handling any [`Result`] by propagating its `Err`.
fn try_build(self) -> Result<Self::FallibleState, Self::Error>;
/// Updates the view with new data fallibly, handling any [`Result`] by propagating its `Err`.
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error>;
}
#[derive(Debug, Clone, Copy)]
pub struct NeverError;
impl core::fmt::Display for NeverError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Ok(())
}
}
impl std::error::Error for NeverError {}
impl<T, R> FallibleRender<R> for T
where
T: Render<R> + InfallibleRender,
R: Renderer,
{
type FallibleState = Self::State;
type Error = NeverError;
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
Ok(self.build())
}
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error> {
self.rebuild(state);
Ok(())
}
}
/// The `RenderHtml` trait allows rendering something to HTML, and transforming
/// that HTML into an interactive interface.
///
/// This process is traditionally called “server rendering” and “hydration.” As a
/// metaphor, this means that the structure of the view is created on the server, then
/// “dehydrated” to HTML, sent across the network, and “rehydrated” with interactivity
/// in the browser.
///
/// However, the same process can be done entirely in the browser: for example, a view
/// can be transformed into some HTML that is used to create a `<template>` node, which
/// can be cloned many times and “hydrated,” which is more efficient than creating the
/// whole view piece by piece.
pub trait RenderHtml<R: Renderer>
where
Self: Render<R>,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize;
fn min_length(&self) -> usize {
Self::MIN_LENGTH
}
/// Renders a view to an HTML string.
fn to_html(self) -> String
where
Self: Sized,
{
let mut buf = String::with_capacity(Self::MIN_LENGTH);
self.to_html_with_buf(&mut buf, &mut Position::FirstChild);
buf
}
/// Renders a view to an in-order stream of HTML.
fn to_html_stream_in_order(self) -> StreamBuilder
where
Self: Sized,
{
let mut builder = StreamBuilder::default();
self.to_html_async_with_buf::<false>(
&mut builder,
&mut Position::FirstChild,
);
builder.finish()
}
/// Renders a view to an out-of-order stream of HTML.
fn to_html_stream_out_of_order(self) -> StreamBuilder
where
Self: Sized,
{
let mut builder = StreamBuilder::new(Some(vec![0]));
self.to_html_async_with_buf::<true>(
&mut builder,
&mut Position::FirstChild,
);
builder.finish()
}
/// Renders a view to an HTML string, asynchronously.
/* fn to_html_stream(self) -> impl Stream<Item = String>
where
Self: Sized,
{
use crate::ssr::handle_chunks;
use futures::channel::mpsc::unbounded;
let mut chunks = VecDeque::new();
let mut curr = String::new();
self.to_html_async_with_buf(
&mut chunks,
&mut curr,
&PositionState::new(Position::FirstChild),
);
let (tx, rx) = unbounded();
handle_chunks(tx, chunks).await;
rx
} */
/// Renders a view to HTML, writing it into the given buffer.
fn to_html_with_buf(self, buf: &mut String, position: &mut Position);
/// Renders a view into a buffer of (synchronous or asynchronous) HTML chunks.
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
buf.with_buf(|buf| self.to_html_with_buf(buf, position));
}
/// Makes a set of DOM nodes rendered from HTML interactive.
///
/// If `FROM_SERVER` is `true`, this HTML was rendered using [`RenderHtml::to_html`]
/// (e.g., during server-side rendering ).
///
/// If `FROM_SERVER` is `false`, the HTML was rendered using [`ToTemplate::to_template`]
/// (e.g., into a `<template>` element).
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State;
/// Hydrates using [`RenderHtml::hydrate`], beginning at the given element.
fn hydrate_from<const FROM_SERVER: bool>(
self,
el: &R::Element,
) -> Self::State
where
Self: Sized,
{
self.hydrate_from_position::<FROM_SERVER>(el, Position::default())
}
/// Hydrates using [`RenderHtml::hydrate`], beginning at the given element and position.
fn hydrate_from_position<const FROM_SERVER: bool>(
self,
el: &R::Element,
position: Position,
) -> Self::State
where
Self: Sized,
{
let cursor = Cursor::new(el.clone());
let position = PositionState::new(position);
self.hydrate::<FROM_SERVER>(&cursor, &position)
}
}
/// Allows a type to be mounted to the DOM.
pub trait Mountable<R: Renderer> {
/// Detaches the view from the DOM.
fn unmount(&mut self);
/// Mounts a node to the interface.
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>);
/// Inserts another `Mountable` type before this one. Returns `false` if
/// this does not actually exist in the UI (for example, `()`).
fn insert_before_this(
&self,
parent: &R::Element,
child: &mut dyn Mountable<R>,
) -> bool;
/// Inserts another `Mountable` type before this one, or before the marker
/// if this one doesn't exist in the UI (for example, `()`).
fn insert_before_this_or_marker(
&self,
parent: &R::Element,
child: &mut dyn Mountable<R>,
marker: Option<&R::Node>,
) {
if !self.insert_before_this(parent, child) {
child.mount(parent, marker);
}
}
}
/// Indicates where a node should be mounted to its parent.
pub enum MountKind<R>
where
R: Renderer,
{
/// Node should be mounted before this marker node.
Before(R::Node),
/// Node should be appended to the parents children.
Append,
}
impl<T, R> Mountable<R> for Option<T>
where
T: Mountable<R>,
R: Renderer,
{
fn unmount(&mut self) {
if let Some(ref mut mounted) = self {
mounted.unmount()
}
}
fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
if let Some(ref mut inner) = self {
inner.mount(parent, marker);
}
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
self.as_ref()
.map(|inner| inner.insert_before_this(parent, child))
.unwrap_or(false)
}
}
/// Allows data to be added to a static template.
pub trait ToTemplate {
const TEMPLATE: &'static str = "";
const CLASS: &'static str = "";
const STYLE: &'static str = "";
const LEN: usize = Self::TEMPLATE.as_bytes().len();
/// Renders a view type to a template. This does not take actual view data,
/// but can be used for constructing part of an HTML `<template>` that corresponds
/// to a view of a particular type.
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
);
}
#[derive(Debug, Default, Clone)]
pub struct PositionState(Arc<RwLock<Position>>);
impl PositionState {
pub fn new(position: Position) -> Self {
Self(Arc::new(RwLock::new(position)))
}
pub fn set(&self, position: Position) {
*self.0.write() = position;
}
pub fn get(&self) -> Position {
*self.0.read()
}
pub fn deep_clone(&self) -> Self {
let current = self.get();
Self(Arc::new(RwLock::new(current)))
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub enum Position {
Current,
#[default]
FirstChild,
NextChild,
NextChildAfterText,
OnlyChild,
LastChild,
}

View file

@ -0,0 +1,170 @@
use super::{
InfallibleRender, Mountable, Position, PositionState, Render, RenderHtml,
};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
view::ToTemplate,
};
use std::{
fmt::Write,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64,
NonZeroU8, NonZeroUsize,
},
};
macro_rules! render_primitive {
($($child_type:ty),* $(,)?) => {
$(
paste::paste! {
pub struct [<$child_type:camel State>]<R>(R::Text, $child_type) where R: Renderer;
impl<'a, R: Renderer> Mountable<R> for [<$child_type:camel State>]<R> {
fn unmount(&mut self) {
self.0.unmount()
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
R::insert_node(parent, self.0.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.0.as_ref()));
true
}
}
impl<'a, R: Renderer> Render<R> for $child_type {
type State = [<$child_type:camel State>]<R>;
fn build(self) -> Self::State {
let node = R::create_text_node(&self.to_string());
[<$child_type:camel State>](node, self)
}
fn rebuild(self, state: &mut Self::State) {
let [<$child_type:camel State>](node, this) = state;
if &self != this {
R::set_text(node, &self.to_string());
*this = self;
}
}
}
impl<'a> InfallibleRender for $child_type {}
impl<'a, R> RenderHtml<R> for $child_type
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
write!(buf, "{}", self);
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
// separating placeholder marker comes before text node
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
let node = cursor.current();
let node = R::Text::cast_from(node)
.expect("couldn't cast text node from node");
if !FROM_SERVER {
R::set_text(&node, &self.to_string());
}
position.set(Position::NextChildAfterText);
[<$child_type:camel State>](node, self)
}
}
impl<'a> ToTemplate for $child_type {
const TEMPLATE: &'static str = " <!>";
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push(' ');
*position = Position::NextChildAfterText;
}
}
}
)*
};
}
render_primitive![
usize,
u8,
u16,
u32,
u64,
u128,
isize,
i8,
i16,
i32,
i64,
i128,
f32,
f64,
char,
bool,
IpAddr,
SocketAddr,
SocketAddrV4,
SocketAddrV6,
Ipv4Addr,
Ipv6Addr,
NonZeroI8,
NonZeroU8,
NonZeroI16,
NonZeroU16,
NonZeroI32,
NonZeroU32,
NonZeroI64,
NonZeroU64,
NonZeroI128,
NonZeroU128,
NonZeroIsize,
NonZeroUsize,
];

View file

@ -0,0 +1,183 @@
use super::{
InfallibleRender, Mountable, Position, PositionState, Render, RenderHtml,
ToTemplate,
};
use crate::{
html::{
attribute::{Attribute, AttributeKey, AttributeValue},
class::IntoClass,
style::IntoStyle,
},
hydration::Cursor,
renderer::{DomRenderer, Renderer},
};
use std::marker::PhantomData;
/// An attribute for which both the key and the value are known at compile time,
/// i.e., as `&'static str`s.
///
/// ```
/// use tachydom::{
/// html::attribute::{Attribute, Type},
/// view::static_types::{static_attr, StaticAttr},
/// };
/// let input_type = static_attr::<Type, "text">();
/// let mut buf = String::new();
/// let mut classes = String::new();
/// let mut styles = String::new();
/// input_type.to_html(&mut buf, &mut classes, &mut styles);
/// assert_eq!(buf, " type=\"text\"");
/// ```
#[derive(Debug)]
pub struct StaticAttr<K: AttributeKey, const V: &'static str> {
ty: PhantomData<K>,
}
impl<K: AttributeKey, const V: &'static str> PartialEq for StaticAttr<K, V> {
fn eq(&self, _other: &Self) -> bool {
// by definition, two static attrs with same key and same const V are same
true
}
}
pub fn static_attr<K: AttributeKey, const V: &'static str>() -> StaticAttr<K, V>
{
StaticAttr { ty: PhantomData }
}
impl<K, const V: &'static str> ToTemplate for StaticAttr<K, V>
where
K: AttributeKey,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
buf.push(' ');
buf.push_str(K::KEY);
buf.push_str("=\"");
buf.push_str(V);
buf.push('"');
}
}
impl<K, const V: &'static str, R> Attribute<R> for StaticAttr<K, V>
where
K: AttributeKey,
R: Renderer,
R::Element: Clone,
{
const MIN_LENGTH: usize = K::KEY.len() + 3 + V.len(); // K::KEY + ="..." + V
type State = ();
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
AttributeValue::<R>::to_html(V, K::KEY, buf)
}
fn hydrate<const FROM_SERVER: bool>(self, _el: &R::Element) -> Self::State {
}
fn build(self, el: &R::Element) -> Self::State {
R::set_attribute(el, K::KEY, V);
}
fn rebuild(self, _state: &mut Self::State) {}
}
#[derive(Debug)]
pub struct Static<const V: &'static str>;
impl<const V: &'static str> PartialEq for Static<V> {
fn eq(&self, _other: &Self) -> bool {
// by definition, two static values of same const V are same
true
}
}
impl<const V: &'static str> AsRef<str> for Static<V> {
fn as_ref(&self) -> &str {
V
}
}
impl<const V: &'static str, R: Renderer> Render<R> for Static<V>
where
R::Text: Mountable<R>,
{
type State = Option<R::Text>;
fn build(self) -> Self::State {
// a view state has to be returned so it can be mounted
Some(R::create_text_node(V))
}
// This type is specified as static, so no rebuilding is done.
fn rebuild(self, _state: &mut Self::State) {}
}
impl<const V: &'static str> InfallibleRender for Static<V> {}
impl<const V: &'static str, R> RenderHtml<R> for Static<V>
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
R::Text: Mountable<R>,
{
const MIN_LENGTH: usize = V.len();
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push_str(V);
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
position.set(Position::NextChildAfterText);
// no view state is created when hydrating, because this is static
None
}
}
impl<const V: &'static str> ToTemplate for Static<V> {
const TEMPLATE: &'static str = V;
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push_str(V);
*position = Position::NextChildAfterText;
}
}

382
tachys/src/view/strings.rs Normal file
View file

@ -0,0 +1,382 @@
use super::{
InfallibleRender, Mountable, Position, PositionState, Render, RenderHtml,
ToTemplate,
};
use crate::{
hydration::Cursor,
renderer::{CastFrom, Renderer},
};
use std::{rc::Rc, sync::Arc};
pub struct StrState<'a, R: Renderer> {
pub node: R::Text,
str: &'a str,
}
impl<'a, R: Renderer> Render<R> for &'a str {
type State = StrState<'a, R>;
fn build(self) -> Self::State {
let node = R::create_text_node(self);
StrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let StrState { node, str } = state;
if &self != str {
R::set_text(node, self);
*str = self;
}
}
}
impl<'a> InfallibleRender for &'a str {}
impl<'a, R> RenderHtml<R> for &'a str
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push_str(self);
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
// separating placeholder marker comes before text node
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
let node = cursor.current();
let node = R::Text::cast_from(node)
.expect("couldn't cast text node from node");
if !FROM_SERVER {
R::set_text(&node, self);
}
position.set(Position::NextChildAfterText);
StrState { node, str: self }
}
}
impl<'a> ToTemplate for &'a str {
const TEMPLATE: &'static str = " <!>";
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push(' ');
*position = Position::NextChildAfterText;
}
}
impl<'a, R> Mountable<R> for StrState<'a, R>
where
R: Renderer,
{
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
R::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.node.as_ref()));
true
}
}
pub struct StringState<R: Renderer> {
node: R::Text,
str: String,
}
impl<R: Renderer> Render<R> for String {
type State = StringState<R>;
fn build(self) -> Self::State {
let node = R::create_text_node(&self);
StringState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let StringState { node, str } = state;
if &self != str {
R::set_text(node, &self);
*str = self;
}
}
}
impl InfallibleRender for String {}
impl<R> RenderHtml<R> for String
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
<&str as RenderHtml<R>>::to_html_with_buf(self.as_str(), buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let StrState { node, .. } =
self.as_str().hydrate::<FROM_SERVER>(cursor, position);
StringState { node, str: self }
}
}
impl ToTemplate for String {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl<R: Renderer> Mountable<R> for StringState<R> {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
R::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.node.as_ref()));
true
}
}
pub struct RcStrState<R: Renderer> {
node: R::Text,
str: Rc<str>,
}
impl<R: Renderer> Render<R> for Rc<str> {
type State = RcStrState<R>;
fn build(self) -> Self::State {
let node = R::create_text_node(&self);
RcStrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let RcStrState { node, str } = state;
if !Rc::ptr_eq(&self, str) {
R::set_text(node, &self);
*str = self;
}
}
}
impl InfallibleRender for Rc<str> {}
impl<R> RenderHtml<R> for Rc<str>
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
<&str as RenderHtml<R>>::to_html_with_buf(&self, buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let this: &str = self.as_ref();
let StrState { node, .. } =
this.hydrate::<FROM_SERVER>(cursor, position);
RcStrState { node, str: self }
}
}
impl ToTemplate for Rc<str> {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl<R: Renderer> Mountable<R> for RcStrState<R> {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
R::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.node.as_ref()));
true
}
}
pub struct ArcStrState<R: Renderer> {
node: R::Text,
str: Arc<str>,
}
impl<R: Renderer> Render<R> for Arc<str> {
type State = ArcStrState<R>;
fn build(self) -> Self::State {
let node = R::create_text_node(&self);
ArcStrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let ArcStrState { node, str } = state;
if !Arc::ptr_eq(&self, str) {
R::set_text(node, &self);
*str = self;
}
}
}
impl InfallibleRender for Arc<str> {}
impl<R> RenderHtml<R> for Arc<str>
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
<&str as RenderHtml<R>>::to_html_with_buf(&self, buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
let this: &str = self.as_ref();
let StrState { node, .. } =
this.hydrate::<FROM_SERVER>(cursor, position);
ArcStrState { node, str: self }
}
}
impl ToTemplate for Arc<str> {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl<R: Renderer> Mountable<R> for ArcStrState<R> {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
R::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(
&self,
parent: &<R as Renderer>::Element,
child: &mut dyn Mountable<R>,
) -> bool {
child.mount(parent, Some(self.node.as_ref()));
true
}
}

115
tachys/src/view/template.rs Normal file
View file

@ -0,0 +1,115 @@
use super::{
Mountable, Position, PositionState, Render, RenderHtml, ToTemplate,
};
use crate::{dom::document, hydration::Cursor, renderer::dom::Dom};
use once_cell::unsync::Lazy;
use rustc_hash::FxHashMap;
use std::{any::TypeId, cell::RefCell};
use wasm_bindgen::JsCast;
use web_sys::HtmlTemplateElement;
thread_local! {
static TEMPLATE_ELEMENT: Lazy<HtmlTemplateElement> =
Lazy::new(|| document().create_element("template").unwrap().unchecked_into());
}
pub struct ViewTemplate<V: Render<Dom> + ToTemplate> {
view: V,
}
thread_local! {
static TEMPLATES: RefCell<FxHashMap<TypeId, HtmlTemplateElement>> = Default::default();
}
impl<V: Render<Dom> + ToTemplate + 'static> ViewTemplate<V> {
pub fn new(view: V) -> Self {
Self { view }
}
fn to_template() -> HtmlTemplateElement {
TEMPLATES.with(|t| {
t.borrow_mut()
.entry(TypeId::of::<V>())
.or_insert_with(|| {
let tpl = TEMPLATE_ELEMENT.with(|t| {
t.clone_node()
.unwrap()
.unchecked_into::<HtmlTemplateElement>()
});
/* let mut buf = String::new();
let mut class = String::new();
let mut style = String::new();
V::to_template(
&mut buf,
&mut class,
&mut style,
&mut Default::default(),
);
tpl.set_inner_html(&buf); */
//log(&format!("setting template to {:?}", V::TEMPLATE));
tpl.set_inner_html(V::TEMPLATE);
tpl
})
.clone()
})
}
}
impl<V> Render<Dom> for ViewTemplate<V>
where
V: Render<Dom> + RenderHtml<Dom> + ToTemplate + 'static,
V::State: Mountable<Dom>,
{
type State = V::State;
fn build(self) -> Self::State {
let tpl = Self::to_template();
let contents = tpl.content().clone_node_with_deep(true).unwrap();
self.view.hydrate::<false>(
&Cursor::new(contents.unchecked_into()),
&Default::default(),
)
}
fn rebuild(self, state: &mut Self::State) {
self.view.rebuild(state)
}
}
impl<V> RenderHtml<Dom> for ViewTemplate<V>
where
V: RenderHtml<Dom> + ToTemplate + 'static,
V::State: Mountable<Dom>,
{
const MIN_LENGTH: usize = V::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
self.view.to_html_with_buf(buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<Dom>,
position: &PositionState,
) -> Self::State {
self.view.hydrate::<FROM_SERVER>(cursor, position)
}
}
impl<V> ToTemplate for ViewTemplate<V>
where
V: RenderHtml<Dom> + ToTemplate + 'static,
V::State: Mountable<Dom>,
{
const TEMPLATE: &'static str = V::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
V::to_template(buf, class, style, inner_html, position);
}
}

352
tachys/src/view/tuples.rs Normal file
View file

@ -0,0 +1,352 @@
use super::{
Mountable, Position, PositionState, Render, RenderHtml, Renderer,
ToTemplate,
};
use crate::{
hydration::Cursor,
view::{FallibleRender, InfallibleRender, StreamBuilder},
};
use const_str_slice_concat::{
const_concat, const_concat_with_separator, str_from_buffer,
};
use std::error::Error;
impl<R: Renderer> Render<R> for () {
type State = ();
fn build(self) -> Self::State {}
fn rebuild(self, _state: &mut Self::State) {}
}
impl InfallibleRender for () {}
impl<R> RenderHtml<R> for ()
where
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(self, _buf: &mut String, _position: &mut Position) {}
fn hydrate<const FROM_SERVER: bool>(
self,
_cursor: &Cursor<R>,
_position: &PositionState,
) -> Self::State {
}
}
impl<R: Renderer> Mountable<R> for () {
fn unmount(&mut self) {}
fn mount(&mut self, _parent: &R::Element, _marker: Option<&R::Node>) {}
fn insert_before_this(
&self,
_parent: &<R as Renderer>::Element,
_child: &mut dyn Mountable<R>,
) -> bool {
false
}
}
impl ToTemplate for () {
const TEMPLATE: &'static str = "";
fn to_template(
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
}
}
impl<A: Render<R>, R: Renderer> Render<R> for (A,) {
type State = A::State;
fn build(self) -> Self::State {
self.0.build()
}
fn rebuild(self, state: &mut Self::State) {
self.0.rebuild(state)
}
}
impl<A: FallibleRender<R>, R: Renderer> FallibleRender<R> for (A,) {
type Error = A::Error;
type FallibleState = A::FallibleState;
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
self.0.try_build()
}
fn try_rebuild(
self,
state: &mut Self::FallibleState,
) -> Result<(), Self::Error> {
self.0.try_rebuild(state)
}
}
impl<A, R> RenderHtml<R> for (A,)
where
A: RenderHtml<R>,
R: Renderer,
R::Node: Clone,
R::Element: Clone,
{
const MIN_LENGTH: usize = A::MIN_LENGTH;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
self.0.to_html_with_buf(buf, position);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
self.0.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor<R>,
position: &PositionState,
) -> Self::State {
self.0.hydrate::<FROM_SERVER>(cursor, position)
}
}
impl<A: ToTemplate> ToTemplate for (A,) {
const TEMPLATE: &'static str = A::TEMPLATE;
const CLASS: &'static str = A::CLASS;
const STYLE: &'static str = A::STYLE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
A::to_template(buf, class, style, inner_html, position)
}
}
macro_rules! impl_view_for_tuples {
($first:ident, $($ty:ident),* $(,)?) => {
impl<$first, $($ty),*, Rndr> Render<Rndr> for ($first, $($ty,)*)
where
$first: Render<Rndr>,
$($ty: Render<Rndr>),*,
Rndr: Renderer
{
type State = ($first::State, $($ty::State,)*);
fn build(self) -> Self::State {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
(
[<$first:lower>].build(),
$([<$ty:lower>].build()),*
)
}
}
fn rebuild(self, state: &mut Self::State) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].rebuild([<view_ $first:lower>]);
$([<$ty:lower>].rebuild([<view_ $ty:lower>]));*
}
}
}
impl<$first, $($ty),*, Rndr> FallibleRender<Rndr> for ($first, $($ty,)*)
where
$first: FallibleRender<Rndr>,
$($ty: FallibleRender<Rndr>),*,
$first::Error: Error + 'static,
$($ty::Error: Error + 'static),*,
Rndr: Renderer
{
type Error = (); /* Box<dyn Error>; */
type FallibleState = ($first::FallibleState, $($ty::FallibleState,)*);
fn try_build(self) -> Result<Self::FallibleState, Self::Error> {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
Ok((
[<$first:lower>].try_build().map_err(|_| ())?,
$([<$ty:lower>].try_build().map_err(|_| ())?),*
))
}
}
fn try_rebuild(self, state: &mut Self::FallibleState) -> Result<(), Self::Error> {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].try_rebuild([<view_ $first:lower>]).map_err(|_| ())?;
$([<$ty:lower>].try_rebuild([<view_ $ty:lower>]).map_err(|_| ())?);*
}
Ok(())
}
}
impl<$first, $($ty),*, Rndr> RenderHtml<Rndr> for ($first, $($ty,)*)
where
$first: RenderHtml<Rndr>,
$($ty: RenderHtml<Rndr>),*,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone
{
const MIN_LENGTH: usize = $first::MIN_LENGTH $(+ $ty::MIN_LENGTH)*;
fn to_html_with_buf(self, buf: &mut String, position: &mut Position) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)* ) = self;
[<$first:lower>].to_html_with_buf(buf, position);
$([<$ty:lower>].to_html_with_buf(buf, position));*
}
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
) where
Self: Sized,
{
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)* ) = self;
[<$first:lower>].to_html_async_with_buf::<OUT_OF_ORDER>(buf, position);
$([<$ty:lower>].to_html_async_with_buf::<OUT_OF_ORDER>(buf, position));*
}
}
fn hydrate<const FROM_SERVER: bool>(self, cursor: &Cursor<Rndr>, position: &PositionState) -> Self::State {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)* ) = self;
(
[<$first:lower>].hydrate::<FROM_SERVER>(cursor, position),
$([<$ty:lower>].hydrate::<FROM_SERVER>(cursor, position)),*
)
}
}
}
impl<$first, $($ty),*> ToTemplate for ($first, $($ty,)*)
where
$first: ToTemplate,
$($ty: ToTemplate),*
{
const TEMPLATE: &'static str = str_from_buffer(&const_concat(&[
$first::TEMPLATE, $($ty::TEMPLATE),*
]));
const CLASS: &'static str = str_from_buffer(&const_concat_with_separator(&[
$first::CLASS, $($ty::CLASS),*
], " "));
const STYLE: &'static str = str_from_buffer(&const_concat_with_separator(&[
$first::STYLE, $($ty::STYLE),*
], ";"));
fn to_template(buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String, position: &mut Position) {
paste::paste! {
$first ::to_template(buf, class, style, inner_html, position);
$($ty::to_template(buf, class, style, inner_html, position));*;
}
}
}
impl<$first, $($ty),*, Rndr> Mountable<Rndr> for ($first, $($ty,)*) where
$first: Mountable<Rndr>,
$($ty: Mountable<Rndr>),*,
Rndr: Renderer
{
fn unmount(&mut self) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
[<$first:lower>].unmount();
$([<$ty:lower>].unmount());*
}
}
fn mount(
&mut self,
parent: &Rndr::Element,
marker: Option<&Rndr::Node>,
) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
[<$first:lower>].mount(parent, marker);
$([<$ty:lower>].mount(parent, marker));*
}
}
fn insert_before_this(
&self,
parent: &Rndr::Element,
child: &mut dyn Mountable<Rndr>,
) -> bool {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
[<$first:lower>].insert_before_this(parent, child)
$(|| [<$ty:lower>].insert_before_this(parent, child))*
}
}
}
};
}
impl_view_for_tuples!(A, B);
impl_view_for_tuples!(A, B, C);
impl_view_for_tuples!(A, B, C, D);
impl_view_for_tuples!(A, B, C, D, E);
impl_view_for_tuples!(A, B, C, D, E, F);
impl_view_for_tuples!(A, B, C, D, E, F, G);
impl_view_for_tuples!(A, B, C, D, E, F, G, H);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);