Initial commit

This commit is contained in:
Greg Johnston 2022-07-31 16:46:14 -04:00
parent e587d985e0
commit 17c2faeb56
64 changed files with 6616 additions and 9 deletions

15
.gitignore vendored
View file

@ -1,10 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
target
dist
pkg
comparisons
blob.rs
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
**/*.rs.bk

29
TODO.md Normal file
View file

@ -0,0 +1,29 @@
- [ ] Async
- [ ] Resource
- [ ] Suspense
- [ ] Docs (and clippy warning to insist on docs)
- [ ] Read through + understand...
- [ ] `Props` macro
- [ ] `component` macro
- [ ] renderer
- [ ] array reconciliation (bundle size?)
- [ ] memory management of scopes
- Reactive system improvements
- [ ] Dispose of scopes properly
- [ ] Effects should take `Option<T>` and return `T`
- [ ] Better `create_memo` implementation
- [ ] `create_signal` return actual closures?
- [ ] Scheduling effets/run effects at end of render
- [ ] `batch()`
- [ ] Examples
- [ ] API fetch w/ Suspense
- [ ] Router
- [ ] Portals
- [ ] SSR
- [ ] Macro
- [ ] Streaming HTML from server
- [ ] Streaming `Resource`s
- [ ] Loaders
- [ ] Transitions
- [ ] Tutorials + website
- [ ] Scoped CSS

View file

@ -0,0 +1,13 @@
[package]
name = "children"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { path = "../../leptos" }
wee_alloc = "0.4"
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="rust" data-wasm-opt="z"/>
</head>
<body></body>
</html>

View file

@ -0,0 +1,53 @@
use leptos::*;
use leptos_dom::wasm_bindgen::{JsCast, UnwrapThrowExt};
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
fn main() {
mount_to_body(|cx| {
view! { <Parent/> }
})
}
type CounterHolder = Vec<(usize, (ReadSignal<i32>, WriteSignal<i32>))>;
struct CounterUpdater {
set_counters: WriteSignal<CounterHolder>,
}
#[component]
fn Parent(cx: Scope) -> web_sys::Element {
let (value, _) = cx.signal(0);
view! {
<div>
"regular"
<h1>"Children should appear below"</h1>
{|| create_text_node(&value.get().to_string())}
<HasChildren>
<span>"Child A"</span>
<span>"Child B"</span>
<span>"Child C"</span>
</HasChildren>
</div>
}
}
#[component]
fn HasChildren(cx: Scope, children: Vec<Element>) -> web_sys::Element {
view! {
<div>
<h2>"I have children:"</h2>
<ul>
{
children.into_iter().map(|child| {
debug_warn!("child is {:?}", child.outer_html());
view! { <li>{child}</li> }
}).collect::<Vec<_>>()
}
</ul>
</div>
}
}

View file

@ -0,0 +1,16 @@
[package]
name = "counter"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { path = "../../leptos" }
wee_alloc = "0.4"
[dev-dependencies]
wasm-bindgen-test = "0.3.0"
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="rust" data-wasm-opt="z"/>
</head>
<body></body>
</html>

View file

@ -0,0 +1,13 @@
use leptos::*;
pub fn simple_counter(cx: Scope) -> web_sys::Element {
let (value, set_value) = cx.signal(0);
view! {
<div>
<button on:click=move |_| set_value(|value| *value -= 1)>"-1"</button>
<span>{|| value.get().to_string()}</span>
<button on:click=move |_| set_value(|value| *value += 1)>"+1"</button>
</div>
}
}

View file

@ -0,0 +1,9 @@
use counter::simple_counter;
use leptos::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub fn main() {
mount_to_body(simple_counter)
}

View file

@ -0,0 +1,40 @@
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use leptos::*;
use web_sys::HtmlElement;
#[wasm_bindgen_test]
fn inc() {
mount_to_body(counter::simple_counter);
let document = leptos::document();
let div = document.query_selector("div").unwrap().unwrap();
let dec = div
.first_child()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
let text = dec
.next_sibling()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
let inc = text
.next_sibling()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
inc.click();
inc.click();
assert_eq!(text.text_content(), Some("2".to_string()));
dec.click();
dec.click();
dec.click();
dec.click();
assert_eq!(text.text_content(), Some("-2".to_string()));
}

View file

@ -0,0 +1,16 @@
[package]
name = "counters"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { path = "../../leptos" }
wee_alloc = "0.4"
[dev-dependencies]
wasm-bindgen-test = "0.3.0"
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="rust" data-wasm-opt="z" data-weak-refs/>
</head>
<body></body>
</html>

View file

@ -0,0 +1,103 @@
use leptos::*;
use leptos::{For, ForProps};
type CounterHolder = Vec<(usize, (ReadSignal<i32>, WriteSignal<i32>))>;
struct CounterUpdater {
set_counters: WriteSignal<CounterHolder>,
}
#[component]
pub fn Counters(cx: Scope) -> web_sys::Element {
let (next_counter_id, set_next_counter_id) = cx.signal(0);
let (counters, set_counters) = cx.signal::<CounterHolder>(Vec::new());
cx.provide_context(CounterUpdater {
set_counters: (*set_counters).clone(),
});
let add_counter = move |_| {
let id = *next_counter_id.get_untracked();
let (read, write) = cx.signal(0);
set_counters(|counters| counters.push((id, (read.clone(), write.clone()))));
set_next_counter_id(|id| *id += 1);
};
let add_many_counters = move |_| {
let mut new_counters = vec![];
for next_id in 0..1000 {
let signal = cx.signal(0);
new_counters.push((next_id, (signal.0.clone(), signal.1.clone())));
}
set_counters(move |n| *n = new_counters.clone());
};
let clear_counters = move |_| {
set_counters(|counters| counters.clear());
};
view! {
<div>
<button on:click=add_counter>
"Add Counter"
</button>
<button on:click=add_many_counters>
"Add 1000 Counters"
</button>
<button on:click=clear_counters>
"Clear Counters"
</button>
<p>
"Total: "
<span>{move ||
counters.get()
.iter()
.map(|(_, (count, _))| *count.get())
.sum::<i32>()
.to_string()
}</span>
" from "
<span>{move || counters.get().len().to_string()}</span>
" counters."
</p>
<ul>
<For each={counters} key={|counter| counter.0}>{
|cx, (id, (value, set_value))| {
view! {
<Counter id=id value=value.clone() set_value=set_value.clone()/>
}
}
}</For>
</ul>
</div>
}
}
#[component]
fn Counter(
cx: Scope,
id: usize,
value: ReadSignal<i32>,
set_value: WriteSignal<i32>,
) -> web_sys::Element {
let CounterUpdater { set_counters } = cx.use_context().unwrap_throw();
let input = {
let set_value = set_value.clone();
move |ev| {
set_value(|value| *value = event_target_value(&ev).parse::<i32>().unwrap_or_default())
}
};
view! {
<li>
<button on:click={let set_value = set_value.clone(); move |_| set_value(|value| *value -= 1)}>"-1"</button>
<input type="text"
prop:value={let value = value.clone(); move || value.get().to_string()}
on:input=input
/>
<span>{move || value.get().to_string()}</span>
<button on:click=move |_| set_value(|value| *value += 1)>"+1"</button>
<button on:click=move |_| set_counters(|counters| counters.retain(|(counter_id, _)| counter_id != &id))>"x"</button>
</li>
}
}

View file

@ -0,0 +1,9 @@
use counters::{Counters, CountersProps};
use leptos::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
fn main() {
mount_to_body(|cx| view! { <Counters/> })
}

View file

@ -0,0 +1,111 @@
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use leptos::{wasm_bindgen::JsValue, *};
use web_sys::HtmlElement;
use counters::{Counters, CountersProps};
#[wasm_bindgen_test]
fn inc() {
mount_to_body(|cx| view! { <Counters/> });
let document = leptos::document();
let div = document.query_selector("div").unwrap().unwrap();
let add_counter = div
.first_child()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
// add 3 counters
add_counter.click();
add_counter.click();
add_counter.click();
// check HTML
assert_eq!(div.inner_html(), "<button>Add Counter</button><button>Add 1000 Counters</button><button>Clear Counters</button><p>Total: <span>0</span> from <span>3</span> counters.</p><ul><li><button>-1</button><input type=\"text\"><span>0</span><button>+1</button><button>x</button></li><li><button>-1</button><input type=\"text\"><span>0</span><button>+1</button><button>x</button></li><li><button>-1</button><input type=\"text\"><span>0</span><button>+1</button><button>x</button></li></ul>");
let counters = div
.query_selector("ul")
.unwrap()
.unwrap()
.unchecked_into::<HtmlElement>()
.children();
// click first counter once, second counter twice, etc.
// `NodeList` isn't a `Vec` so we iterate over it in this slightly awkward way
for idx in 0..counters.length() {
let counter = counters.item(idx).unwrap();
let inc_button = counter
.first_child()
.unwrap()
.next_sibling()
.unwrap()
.next_sibling()
.unwrap()
.next_sibling()
.unwrap()
.unchecked_into::<HtmlElement>();
for _ in 0..=idx {
inc_button.click();
}
}
assert_eq!(div.inner_html(), "<button>Add Counter</button><button>Add 1000 Counters</button><button>Clear Counters</button><p>Total: <span>6</span> from <span>3</span> counters.</p><ul><li><button>-1</button><input type=\"text\"><span>1</span><button>+1</button><button>x</button></li><li><button>-1</button><input type=\"text\"><span>2</span><button>+1</button><button>x</button></li><li><button>-1</button><input type=\"text\"><span>3</span><button>+1</button><button>x</button></li></ul>");
// remove the first counter
counters
.item(0)
.unwrap()
.last_child()
.unwrap()
.unchecked_into::<HtmlElement>()
.click();
assert_eq!(div.inner_html(), "<button>Add Counter</button><button>Add 1000 Counters</button><button>Clear Counters</button><p>Total: <span>5</span> from <span>2</span> counters.</p><ul><li><button>-1</button><input type=\"text\"><span>2</span><button>+1</button><button>x</button></li><li><button>-1</button><input type=\"text\"><span>3</span><button>+1</button><button>x</button></li></ul>");
// decrement all by 1
for idx in 0..counters.length() {
let counter = counters.item(idx).unwrap();
let dec_button = counter
.first_child()
.unwrap()
.unchecked_into::<HtmlElement>();
dec_button.click();
}
// we can use RSX in test comparisons!
// note that if RSX template creation is bugged, this probably won't catch it
// (because the same bug will be reproduced in both sides of the assertion)
// so I use HTML tests for most internal testing like this
// but in user-land testing, RSX comparanda are cool
assert_eq!(
div.outer_html(),
view! {
<div>
<button>"Add Counter"</button>
<button>"Add 1000 Counters"</button>
<button>"Clear Counters"</button>
<p>"Total: "<span>"3"</span>" from "<span>"2"</span>" counters."</p>
<ul>
<li>
<button>"-1"</button>
<input type="text"/>
<span>"1"</span>
<button>"+1"</button>
<button>"x"</button>
</li>
<li>
<button>"-1"</button>
<input type="text"/>
<span>"2"</span>
<button>"+1"</button>
<button>"x"</button>
</li>
</ul>
</div>
}
.outer_html()
);
}

View file

@ -0,0 +1,17 @@
[package]
name = "todomvc"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { path = "../../leptos" }
wee_alloc = "0.4"
miniserde = "0.1"
[dev-dependencies]
wasm-bindgen-test = "0.3.0"
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link data-trunk rel="css" href="./node_modules/todomvc-common/base.css">
<link data-trunk rel="css" href="./node_modules/todomvc-app-css/index.css">
<title>Leptos • TodoMVC</title>
<link data-trunk rel="rust" data-wasm-opt="z"/>
</head>
<body></body>
</html>

18
examples/todomvc/node_modules/.package-lock.json generated vendored Normal file
View file

@ -0,0 +1,18 @@
{
"name": "todomvc",
"version": "0.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/todomvc-app-css": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.4.2.tgz",
"integrity": "sha512-ViAkQ7ed89rmhFIGRsT36njN+97z8+s3XsJnB8E2IKOq+/SLD/6PtSvmTtiwUcVk39qPcjAc/OyeDys4LoJUVg=="
},
"node_modules/todomvc-common": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/todomvc-common/-/todomvc-common-1.0.5.tgz",
"integrity": "sha512-D8kEJmxVMQIWwztEdH+WeiAfXRbbSCpgXq4NkYi+gduJ2tr8CNq7sYLfJvjpQ10KD9QxJwig57rvMbV2QAESwQ=="
}
}
}

393
examples/todomvc/node_modules/todomvc-app-css/index.css generated vendored Normal file
View file

@ -0,0 +1,393 @@
@charset "utf-8";
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #111111;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 300;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 400;
color: rgba(0, 0, 0, 0.4);
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 400;
color: rgba(0, 0, 0, 0.4);
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 400;
color: rgba(0, 0, 0, 0.4);
}
.todoapp h1 {
position: absolute;
top: -140px;
width: 100%;
font-size: 80px;
font-weight: 200;
text-align: center;
color: #b83f45;
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.new-todo {
padding: 16px 16px 16px 60px;
height: 65px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
.toggle-all {
width: 1px;
height: 1px;
border: none; /* Mobile Safari */
opacity: 0;
position: absolute;
right: 100%;
bottom: 100%;
}
.toggle-all + label {
display: flex;
align-items: center;
justify-content: center;
width: 45px;
height: 65px;
font-size: 0;
position: absolute;
top: -65px;
left: -0;
}
.toggle-all + label:before {
content: '';
display: inline-block;
font-size: 22px;
color: #949494;
padding: 10px 27px 10px 27px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}
.toggle-all:checked + label:before {
color: #484848;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: calc(100% - 43px);
padding: 12px 16px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle {
opacity: 0;
}
.todo-list li .toggle + label {
/*
Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
*/
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23949494%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
background-repeat: no-repeat;
background-position: center left;
}
.todo-list li .toggle:checked + label {
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%2359A193%22%20stroke-width%3D%223%22%2F%3E%3Cpath%20fill%3D%22%233EA390%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22%2F%3E%3C%2Fsvg%3E');
}
.todo-list li label {
word-break: break-all;
padding: 15px 15px 15px 60px;
display: block;
line-height: 1.2;
transition: color 0.4s;
font-weight: 400;
color: #484848;
}
.todo-list li.completed label {
color: #949494;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #949494;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover,
.todo-list li .destroy:focus {
color: #C18585;
}
.todo-list li .destroy:after {
content: '×';
display: block;
height: 100%;
line-height: 1.1;
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
padding: 10px 15px;
height: 20px;
text-align: center;
font-size: 15px;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a:hover {
border-color: #DB7676;
}
.filters li a.selected {
border-color: #CE4646;
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 19px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #4d4d4d;
font-size: 11px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
:focus,
.toggle:focus + label,
.toggle-all:focus + label {
box-shadow: 0 0 2px 2px #CF7D7D;
outline: 0;
}

397
examples/todomvc/node_modules/todomvc-app-css/license generated vendored Normal file
View file

@ -0,0 +1,397 @@
Creative Commons Attribution 4.0 International (CC-BY-4.0)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View file

@ -0,0 +1,26 @@
{
"name": "todomvc-app-css",
"version": "2.4.2",
"description": "CSS for TodoMVC apps",
"license": "CC-BY-4.0",
"repository": "tastejs/todomvc-app-css",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"files": [
"index.css"
],
"keywords": [
"todomvc",
"tastejs",
"app",
"todo",
"template",
"css",
"style",
"stylesheet"
],
"style": "index.css"
}

View file

@ -0,0 +1,27 @@
# todomvc-app-css
> CSS for TodoMVC apps
![](screenshot.png)
## Install
```
$ npm install todomvc-app-css
```
## Getting started
```html
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
```
See the [TodoMVC app template](https://github.com/tastejs/todomvc-app-template).
## License
CC-BY-4.0 © [Sindre Sorhus](https://sindresorhus.com)

141
examples/todomvc/node_modules/todomvc-common/base.css generated vendored Normal file
View file

@ -0,0 +1,141 @@
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar > .learn {
left: 8px;
}
}

249
examples/todomvc/node_modules/todomvc-common/base.js generated vendored Normal file
View file

@ -0,0 +1,249 @@
/* global _ */
(function () {
'use strict';
/* jshint ignore:start */
// Underscore's Template Module
// Courtesy of underscorejs.org
var _ = (function (_) {
_.defaults = function (object) {
if (!object) {
return object;
}
for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
var iterable = arguments[argsIndex];
if (iterable) {
for (var key in iterable) {
if (object[key] == null) {
object[key] = iterable[key];
}
}
}
}
return object;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
return _;
})({});
if (location.hostname === 'todomvc.com') {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-31081062-1', 'auto');
ga('send', 'pageview');
}
/* jshint ignore:end */
function redirect() {
if (location.hostname === 'tastejs.github.io') {
location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
}
}
function findRoot() {
var base = location.href.indexOf('examples/');
return location.href.substr(0, base);
}
function getFile(file, callback) {
if (!location.host) {
return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.');
}
var xhr = new XMLHttpRequest();
xhr.open('GET', findRoot() + file, true);
xhr.send();
xhr.onload = function () {
if (xhr.status === 200 && callback) {
callback(xhr.responseText);
}
};
}
function Learn(learnJSON, config) {
if (!(this instanceof Learn)) {
return new Learn(learnJSON, config);
}
var template, framework;
if (typeof learnJSON !== 'object') {
try {
learnJSON = JSON.parse(learnJSON);
} catch (e) {
return;
}
}
if (config) {
template = config.template;
framework = config.framework;
}
if (!template && learnJSON.templates) {
template = learnJSON.templates.todomvc;
}
if (!framework && document.querySelector('[data-framework]')) {
framework = document.querySelector('[data-framework]').dataset.framework;
}
this.template = template;
if (learnJSON.backend) {
this.frameworkJSON = learnJSON.backend;
this.frameworkJSON.issueLabel = framework;
this.append({
backend: true
});
} else if (learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework];
this.frameworkJSON.issueLabel = framework;
this.append();
}
this.fetchIssueCount();
}
Learn.prototype.append = function (opts) {
var aside = document.createElement('aside');
aside.innerHTML = _.template(this.template, this.frameworkJSON);
aside.className = 'learn';
if (opts && opts.backend) {
// Remove demo link
var sourceLinks = aside.querySelector('.source-links');
var heading = sourceLinks.firstElementChild;
var sourceLink = sourceLinks.lastElementChild;
// Correct link path
var href = sourceLink.getAttribute('href');
sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http')));
sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML;
} else {
// Localize demo links
var demoLinks = aside.querySelectorAll('.demo-link');
Array.prototype.forEach.call(demoLinks, function (demoLink) {
if (demoLink.getAttribute('href').substr(0, 4) !== 'http') {
demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
}
});
}
document.body.className = (document.body.className + ' learn-bar').trim();
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
};
Learn.prototype.fetchIssueCount = function () {
var issueLink = document.getElementById('issue-count-link');
if (issueLink) {
var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos');
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
var parsedResponse = JSON.parse(e.target.responseText);
if (parsedResponse instanceof Array) {
var count = parsedResponse.length;
if (count !== 0) {
issueLink.innerHTML = 'This app has ' + count + ' open issues';
document.getElementById('issue-count').style.display = 'inline';
}
}
};
xhr.send();
}
};
redirect();
getFile('learn.json', Learn);
})();

9
examples/todomvc/node_modules/todomvc-common/license generated vendored Normal file
View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) TasteJS
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,20 @@
{
"name": "todomvc-common",
"version": "1.0.5",
"description": "Common TodoMVC utilities used by our apps",
"license": "MIT",
"repository": "tastejs/todomvc-common",
"author": "TasteJS",
"main": "base.js",
"style": "base.css",
"files": [
"base.js",
"base.css"
],
"keywords": [
"todomvc",
"tastejs",
"util",
"utilities"
]
}

15
examples/todomvc/node_modules/todomvc-common/readme.md generated vendored Normal file
View file

@ -0,0 +1,15 @@
# todomvc-common
> Common TodoMVC utilities used by our apps
## Install
```
$ npm install todomvc-common
```
## License
MIT © [TasteJS](http://tastejs.com)

39
examples/todomvc/package-lock.json generated Normal file
View file

@ -0,0 +1,39 @@
{
"name": "todomvc",
"version": "0.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "todomvc",
"version": "0.1.0",
"license": "ISC",
"dependencies": {
"todomvc-app-css": "^2.4.2",
"todomvc-common": "^1.0.5"
}
},
"node_modules/todomvc-app-css": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.4.2.tgz",
"integrity": "sha512-ViAkQ7ed89rmhFIGRsT36njN+97z8+s3XsJnB8E2IKOq+/SLD/6PtSvmTtiwUcVk39qPcjAc/OyeDys4LoJUVg=="
},
"node_modules/todomvc-common": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/todomvc-common/-/todomvc-common-1.0.5.tgz",
"integrity": "sha512-D8kEJmxVMQIWwztEdH+WeiAfXRbbSCpgXq4NkYi+gduJ2tr8CNq7sYLfJvjpQ10KD9QxJwig57rvMbV2QAESwQ=="
}
},
"dependencies": {
"todomvc-app-css": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.4.2.tgz",
"integrity": "sha512-ViAkQ7ed89rmhFIGRsT36njN+97z8+s3XsJnB8E2IKOq+/SLD/6PtSvmTtiwUcVk39qPcjAc/OyeDys4LoJUVg=="
},
"todomvc-common": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/todomvc-common/-/todomvc-common-1.0.5.tgz",
"integrity": "sha512-D8kEJmxVMQIWwztEdH+WeiAfXRbbSCpgXq4NkYi+gduJ2tr8CNq7sYLfJvjpQ10KD9QxJwig57rvMbV2QAESwQ=="
}
}
}

View file

@ -0,0 +1,11 @@
{
"name": "todomvc",
"version": "0.1.0",
"description": "TodoMVC implemented in the Leptos framework for Rust",
"author": "Greg Johnston <greg.johnston@gmail.com>",
"license": "ISC",
"dependencies": {
"todomvc-app-css": "^2.4.2",
"todomvc-common": "^1.0.5"
}
}

327
examples/todomvc/src/lib.rs Normal file
View file

@ -0,0 +1,327 @@
use leptos::{web_sys::HtmlInputElement, *};
use miniserde::json;
use storage::TodoSerialized;
mod storage;
#[derive(Clone)]
pub struct Todos {
todos: ReadSignal<Vec<Todo>>,
set_todos: WriteSignal<Vec<Todo>>,
}
const STORAGE_KEY: &str = "todos-leptos";
impl Todos {
pub fn new(cx: Scope) -> Self {
let starting_todos = if let Ok(Some(storage)) = window().local_storage() {
storage
.get_item(STORAGE_KEY)
.ok()
.flatten()
.and_then(|value| json::from_str::<Vec<TodoSerialized>>(&value).ok())
.map(|values| {
values
.into_iter()
.map(|stored| stored.into_todo(cx))
.collect()
})
.unwrap_or_default()
} else {
Vec::new()
};
let (todos, set_todos) = cx.signal_cloned(starting_todos);
Self { todos, set_todos }
}
pub fn is_empty(&self) -> bool {
self.todos.get().is_empty()
}
pub fn add(&self, todo: Todo) {
(self.set_todos)(move |todos| todos.push(todo.clone()));
}
pub fn remove(&self, id: usize) {
(self.set_todos)(|todos| todos.retain(|todo| todo.id != id));
}
pub fn remaining(&self) -> usize {
self.todos
.get()
.iter()
.filter(|todo| !*todo.completed.get())
.count()
}
pub fn completed(&self) -> usize {
self.todos
.get()
.iter()
.filter(|todo| *todo.completed.get())
.count()
}
pub fn toggle_all(&self) {
// if all are complete, mark them all active instead
if self.remaining() == 0 {
for todo in self.todos.get_untracked().iter() {
if todo.is_completed_untracked() {
(todo.set_completed)(|completed| *completed = false);
}
}
}
// otherwise, mark them all complete
else {
for todo in self.todos.get_untracked().iter() {
(todo.set_completed)(|completed| *completed = true);
}
}
}
fn clear_completed(&self) {
(self.set_todos)(|todos| todos.retain(|todo| !todo.is_completed_untracked()));
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct Todo {
pub id: usize,
pub title: ReadSignal<String>,
pub set_title: WriteSignal<String>,
pub completed: ReadSignal<bool>,
pub set_completed: WriteSignal<bool>,
}
impl Todo {
pub fn new(cx: Scope, id: usize, title: String) -> Self {
Self::new_with_completed(cx, id, title, false)
}
pub fn new_with_completed(cx: Scope, id: usize, title: String, completed: bool) -> Self {
let (title, set_title) = cx.signal_cloned(title);
let (completed, set_completed) = cx.signal_cloned(completed);
Self {
id,
title,
set_title,
completed,
set_completed,
}
}
pub fn toggle(&self) {
(self.set_completed)(|completed| *completed = !*completed);
}
pub fn is_completed_untracked(&self) -> bool {
*self.completed.get_untracked()
}
}
const ESCAPE_KEY: u32 = 27;
const ENTER_KEY: u32 = 13;
#[component]
pub fn TodoMVC(cx: Scope) -> Vec<Element> {
let todos = Todos::new(cx);
cx.provide_context(todos.clone());
let todos = cx.create_ref(todos);
let (mode, set_mode) = cx.signal(Mode::All);
window_event_listener("hashchange", move |_| {
let new_mode = location_hash().map(|hash| route(&hash)).unwrap_or_default();
set_mode(|mode| *mode = new_mode);
});
let mut next_id = 0;
let add_todo = move |ev: web_sys::Event| {
let target = event_target::<HtmlInputElement>(&ev);
ev.stop_propagation();
let key_code = ev.unchecked_ref::<web_sys::KeyboardEvent>().key_code();
if key_code == ENTER_KEY {
let title = event_target_value(&ev);
let title = title.trim();
if !title.is_empty() {
todos.add(Todo::new(cx, next_id, title.to_string()));
next_id += 1;
target.set_value("");
}
}
};
let filtered_todos = cx.memo::<Vec<Todo>>(move || {
let todos = todos.todos.get();
match *mode.get() {
Mode::All => todos.iter().cloned().collect(),
Mode::Active => todos
.iter()
.filter(|todo| !*todo.completed.get())
.cloned()
.collect(),
Mode::Completed => todos
.iter()
.filter(|todo| *todo.completed.get())
.cloned()
.collect(),
}
});
// effect to serialize to JSON
// this does reactive reads, so it will automatically serialize on any relevant change
cx.create_effect(move || {
if let Ok(Some(storage)) = window().local_storage() {
let objs = todos
.todos
.get()
.iter()
.map(TodoSerialized::from)
.collect::<Vec<_>>();
let json = json::to_string(&objs);
storage.set_item(STORAGE_KEY, &json);
}
});
view! {
<>
<section class="todoapp">
<header class="header">
<h1>"todos"</h1>
<input class="new-todo" placeholder="What needs to be done?" autofocus on:keydown={add_todo} />
</header>
<section class="main" class:hidden={move || todos.is_empty()}>
<input id="toggle-all" class="toggle-all" type="checkbox"
prop:checked={move || todos.remaining() > 0}
on:input={move |_| todos.toggle_all()}
/>
<label for="toggle-all">"Mark all as complete"</label>
<ul class="todo-list">
<For each={filtered_todos} key={|todo| todo.id}>
{move |cx, todo| view! { <Todo todo={todo.clone()} /> }}
</For>
</ul>
</section>
<footer class="footer" class:hidden={move || todos.is_empty()}>
<span class="todo-count">
<strong>{move || todos.remaining().to_string()}</strong>
{move || if todos.remaining() == 1 {
" item"
} else {
" items"
}}
" left"
</span>
<ul class="filters">
<li><a href="#/" class:selected={move || *mode.get() == Mode::All}>"All"</a></li>
<li><a href="#/active" class:selected={move || *mode.get() == Mode::Active}>"Active"</a></li>
<li><a href="#/completed" class:selected={move || *mode.get() == Mode::Completed}>"Completed"</a></li>
</ul>
<button
class="clear-completed"
class:hidden={move || todos.completed() == 0}
on:click={move |_| todos.clear_completed()}
>
"Clear completed"
</button>
</footer>
</section>
<footer class="info">
<p>"Double-click to edit a todo"</p>
<p>"Created by "<a href="http://todomvc.com">"Greg Johnston"</a></p>
<p>"Part of "<a href="http://todomvc.com">"TodoMVC"</a></p>
</footer>
</>
}
}
#[component]
pub fn Todo(cx: Scope, todo: Todo) -> Element {
// creates a scope-bound reference to the Todo
// this allows us to move the reference into closures below without cloning it
let todo = cx.create_ref(todo);
let (editing, set_editing) = cx.signal(false);
let todos = cx.use_context::<Todos>().unwrap();
let input: web_sys::Element;
let save = move |value: &str| {
let value = value.trim();
if value.is_empty() {
todos.remove(todo.id);
} else {
(todo.set_title)(move |n| *n = value.to_string());
}
set_editing(|n| *n = false);
};
let tpl = view! {
<li
class="todo"
class:editing={move || *editing.get()}
class:completed={move || *todo.completed.get()}
_ref=input
>
<div class="view">
<input
class="toggle"
type="checkbox"
prop:checked={move || *todo.completed.get()}
on:input={move |ev| {
let checked = event_target_checked(&ev);
(todo.set_completed)(|n| *n = checked);
}}
/>
<label on:dblclick={move |_| set_editing(|n| *n = true)}>
{move || todo.title.get().clone()}
</label>
<button class="destroy" on:click={move |_| todos.remove(todo.id)}/>
</div>
{move || (*editing.get()).then(|| view! {
<input
class="edit"
class:hidden={move || !*editing.get()}
prop:value={move || todo.title.get().to_string()}
on:focusout={move |ev| save(&event_target_value(&ev))}
on:keyup={move |ev| {
let key_code = ev.unchecked_ref::<web_sys::KeyboardEvent>().key_code();
if key_code == ENTER_KEY {
save(&event_target_value(&ev));
} else if key_code == ESCAPE_KEY {
set_editing(|n| *n = false);
}
}}
/>
})
}
</li>
};
cx.create_effect(move || {
if *editing.get() {
log!("focusing element");
input.unchecked_ref::<HtmlInputElement>().focus();
}
});
tpl
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Active,
Completed,
All,
}
impl Default for Mode {
fn default() -> Self {
Mode::All
}
}
pub fn route(hash: &str) -> Mode {
match hash {
"/active" => Mode::Active,
"/completed" => Mode::Completed,
_ => Mode::All,
}
}

View file

@ -0,0 +1,9 @@
use leptos::*;
use todomvc::{TodoMVC, TodoMVCProps};
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
fn main() {
mount_to_body(|cx| view! { <TodoMVC/> })
}

View file

@ -0,0 +1,26 @@
use crate::Todo;
use leptos::Scope;
use miniserde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct TodoSerialized {
pub id: usize,
pub title: String,
pub completed: bool,
}
impl TodoSerialized {
pub fn into_todo(self, cx: Scope) -> Todo {
Todo::new_with_completed(cx, self.id, self.title, self.completed)
}
}
impl From<&Todo> for TodoSerialized {
fn from(todo: &Todo) -> Self {
Self {
id: todo.id,
title: todo.title.get().to_string(),
completed: *todo.completed.get(),
}
}
}

10
leptos/Cargo.toml Normal file
View file

@ -0,0 +1,10 @@
[package]
name = "leptos"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos_core = { path = "../leptos_core" }
leptos_dom = { path = "../leptos_dom" }
leptos_macro = { path = "../leptos_macro" }
leptos_reactive = { path = "../leptos_reactive" }

8
leptos/src/lib.rs Normal file
View file

@ -0,0 +1,8 @@
#![feature(stmt_expr_attributes)]
pub use leptos_core::*;
pub use leptos_dom;
pub use leptos_dom::wasm_bindgen::{JsCast, UnwrapThrowExt};
pub use leptos_dom::*;
pub use leptos_macro::*;
pub use leptos_reactive::*;

9
leptos_core/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "leptos_core"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos_dom = { path = "../leptos_dom" }
leptos_macro = { path = "../leptos_macro" }
leptos_reactive = { path = "../leptos_reactive" }

View file

@ -0,0 +1,40 @@
use leptos_dom::Element;
use leptos_macro::*;
use leptos_reactive::{BoundedScope, ReadSignal, Scope};
use std::hash::Hash;
use crate as leptos;
use crate::map::map_keyed;
/// Properties for the [For](crate::For) component.
#[derive(Props)]
pub struct ForProps<'a, T, G, I, K>
where
G: Fn(BoundedScope<'_, 'a>, T) -> Element,
I: Fn(&T) -> K + 'a,
K: Eq + Hash,
T: Eq + Clone + 'static,
{
pub each: &'a ReadSignal<Vec<T>>,
pub key: I,
pub children: G,
}
/// Iterates over children and displays them, keyed by `PartialEq`. If you want to provide your
/// own key function, use [Index] instead.
///
/// This is much more efficient than naively iterating over nodes with `.iter().map(|n| view! { ... })...`,
/// as it avoids re-creating DOM nodes that are not being changed.
#[allow(non_snake_case)]
pub fn For<'a, T, G, I, K>(
cx: Scope<'a>,
props: ForProps<'a, T, G, I, K>,
) -> ReadSignal<Vec<Element>>
where
G: Fn(BoundedScope<'_, 'a>, T) -> Element + 'a,
I: Fn(&T) -> K + 'a,
K: Eq + Hash,
T: Eq + Clone + 'static,
{
map_keyed(cx, props.each, props.children, props.key).clone()
}

13
leptos_core/src/lib.rs Normal file
View file

@ -0,0 +1,13 @@
mod for_component;
mod map;
mod show;
pub use for_component::*;
pub use show::*;
pub trait Prop {
type Builder;
/// The builder should be automatically generated using the `Prop` derive macro.
fn builder() -> Self::Builder;
}

161
leptos_core/src/map.rs Normal file
View file

@ -0,0 +1,161 @@
use leptos_reactive::{BoundedScope, ReadSignal, Scope, ScopeDisposer};
use std::{collections::HashMap, hash::Hash};
/// Function that maps a `Vec` to another `Vec` via a map function. The mapped `Vec` is lazy
/// computed; its value will only be updated when requested. Modifications to the
/// input `Vec` are diffed using keys to prevent recomputing values that have not changed.
///
/// This function is the underlying utility behind `Keyed`.
///
/// # Params
/// * `list` - The list to be mapped. The list must be a [`ReadSignal`] (obtained from a [`Signal`])
/// and therefore reactive.
/// * `map_fn` - A closure that maps from the input type to the output type.
/// * `key_fn` - A closure that returns an _unique_ key to each entry.
///
/// _Credits: Based on implementation for [Sycamore](https://github.com/sycamore-rs/sycamore/blob/53735aab9ef72b98439b4d2eaeb85a97f7f32775/packages/sycamore-reactive/src/iter.rs),
/// which is in turned based on on the TypeScript implementation in <https://github.com/solidjs/solid>_
pub fn map_keyed<'a, T, U, K>(
cx: Scope<'a>,
list: &'a ReadSignal<Vec<T>>,
map_fn: impl for<'child_lifetime> Fn(BoundedScope<'child_lifetime, 'a>, T) -> U + 'a,
key_fn: impl Fn(&T) -> K + 'a,
) -> &'a ReadSignal<Vec<U>>
where
T: PartialEq + Clone + 'a,
K: Eq + Hash,
U: Clone,
{
// Previous state used for diffing.
let mut items = Vec::new();
let mut mapped: Vec<U> = Vec::new();
let mut disposers: Vec<Option<ScopeDisposer<'a>>> = Vec::new();
let (item_signal, set_item_signal) = cx.signal(Vec::new());
// Diff and update signal each time list is updated.
cx.create_effect(move || {
let new_items = list.get();
if new_items.is_empty() {
// Fast path for removing all items.
for disposer in std::mem::take(&mut disposers) {
unsafe {
disposer.unwrap().dispose();
}
}
mapped = Vec::new();
} else if items.is_empty() {
// Fast path for creating items when the existing list is empty.
for new_item in new_items.iter() {
let mut value = None;
let new_disposer = cx.child_scope(|cx| {
// SAFETY: f takes the same parameter as the argument to create_child_scope.
value = Some(map_fn(
unsafe { std::mem::transmute(cx) },
(*new_item).clone(),
));
});
mapped.push(value.unwrap());
disposers.push(Some(new_disposer));
}
} else {
let mut temp = vec![None; new_items.len()];
let mut temp_disposers: Vec<Option<ScopeDisposer<'a>>> =
(0..new_items.len()).map(|_| None).collect();
// Skip common prefix.
let min_len = usize::min(items.len(), new_items.len());
let start = items
.iter()
.zip(new_items.iter())
.position(|(a, b)| a != b)
.unwrap_or(min_len);
// Skip common suffix.
let mut end = items.len();
let mut new_end = new_items.len();
#[allow(clippy::suspicious_operation_groupings)]
// FIXME: make code clearer so that clippy won't complain
while end > start && new_end > start && items[end - 1] == new_items[new_end - 1] {
end -= 1;
new_end -= 1;
temp[new_end] = Some(mapped[end].clone());
temp_disposers[new_end] = disposers[end].take();
}
// 0) Prepare a map of indices in newItems. Scan backwards so we encounter them in
// natural order.
let mut new_indices = HashMap::with_capacity(new_end - start);
// Indexes for new_indices_next are shifted by start because values at 0..start are
// always None.
let mut new_indices_next = vec![None; new_end - start];
for j in (start..new_end).rev() {
let item = &new_items[j];
let i = new_indices.get(&key_fn(item));
new_indices_next[j - start] = i.copied();
new_indices.insert(key_fn(item), j);
}
// 1) Step through old items and see if they can be found in new set; if so, mark
// them as moved.
for i in start..end {
let item = &items[i];
if let Some(j) = new_indices.get(&key_fn(item)).copied() {
// Moved. j is index of item in new_items.
temp[j] = Some(mapped[i].clone());
temp_disposers[j] = disposers[i].take();
new_indices_next[j - start].and_then(|j| new_indices.insert(key_fn(item), j));
} else {
// Create new.
unsafe {
disposers[i].take().unwrap().dispose();
}
}
}
// 2) Set all the new values, pulling from the moved array if copied, otherwise
// entering the new value.
for j in start..new_items.len() {
if matches!(temp.get(j), Some(Some(_))) {
// Pull from moved array.
if j >= mapped.len() {
debug_assert_eq!(mapped.len(), j);
mapped.push(temp[j].clone().unwrap());
disposers.push(temp_disposers[j].take());
} else {
mapped[j] = temp[j].clone().unwrap();
disposers[j] = temp_disposers[j].take();
}
} else {
// Create new value.
let mut tmp = None;
let new_item = new_items[j].clone();
let new_disposer = cx.child_scope(|cx| {
// SAFETY: f takes the same parameter as the argument to create_child_scope.
tmp = Some(map_fn(unsafe { std::mem::transmute(cx) }, new_item.clone()));
});
if mapped.len() > j {
mapped[j] = tmp.unwrap();
disposers[j] = Some(new_disposer);
} else {
mapped.push(tmp.unwrap());
disposers.push(Some(new_disposer));
}
}
}
}
// 3) In case the new set is shorter than the old, set the length of the mapped array.
mapped.truncate(new_items.len());
disposers.truncate(new_items.len());
// 4) Save a copy of the mapped items for the next update.
items = new_items.to_vec();
// 5) Update signal to trigger updates.
set_item_signal(|n| *n = mapped.clone());
});
item_signal
}

31
leptos_core/src/show.rs Normal file
View file

@ -0,0 +1,31 @@
use std::marker::PhantomData;
use crate as leptos;
use leptos_dom::{Child, Element, IntoChild};
use leptos_macro::*;
use leptos_reactive::{ReadSignal, Scope};
#[derive(Props)]
pub struct ShowProps<W, C>
where
W: Fn() -> bool,
C: for<'a> IntoChild<'a>,
{
when: W,
children: C,
}
#[allow(non_snake_case)]
pub fn Show<'a, W, C>(cx: Scope<'a>, props: ShowProps<W, C>) -> impl Fn() -> Child<'a>
where
W: Fn() -> bool,
C: for<'c> IntoChild<'c> + Clone,
{
move || {
if (props.when)() {
props.children.clone().into_child(cx)
} else {
Child::Null
}
}
}

53
leptos_dom/Cargo.toml Normal file
View file

@ -0,0 +1,53 @@
[package]
name = "leptos_dom"
version = "0.1.0"
edition = "2021"
[dependencies]
js-sys = "0.3"
leptos_reactive = { path = "../leptos_reactive" }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4.31"
wee_alloc = "0.4.5"
[dependencies.web-sys]
version = "0.3"
features = [
"Attr",
"console",
"Comment",
"CssStyleDeclaration",
"CustomEvent",
"CustomEventInit",
"Document",
"DocumentFragment",
"DomStringMap",
"DomTokenList",
"Element",
"Event",
"EventTarget",
"HtmlCollection",
"HtmlDivElement",
"HtmlElement",
"HtmlInputElement",
"HtmlTemplateElement",
"KeyboardEvent",
"Location",
"MutationObserver",
"NamedNodeMap",
"Node",
"NodeList",
"Performance",
"ShadowRoot",
"ShadowRootInit",
"ShadowRootMode",
"Storage",
"Text",
"TreeWalker",
"Window"
]
[profile.release]
codegen-units = 1
lto = true
opt-level = 'z'

View file

@ -0,0 +1,75 @@
use leptos_reactive::Scope;
pub enum Attribute<'a> {
String(String),
Fn(&'a dyn Fn() -> Attribute<'a>),
Option(Option<String>),
Bool(bool),
}
pub trait IntoAttribute<'a> {
fn into_attribute(self, cx: Scope<'a>) -> Attribute<'a>;
}
impl<'a> IntoAttribute<'a> for String {
fn into_attribute(self, _cx: Scope<'a>) -> Attribute<'a> {
Attribute::String(self)
}
}
impl<'a> IntoAttribute<'a> for bool {
fn into_attribute(self, _cx: Scope<'a>) -> Attribute<'a> {
Attribute::Bool(self)
}
}
impl<'a> IntoAttribute<'a> for Option<String> {
fn into_attribute(self, _cx: Scope<'a>) -> Attribute<'a> {
Attribute::Option(self)
}
}
impl<'a, T, U> IntoAttribute<'a> for T
where
T: Fn() -> U + 'a,
U: IntoAttribute<'a>,
{
fn into_attribute(self, cx: Scope<'a>) -> Attribute<'a> {
let modified_fn = cx.create_ref(move || (self)().into_attribute(cx));
Attribute::Fn(modified_fn)
}
}
macro_rules! attr_type {
($attr_type:ty) => {
impl<'a> IntoAttribute<'a> for $attr_type {
fn into_attribute(self, _cx: Scope<'a>) -> Attribute<'a> {
Attribute::String(self.to_string())
}
}
impl<'a> IntoAttribute<'a> for Option<$attr_type> {
fn into_attribute(self, _cx: Scope<'a>) -> Attribute<'a> {
Attribute::Option(self.map(|n| n.to_string()))
}
}
};
}
attr_type!(&String);
attr_type!(&str);
attr_type!(usize);
attr_type!(u8);
attr_type!(u16);
attr_type!(u32);
attr_type!(u64);
attr_type!(u128);
attr_type!(isize);
attr_type!(i8);
attr_type!(i16);
attr_type!(i32);
attr_type!(i64);
attr_type!(i128);
attr_type!(f32);
attr_type!(f64);
attr_type!(char);

149
leptos_dom/src/child.rs Normal file
View file

@ -0,0 +1,149 @@
use leptos_reactive::{ReadSignal, Scope};
use wasm_bindgen::JsCast;
type Node = web_sys::Node;
#[derive(Clone)]
pub enum Child<'a> {
Null,
Text(String),
Fn(&'a dyn Fn() -> Child<'a>),
Node(Node),
Nodes(Vec<Node>),
}
impl<'a> std::fmt::Debug for Child<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Null => write!(f, "Null"),
Self::Text(arg0) => f.debug_tuple("Text").field(arg0).finish(),
Self::Fn(_) => f.debug_tuple("Fn").finish(),
Self::Node(arg0) => f.debug_tuple("Node").field(arg0).finish(),
Self::Nodes(arg0) => f.debug_tuple("Nodes").field(arg0).finish(),
}
}
}
impl<'a> PartialEq for Child<'a> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Text(l0), Self::Text(r0)) => l0 == r0,
(Self::Fn(l0), Self::Fn(r0)) => std::ptr::eq(l0, r0),
(Self::Node(l0), Self::Node(r0)) => l0 == r0,
(Self::Nodes(l0), Self::Nodes(r0)) => l0 == r0,
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
pub trait IntoChild<'a> {
fn into_child(self, cx: Scope<'a>) -> Child<'a>;
}
impl<'a> IntoChild<'a> for Child<'a> {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
self
}
}
impl<'a> IntoChild<'a> for String {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Text(self)
}
}
impl<'a> IntoChild<'a> for web_sys::Node {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Node(self)
}
}
impl<'a> IntoChild<'a> for web_sys::Text {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Node(self.unchecked_into())
}
}
impl<'a> IntoChild<'a> for web_sys::Element {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Node(self.unchecked_into())
}
}
impl<'a, T> IntoChild<'a> for Option<T>
where
T: IntoChild<'a>,
{
fn into_child(self, cx: Scope<'a>) -> Child<'a> {
match self {
Some(val) => val.into_child(cx),
None => Child::Null,
}
}
}
impl<'a> IntoChild<'a> for Vec<web_sys::Node> {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Nodes(self)
}
}
impl<'a> IntoChild<'a> for Vec<web_sys::Element> {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Nodes(
self.into_iter()
.map(|el| el.unchecked_into::<web_sys::Node>())
.collect(),
)
}
}
impl<'a, T> IntoChild<'a> for ReadSignal<T>
where
T: Clone + IntoChild<'a>,
{
fn into_child(self, cx: Scope<'a>) -> Child<'a> {
let modified_fn = cx.create_ref(move || self.get().clone().into_child(cx));
Child::Fn(modified_fn)
}
}
impl<'a, T, U> IntoChild<'a> for T
where
T: Fn() -> U + 'a,
U: IntoChild<'a>,
{
fn into_child(self, cx: Scope<'a>) -> Child<'a> {
let modified_fn = cx.create_ref(move || (self)().into_child(cx));
Child::Fn(modified_fn)
}
}
macro_rules! child_type {
($child_type:ty) => {
impl<'a> IntoChild<'a> for $child_type {
fn into_child(self, _cx: Scope<'a>) -> Child<'a> {
Child::Text(self.to_string())
}
}
};
}
child_type!(&String);
child_type!(&str);
child_type!(usize);
child_type!(u8);
child_type!(u16);
child_type!(u32);
child_type!(u64);
child_type!(u128);
child_type!(isize);
child_type!(i8);
child_type!(i16);
child_type!(i32);
child_type!(i64);
child_type!(i128);
child_type!(f32);
child_type!(f64);
child_type!(char);
child_type!(bool);

26
leptos_dom/src/class.rs Normal file
View file

@ -0,0 +1,26 @@
use leptos_reactive::Scope;
pub enum Class<'a> {
Value(bool),
Fn(&'a dyn Fn() -> bool),
}
pub trait IntoClass<'a> {
fn into_class(self, cx: Scope<'a>) -> Class<'a>;
}
impl<'a> IntoClass<'a> for bool {
fn into_class(self, _cx: Scope<'a>) -> Class<'a> {
Class::Value(self)
}
}
impl<'a, T> IntoClass<'a> for T
where
T: Fn() -> bool + 'a,
{
fn into_class(self, cx: Scope<'a>) -> Class<'a> {
let modified_fn = cx.create_ref(self);
Class::Fn(modified_fn)
}
}

View file

@ -0,0 +1 @@
pub trait Prop {}

View file

@ -0,0 +1,79 @@
use std::cell::RefCell;
use std::collections::HashSet;
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use crate::window_event_listener;
thread_local! {
pub static GLOBAL_EVENTS: RefCell<HashSet<&'static str>> = RefCell::new(HashSet::new());
}
// cf eventHandler in ryansolid/dom-expressions
pub(crate) fn add_event_listener(event_name: &'static str) {
GLOBAL_EVENTS.with(|global_events| {
let mut events = global_events.borrow_mut();
if !events.contains(event_name) {
// create global handler
let key = JsValue::from_str(&event_delegation_key(event_name));
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_throw()
.is_truthy();
if !node_is_disabled {
let maybe_handler = js_sys::Reflect::get(&node, &key).unwrap_throw();
if !maybe_handler.is_undefined() {
let f = maybe_handler.unchecked_ref::<js_sys::Function>();
if let Err(e) = f.call1(&node, &ev) {
crate::debug_warn!("{e:#?}");
}
if ev.cancel_bubble() {
return;
}
}
}
// navigate up tree
let host =
js_sys::Reflect::get(&node, &JsValue::from_str("host")).unwrap_throw();
if host.is_truthy() && host != node && host.dyn_ref::<web_sys::Node>().is_some()
{
node = host;
} else if let Some(parent) =
node.unchecked_into::<web_sys::Node>().parent_node()
{
node = parent.into()
} else {
node = JsValue::null()
}
}
};
window_event_listener(event_name, handler);
// register that we've created handler
events.insert(event_name);
}
})
}
pub(crate) fn event_delegation_key(event_name: &'static str) -> String {
let mut n = String::from("$$$");
n.push_str(event_name);
n
}

89
leptos_dom/src/lib.rs Normal file
View file

@ -0,0 +1,89 @@
mod attribute;
mod child;
mod class;
mod event_delegation;
pub mod logging;
mod operations;
mod property;
mod reconcile;
mod render;
pub use attribute::*;
pub use child::*;
pub use class::*;
pub use logging::*;
pub use operations::*;
pub use property::*;
pub use render::*;
pub use js_sys;
pub use wasm_bindgen;
pub use web_sys;
pub type Element = web_sys::Element;
use leptos_reactive::{create_scope, RootContext, Scope};
pub use wasm_bindgen::UnwrapThrowExt;
pub trait Mountable {
fn mount(&self, parent: &web_sys::Element);
}
impl Mountable for Element {
fn mount(&self, parent: &web_sys::Element) {
parent.append_child(&self).unwrap_throw();
}
}
impl Mountable for Vec<Element> {
fn mount(&self, parent: &web_sys::Element) {
for element in self {
parent.append_child(&element).unwrap_throw();
}
}
}
pub fn mount_to_body<T, F>(f: F)
where
F: Fn(Scope) -> T,
T: Mountable,
{
mount(&document().body().unwrap_throw(), f)
}
pub fn mount<T, F>(parent: &web_sys::Element, f: F)
where
F: Fn(Scope) -> T,
T: Mountable,
{
let stack = Box::leak(Box::new(RootContext::new()));
// running "mount" intentionally leaks the memory,
// as the "mount" has no parent that can clean it up
let _ = create_scope(stack, |cx| {
(f(cx)).mount(parent);
});
}
pub fn create_component<'a, F, T>(cx: Scope<'a>, f: F) -> T
where
F: Fn() -> T,
T: IntoChild<'a>,
{
// TODO hydration logic here
cx.untrack(f)
}
#[macro_export]
macro_rules! is_server {
() => {
!cfg!(target_arch = "wasm32")
};
}
#[macro_export]
macro_rules! is_dev {
() => {
cfg!(debug_assertions)
};
}

70
leptos_dom/src/logging.rs Normal file
View file

@ -0,0 +1,70 @@
use wasm_bindgen::JsValue;
use crate::is_server;
#[macro_export]
macro_rules! log {
($($t:tt)*) => ($crate::console_log(&format_args!($($t)*).to_string()))
}
#[macro_export]
macro_rules! warn {
($($t:tt)*) => ($crate::console_warn(&format_args!($($t)*).to_string()))
}
#[macro_export]
macro_rules! error {
($($t:tt)*) => ($crate::console_error(&format_args!($($t)*).to_string()))
}
#[macro_export]
macro_rules! debug_warn {
($($x:tt)*) => {
{
#[cfg(debug_assertions)]
{
$crate::warn!($($x)*)
}
#[cfg(not(debug_assertions))]
{
($($x)*)
}
}
}
}
pub fn console_log(s: &str) {
if is_server!() {
println!("{}", s);
} else {
web_sys::console::log_1(&JsValue::from_str(s));
}
}
pub fn console_warn(s: &str) {
if is_server!() {
eprintln!("{}", s);
} else {
web_sys::console::warn_1(&JsValue::from_str(s));
}
}
pub fn console_error(s: &str) {
if is_server!() {
eprintln!("{}", s);
} else {
web_sys::console::warn_1(&JsValue::from_str(s));
}
}
#[cfg(debug_assertions)]
pub fn console_debug_warn(s: &str) {
if is_server!() {
eprintln!("{}", s);
} else {
web_sys::console::warn_1(&JsValue::from_str(s));
}
}
#[cfg(not(debug_assertions))]
pub fn console_debug_warn(s: &str) {}

View file

@ -0,0 +1,317 @@
use std::time::Duration;
use std::future::Future;
use wasm_bindgen::{prelude::Closure, JsCast, JsValue, UnwrapThrowExt};
use crate::{event_delegation, is_server};
thread_local! {
pub static WINDOW: web_sys::Window = web_sys::window().unwrap_throw();
pub static DOCUMENT: web_sys::Document = web_sys::window().unwrap_throw().document().unwrap_throw();
}
pub fn window() -> web_sys::Window {
WINDOW.with(|window| window.clone())
}
pub fn document() -> web_sys::Document {
DOCUMENT.with(|document| document.clone())
}
pub fn body() -> Option<web_sys::HtmlElement> {
document().body()
}
pub fn create_element(tag_name: &str) -> web_sys::Element {
document().create_element(tag_name).unwrap_throw()
}
pub fn create_text_node(data: &str) -> web_sys::Text {
document().create_text_node(data)
}
pub fn create_fragment() -> web_sys::DocumentFragment {
document().create_document_fragment()
}
pub fn create_comment_node() -> web_sys::Node {
document().create_comment("").unchecked_into()
}
pub fn create_template(html: &str) -> web_sys::HtmlTemplateElement {
let template = create_element("template");
template.set_inner_html(html);
template.unchecked_into()
}
pub fn clone_template(template: &web_sys::HtmlTemplateElement) -> web_sys::DocumentFragment {
template
.content()
.clone_node_with_deep(true)
.unwrap_throw()
.unchecked_into()
}
pub fn append_child(parent: &web_sys::Element, child: &web_sys::Node) -> web_sys::Node {
parent.append_child(child).unwrap_throw()
}
pub fn remove_child(parent: &web_sys::Element, child: &web_sys::Node) {
parent.remove_child(child).unwrap_throw();
}
pub fn replace_child(parent: &web_sys::Element, new: &web_sys::Node, old: &web_sys::Node) {
parent.replace_child(new, old).unwrap_throw();
}
pub fn insert_before(
parent: &web_sys::Element,
new: &web_sys::Node,
existing: Option<&web_sys::Node>,
) -> web_sys::Node {
parent.insert_before(new, existing).unwrap_throw()
}
pub fn replace_with(old_node: &web_sys::Element, new_node: &web_sys::Node) {
old_node.replace_with_with_node_1(new_node).unwrap_throw()
}
pub fn set_data(node: &web_sys::Text, value: &str) {
node.set_data(value);
}
pub fn set_attribute(el: &web_sys::Element, attr_name: &str, value: &str) {
el.set_attribute(attr_name, value).unwrap_throw()
}
pub fn remove_attribute(el: &web_sys::Element, attr_name: &str) {
el.remove_attribute(attr_name).unwrap_throw()
}
pub fn set_property(el: &web_sys::Element, prop_name: &str, value: &Option<JsValue>) {
let key = JsValue::from_str(prop_name);
match value {
Some(value) => js_sys::Reflect::set(el, &key, value).unwrap_throw(),
None => js_sys::Reflect::delete_property(el, &key).unwrap_throw(),
};
}
pub fn location() -> web_sys::Location {
window().location()
}
pub fn descendants(el: &web_sys::Element) -> impl Iterator<Item = web_sys::Node> {
let children = el.child_nodes();
(0..children.length()).flat_map({
move |idx| {
let child = children.get(idx);
if let Some(child) = child {
// if an Element, send children
if child.node_type() == 1 {
Box::new(descendants(&child.unchecked_into()))
as Box<dyn Iterator<Item = web_sys::Node>>
}
// otherwise, just the node
else {
Box::new(std::iter::once(child)) as Box<dyn Iterator<Item = web_sys::Node>>
}
} else {
Box::new(std::iter::empty()) as Box<dyn Iterator<Item = web_sys::Node>>
}
}
})
}
/// Current window.location.hash without the beginning #
pub fn location_hash() -> Option<String> {
if is_server!() {
None
} else {
location().hash().ok().map(|hash| hash.replace('#', ""))
}
}
pub fn location_pathname() -> Option<String> {
location().pathname().ok()
}
pub fn event_target<T>(event: &web_sys::Event) -> T
where
T: JsCast,
{
event.target().unwrap_throw().unchecked_into::<T>()
}
pub fn event_target_value(event: &web_sys::Event) -> String {
event
.target()
.unwrap_throw()
.unchecked_into::<web_sys::HtmlInputElement>()
.value()
}
pub fn event_target_checked(ev: &web_sys::Event) -> bool {
ev.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>()
.checked()
}
pub fn event_target_selector(ev: &web_sys::Event, selector: &str) -> bool {
matches!(
ev.target().and_then(|target| {
target
.dyn_ref::<web_sys::Element>()
.map(|el| el.closest(selector))
}),
Some(Ok(Some(_)))
)
}
pub fn request_animation_frame(cb: impl Fn() + 'static) {
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
window()
.request_animation_frame(cb.as_ref().unchecked_ref())
.unwrap_throw();
}
pub fn request_idle_callback(cb: impl Fn() + 'static) {
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
window()
.request_idle_callback(cb.as_ref().unchecked_ref())
.unwrap_throw();
}
pub fn set_timeout(cb: impl Fn() + 'static, duration: Duration) {
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
window()
.set_timeout_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.unwrap_throw();
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct IntervalHandle(i32);
impl IntervalHandle {
pub fn clear(&self) {
window().clear_interval_with_handle(self.0);
}
}
pub fn set_interval(
cb: impl Fn() + 'static,
duration: Duration,
) -> Result<IntervalHandle, JsValue> {
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
let handle = window().set_interval_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)?;
Ok(IntervalHandle(handle))
}
pub fn add_event_listener(
target: &web_sys::Element,
event_name: &'static str,
cb: impl FnMut(web_sys::Event),
) {
let boxed: Box<dyn FnMut(web_sys::Event)> = Box::new(cb);
// Safety: components should only be mounted by calling dom::mount or dom::mount_to_body,
// which create and leak a new Scope. Components can be written with lifetimes (which allows)
// the use of non-'static Scopes on, e.g., the server; but event listeners will never be called
// in that situation. As a result, all Signals and Effects running in the browser actually have
// a static lifetime, so the handler can be upgraded to a static lifetime.
let handler: Box<dyn FnMut(web_sys::Event) + 'static> = unsafe { std::mem::transmute(boxed) };
let cb = Closure::wrap(handler).into_js_value();
// delegate events
let key = event_delegation::event_delegation_key(event_name);
js_sys::Reflect::set(target, &JsValue::from_str(&key), &cb).unwrap_throw();
event_delegation::add_event_listener(event_name);
// below: non-delegated
/* target
.add_event_listener_with_callback(event_name, cb.unchecked_ref())
.unwrap_throw(); */
}
pub fn window_event_listener(event_name: &str, cb: impl Fn(web_sys::Event)) {
let boxed: Box<dyn FnMut(web_sys::Event)> = Box::new(cb);
// Safety: see add_event_listener above
let handler: Box<dyn FnMut(web_sys::Event) + 'static> = unsafe { std::mem::transmute(boxed) };
let cb = Closure::wrap(handler).into_js_value();
window()
.add_event_listener_with_callback(event_name, cb.unchecked_ref())
.unwrap_throw();
}
// Hydration operations to find text and comment nodes
pub fn pick_up_comment_node(
parent: &web_sys::HtmlElement,
node_idx: usize,
) -> Option<web_sys::Node> {
let mut node_identifier = String::from("hk");
node_identifier.push_str(&node_idx.to_string());
let walker = document()
.create_tree_walker_with_what_to_show(parent, 128) // = NodeFilter.SHOW_COMMENT
.unwrap_throw();
while let Some(node) = walker.next_node().unwrap_throw() {
if let Some(value) = node.node_value() {
if value == node_identifier {
return Some(node);
}
}
}
None
}
pub fn pick_up_text_node(parent: &web_sys::HtmlElement, node_idx: usize) -> Option<web_sys::Text> {
let mut node_identifier = String::from("hk");
node_identifier.push_str(&node_idx.to_string());
let walker = document()
.create_tree_walker(parent) //_with_what_to_show(&node, 128) // = NodeFilter.SHOW_COMMENT
.unwrap_throw();
while let Some(node) = walker.next_node().unwrap_throw() {
let next_value = node.node_value();
if next_value.is_some() && next_value.unwrap_throw() == node_identifier {
let next_node = walker.next_node().unwrap_throw();
if let Some(node) = next_node {
// if it's Node.TEXT_NODE
if node.node_type() == 3 {
return Some(node.unchecked_into());
}
}
}
}
None
}
#[cfg(target_arch = "wasm32")]
pub fn spawn_local<F>(fut: F)
where
F: Future<Output = ()> + 'static,
{
wasm_bindgen_futures::spawn_local(fut)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn spawn_local<F>(_fut: F)
where
F: Future<Output = ()> + 'static,
{
// noop for now; useful for ignoring any async tasks on the server side
// could be replaced with a Tokio dependency
}
pub fn remove_event_listeners(el: &web_sys::Element) {
let clone = el.clone_node().unwrap_throw();
replace_with(el, clone.unchecked_ref());
}

View file

@ -0,0 +1,57 @@
use leptos_reactive::Scope;
use wasm_bindgen::JsValue;
pub enum Property<'a> {
Value(JsValue),
Fn(&'a dyn Fn() -> JsValue),
}
pub trait IntoProperty<'a> {
fn into_property(self, cx: Scope<'a>) -> Property<'a>;
}
impl<'a, T, U> IntoProperty<'a> for T
where
T: Fn() -> U + 'a,
U: Into<JsValue>,
{
fn into_property(self, cx: Scope<'a>) -> Property<'a> {
let modified_fn = cx.create_ref(move || self().into());
Property::Fn(modified_fn)
}
}
macro_rules! prop_type {
($prop_type:ty) => {
impl<'a> IntoProperty<'a> for $prop_type {
fn into_property(self, _cx: Scope<'a>) -> Property<'a> {
Property::Value(self.into())
}
}
impl<'a> IntoProperty<'a> for Option<$prop_type> {
fn into_property(self, _cx: Scope<'a>) -> Property<'a> {
Property::Value(self.into())
}
}
};
}
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);

150
leptos_dom/src/reconcile.rs Normal file
View file

@ -0,0 +1,150 @@
use std::collections::HashMap;
use crate::insert_before;
struct NodeWrapper<'a>(&'a web_sys::Node);
impl<'a> std::hash::Hash for NodeWrapper<'a> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(self.0, state)
}
}
impl<'a> PartialEq for NodeWrapper<'a> {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(&self.0, &other.0)
}
}
impl<'a> Eq for NodeWrapper<'a> {}
pub fn reconcile_arrays(parent: &web_sys::Element, a: &mut [web_sys::Node], b: &[web_sys::Node]) {
debug_assert!(!a.is_empty(), "a cannot be empty");
// Sanity check: make sure all nodes in a are children of parent.
#[cfg(debug_assertions)]
{
for (i, node) in a.iter().enumerate() {
if node.parent_node().as_ref() != Some(parent) {
panic!(
"node {} in existing nodes Vec is not a child of parent. node = {:#?}",
i, node
);
}
}
}
let b_len = b.len();
let mut a_end = a.len();
let mut b_end = b_len;
let mut a_start = 0;
let mut b_start = 0;
let mut map = None::<HashMap<NodeWrapper, usize>>;
// Last node in a.
let after = a[a_end - 1].next_sibling();
while a_start < a_end || b_start < b_end {
if a_end == a_start {
// Append.
let node = if b_end < b_len {
if b_start != 0 {
b[b_start - 1].next_sibling()
} else {
Some(b[b_end - b_start].clone())
}
} else {
after.clone()
};
for new_node in &b[b_start..b_end] {
insert_before(parent, new_node, node.as_ref());
}
b_start = b_end;
} else if b_end == b_start {
// Remove.
for node in &a[a_start..a_end] {
if map.is_none() || !map.as_ref().unwrap().contains_key(&NodeWrapper(&node)) {
parent.remove_child(node);
}
}
a_start = a_end;
} else if a[a_start] == b[b_start] {
// Common prefix.
a_start += 1;
b_start += 1;
} else if a[a_end - 1] == b[b_end - 1] {
// Common suffix.
a_end -= 1;
b_end -= 1;
} else if a[a_start] == b[b_end - 1] && b[b_start] == a[a_end - 1] {
// Swap backwards.
let node = a[a_end - 1].next_sibling();
parent.insert_before(&b[b_start], a[a_start].next_sibling().as_ref());
parent.insert_before(&b[b_end - 1], node.as_ref());
a_start += 1;
b_start += 1;
a_end -= 1;
b_end -= 1;
a[a_end] = b[b_end].clone();
} else {
// Fallback to map.
if map.is_none() {
let tmp = b[b_start..b_end]
.iter()
.enumerate()
.map(|(i, g)| (NodeWrapper(&g), i))
.collect();
map = Some(tmp);
}
let map = map.as_ref().unwrap();
if let Some(&index) = map.get(&NodeWrapper(&a[a_start])) {
if b_start < index && index < b_end {
let mut i = a_start;
let mut sequence = 1;
let mut t;
while i + 1 < a_end && i + 1 < b_end {
i += 1;
t = map.get(&NodeWrapper(&a[i])).copied();
if t != Some(index + sequence) {
break;
}
sequence += 1;
}
if sequence > index - b_start {
let node = &a[a_start];
while b_start < index {
parent.insert_before(&b[b_start], Some(node));
b_start += 1;
}
} else {
parent.replace_child(&a[a_start], &b[b_start]);
a_start += 1;
b_start += 1;
}
} else {
a_start += 1;
}
} else {
parent.remove_child(&a[a_start]);
a_start += 1;
}
}
}
// Sanity check: make sure all nodes in b are children of parent after reconciliation.
#[cfg(debug_assertions)]
{
for (i, node) in b.iter().enumerate() {
if node.parent_node().as_ref() != Some(parent) {
panic!(
"node {} in new nodes Vec is not a child of parent after reconciliation. node = {:#?}",
i, node
);
}
}
}
}

352
leptos_dom/src/render.rs Normal file
View file

@ -0,0 +1,352 @@
use leptos_reactive::Scope;
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use crate::{
append_child, create_text_node, debug_warn, insert_before, reconcile::reconcile_arrays,
remove_attribute, remove_child, replace_child, replace_with, set_attribute, Attribute, Child,
Class, Property,
};
pub fn attribute<'a>(
cx: Scope<'a>,
el: &web_sys::Element,
attr_name: &'static str,
value: Attribute<'a>,
) {
match value {
Attribute::Fn(f) => {
let el = el.clone();
cx.create_effect(move || attribute_expression(&el, attr_name, f()))
}
_ => attribute_expression(el, attr_name, value),
}
}
fn attribute_expression<'a>(el: &web_sys::Element, attr_name: &str, value: Attribute<'a>) {
match value {
Attribute::String(value) => set_attribute(el, attr_name, &value),
Attribute::Option(value) => match value {
Some(value) => set_attribute(el, attr_name, &value),
None => remove_attribute(el, attr_name),
},
Attribute::Bool(_) => todo!(),
_ => panic!("Remove nested Fn in Attribute"),
}
}
pub fn property<'a>(
cx: Scope<'a>,
el: &web_sys::Element,
prop_name: &'static str,
value: Property<'a>,
) {
match value {
Property::Fn(f) => {
let el = el.clone();
cx.create_effect(move || property_expression(&el, prop_name, f()))
}
Property::Value(value) => property_expression(el, prop_name, value),
}
}
fn property_expression(el: &web_sys::Element, prop_name: &str, value: JsValue) {
js_sys::Reflect::set(el, &JsValue::from_str(prop_name), &value).unwrap_throw();
}
pub fn class<'a>(cx: Scope<'a>, el: &web_sys::Element, class_name: &'static str, value: Class<'a>) {
match value {
Class::Fn(f) => {
let el = el.clone();
cx.create_effect(move || class_expression(&el, class_name, f()))
}
Class::Value(value) => class_expression(el, class_name, value),
}
}
fn class_expression(el: &web_sys::Element, class_name: &str, value: bool) {
let class_list = el.class_list();
if value {
class_list.add_1(class_name).unwrap_throw();
} else {
class_list.remove_1(class_name).unwrap_throw();
}
}
pub fn insert<'a>(
cx: Scope,
parent: web_sys::Node,
value: Child<'a>,
before: Option<web_sys::Node>,
initial: Option<Child<'a>>,
) {
/* let initial = if before.is_some() && initial.is_none() {
Some(Child::Nodes(vec![]))
} else {
initial
}; */
/* while let Some(Child::Fn(f)) = current {
current = Some(f());
} */
match value {
Child::Fn(f) => {
let mut current = initial.clone();
cx.create_effect(move || {
let mut value = f();
while let Child::Fn(f) = value {
value = f();
}
insert_expression(
parent.clone().unchecked_into(),
&f(),
current.clone().unwrap_or(Child::Null),
//current.get_untracked().clone(), // get untracked to avoid infinite loop when we set current, below
before.as_ref(),
);
current = Some(value);
});
}
_ => {
insert_expression(
parent.unchecked_into(),
&value,
initial.clone().unwrap_or(Child::Null),
before.as_ref(),
);
}
}
}
pub fn insert_expression<'a>(
parent: web_sys::Element,
new_value: &Child<'a>,
mut current: Child<'a>,
before: Option<&web_sys::Node>,
) -> Child<'a> {
if new_value == &current {
current
} else {
let multi = before.is_some();
let parent = if multi {
match &current {
Child::Nodes(nodes) => nodes
.get(0)
.and_then(|node| node.parent_node())
.map(|node| node.unchecked_into::<web_sys::Element>())
.unwrap_or_else(|| parent.clone()),
_ => parent,
}
} else {
parent
};
match new_value {
// if the new value is null, clean children out of the parent up to the marker node
Child::Null => {
if let Child::Node(old_node) = current {
crate::debug_warn!("just remove the node");
remove_child(&parent, &old_node);
Child::Null
} else {
clean_children(&parent, current, before, None)
}
}
// if it's a new text value, set that text value
Child::Text(data) => insert_str(&parent, data, before, multi, current),
Child::Node(node) => match current {
Child::Nodes(current) => {
clean_children(&parent, Child::Nodes(current), before, Some(node.clone()))
}
Child::Null => Child::Node(append_child(&parent, node)),
Child::Text(current_text) => {
if current_text.is_empty() {
Child::Node(append_child(&parent, node))
} else {
replace_with(parent.first_child().unwrap_throw().unchecked_ref(), node);
Child::Node(node.clone())
}
}
Child::Node(old_node) => {
replace_with(old_node.unchecked_ref(), node);
Child::Node(node.clone())
}
Child::Fn(_) => {
debug_warn!(
"{}: replacing a Child::Node<{}> with Child::Fn<...>",
std::panic::Location::caller(),
node.node_name()
);
current
}
},
Child::Nodes(new_nodes) => {
if new_nodes.is_empty() {
clean_children(&parent, current, before, None)
} else if let Child::Nodes(ref mut current_nodes) = current {
if current_nodes.is_empty() {
Child::Nodes(append_nodes(&parent, new_nodes, before))
} else {
reconcile_arrays(&parent, current_nodes, new_nodes);
Child::Nodes(new_nodes.to_vec())
}
} else {
clean_children(&parent, Child::Null, None, None);
append_nodes(&parent, new_nodes, before);
Child::Nodes(new_nodes.to_vec())
}
}
// Nested Signals here simply won't do anything; they should be flattened so it's a single Signal
Child::Fn(_) => {
debug_warn!(
"{}: Child<Fn<'a, Child<Fn<'a, ...>>> should be flattened.",
std::panic::Location::caller()
);
current
}
}
}
}
fn node_list_to_vec(node_list: web_sys::NodeList) -> Vec<web_sys::Node> {
let mut vec = Vec::new();
for idx in 0..node_list.length() {
if let Some(node) = node_list.item(idx) {
vec.push(node);
}
}
vec
}
pub fn insert_str<'a>(
parent: &web_sys::Element,
data: &str,
before: Option<&web_sys::Node>,
multi: bool,
current: Child,
) -> Child<'a> {
if multi {
let node = if let Child::Nodes(nodes) = &current {
if let Some(node) = nodes.get(0) {
if node.node_type() == 3 {
node.unchecked_ref::<web_sys::Text>().set_data(data);
node.clone()
} else {
create_text_node(data).unchecked_into()
}
} else {
create_text_node(data).unchecked_into()
}
} else if let Some(node) = before
.and_then(|marker| marker.previous_sibling())
.and_then(|prev| prev.dyn_into::<web_sys::Text>().ok())
{
node.set_data(data);
return Child::Text(data.to_string());
} else {
create_text_node(data).unchecked_into()
};
clean_children(parent, current, before, Some(node))
} else {
match current {
Child::Text(_) => match before {
Some(marker) => {
let prev = marker.previous_sibling().unwrap_throw();
if let Some(text_node) = prev.dyn_ref::<web_sys::Text>() {
crate::log!("branch A");
text_node.set_data(data)
} else {
crate::log!("branch B");
prev.set_text_content(Some(data))
}
}
None => match parent.first_child() {
Some(child) => {
crate::log!("branch C");
child.unchecked_ref::<web_sys::Text>().set_data(data);
}
None => {
crate::log!("branch D");
parent.set_text_content(Some(data))
}
},
},
/* match parent.first_child() {
Some(child) => {
child.unchecked_ref::<web_sys::Text>().set_data(data);
}
None => parent.set_text_content(Some(data)),
}, */
_ => parent.set_text_content(Some(data)),
}
Child::Text(data.to_string())
}
}
fn append_nodes(
parent: &web_sys::Element,
new_nodes: &[web_sys::Node],
marker: Option<&web_sys::Node>,
) -> Vec<web_sys::Node> {
let mut result = Vec::new();
for node in new_nodes {
if let Some(marker) = marker {
result.push(insert_before(parent, node, Some(marker)));
} else {
result.push(append_child(parent, node));
}
}
result
}
fn clean_children<'a>(
parent: &web_sys::Element,
current: Child,
marker: Option<&web_sys::Node>,
replacement: Option<web_sys::Node>,
) -> Child<'a> {
match marker {
None => {
parent.set_text_content(Some(""));
Child::Null
}
Some(marker) => {
let node = replacement.unwrap_or_else(|| create_text_node("").unchecked_into());
match current {
Child::Null => Child::Node(insert_before(parent, &node, Some(marker))),
Child::Text(_) => Child::Node(insert_before(parent, &node, Some(marker))),
Child::Node(node) => Child::Node(insert_before(parent, &node, Some(marker))),
Child::Nodes(nodes) => {
let mut inserted = false;
let mut result = Vec::new();
for (idx, el) in nodes.iter().enumerate().rev() {
if &node != el {
let is_parent =
el.parent_node() == Some(parent.clone().unchecked_into());
if !inserted && idx == 0 {
if is_parent {
replace_child(parent, &node, el);
result.push(node.clone())
} else {
result.push(insert_before(parent, &node, Some(marker)))
}
}
} else {
inserted = true;
}
}
Child::Nodes(result)
}
Child::Fn(_) => todo!(),
}
}
}
}

2
leptos_macro/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

14
leptos_macro/Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "leptos_macro"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
proc-macro-error = "1.0.4"
proc-macro2 = "1"
quote = "1"
syn = { version = "1", features = ["full", "parsing", "extra-traits"] }
syn-rsx = "0.8.1"

View file

@ -0,0 +1,163 @@
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
*,
};
pub struct InlinePropsBody {
pub attrs: Vec<Attribute>,
pub vis: syn::Visibility,
pub fn_token: Token![fn],
pub ident: Ident,
pub cx_token: Box<Pat>,
pub generics: Generics,
pub paren_token: token::Paren,
pub inputs: Punctuated<FnArg, Token![,]>,
// pub fields: FieldsNamed,
pub output: ReturnType,
pub where_clause: Option<WhereClause>,
pub block: Box<Block>,
}
/// The custom rusty variant of parsing rsx!
impl Parse for InlinePropsBody {
fn parse(input: ParseStream) -> Result<Self> {
let attrs: Vec<Attribute> = input.call(Attribute::parse_outer)?;
let vis: Visibility = input.parse()?;
let fn_token = input.parse()?;
let ident = input.parse()?;
let generics: Generics = input.parse()?;
let content;
let paren_token = syn::parenthesized!(content in input);
let first_arg: FnArg = content.parse()?;
let cx_token = {
match first_arg {
FnArg::Receiver(_) => panic!("first argument must not be a receiver argument"),
FnArg::Typed(f) => f.pat,
}
};
let _: Result<Token![,]> = content.parse();
let inputs = syn::punctuated::Punctuated::parse_terminated(&content)?;
let output = input.parse()?;
let where_clause = input
.peek(syn::token::Where)
.then(|| input.parse())
.transpose()?;
let block = input.parse()?;
Ok(Self {
vis,
fn_token,
ident,
generics,
paren_token,
inputs,
output,
where_clause,
block,
cx_token,
attrs,
})
}
}
/// Serialize the same way, regardless of flavor
impl ToTokens for InlinePropsBody {
fn to_tokens(&self, out_tokens: &mut TokenStream2) {
let Self {
vis,
ident,
generics,
inputs,
output,
where_clause,
block,
cx_token,
attrs,
..
} = self;
let fields = inputs.iter().map(|f| {
quote! { #vis #f }
});
let struct_name = Ident::new(&format!("{}Props", ident), Span::call_site());
let field_names = inputs.iter().filter_map(|f| match f {
FnArg::Receiver(_) => todo!(),
FnArg::Typed(t) => Some(&t.pat),
});
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let modifiers = if first_lifetime.is_some() {
quote! { #[derive(Props)] }
} else {
quote! { #[derive(Props, PartialEq, Eq)] }
};
let (scope_lifetime, fn_generics, struct_generics) = if let Some(lt) = first_lifetime {
let struct_generics: Punctuated<_, token::Comma> = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.push(parse_quote!( 'a ));
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
(
quote! { #lt, },
generics.clone(),
quote! { <#struct_generics> },
)
} else {
let lifetime: LifetimeDef = parse_quote! { 'a };
let mut fn_generics = generics.clone();
fn_generics
.params
.insert(0, GenericParam::Lifetime(lifetime.clone()));
(quote! { #lifetime, }, fn_generics, quote! { #generics })
};
out_tokens.append_all(quote! {
#modifiers
#[allow(non_camel_case_types)]
#vis struct #struct_name #struct_generics
#where_clause
{
#(#fields),*
}
#[allow(non_snake_case)]
#(#attrs)*
#vis fn #ident #fn_generics (#cx_token: Scope<#scope_lifetime>, props: #struct_name) #output
#where_clause
{
let #struct_name { #(#field_names),* } = props;
#block
}
});
}
}

500
leptos_macro/src/csr.rs Normal file
View file

@ -0,0 +1,500 @@
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{spanned::Spanned, ExprPath};
use syn_rsx::{Node, NodeName, NodeType};
use crate::is_component_node;
pub fn client_side_rendering(nodes: &[Node]) -> TokenStream {
if nodes.len() == 1 {
first_node_to_tokens(&nodes[0])
} else {
let nodes = nodes.iter().map(first_node_to_tokens);
quote! {
{
vec![
#(#nodes),*
]
}
}
}
}
fn first_node_to_tokens(node: &Node) -> TokenStream {
match node.node_type {
NodeType::Doctype | NodeType::Comment => quote! {},
NodeType::Fragment => {
let nodes = node.children.iter().map(first_node_to_tokens);
quote! {
{
vec![
#(#nodes),*
]
}
}
}
NodeType::Element => root_element_to_tokens(node),
NodeType::Block => node
.value
.as_ref()
.map(|value| quote! { #value })
.expect("root Block node with no value"),
_ => panic!("Root nodes need to be a Fragment (<></>) or Element."),
}
}
fn root_element_to_tokens(node: &Node) -> TokenStream {
let mut template = String::new();
let mut navigations = Vec::new();
let mut expressions = Vec::new();
if is_component_node(node) {
create_component(node)
} else {
element_to_tokens(
node,
&Ident::new("root", Span::call_site()),
None,
&mut 0,
&mut template,
&mut navigations,
&mut expressions,
);
quote! {
{
let template = #template;
let root = leptos_dom::clone_template(&leptos_dom::create_template(template));
#(#navigations);*
#(#expressions);*;
// returns the first child created in the template
root.first_element_child().unwrap_throw()
}
}
}
}
#[derive(Clone, Debug)]
enum PrevSibChange {
Sib(Ident),
Parent,
Skip,
}
#[allow(clippy::too_many_arguments)]
fn element_to_tokens(
node: &Node,
parent: &Ident,
prev_sib: Option<Ident>,
next_el_id: &mut usize,
template: &mut String,
navigations: &mut Vec<TokenStream>,
expressions: &mut Vec<TokenStream>,
) -> Ident {
// create this element
*next_el_id += 1;
let this_el_ident = child_ident(*next_el_id, node);
// TEMPLATE: open tag
let name_str = node.name_as_string().unwrap();
template.push('<');
template.push_str(&name_str);
// attributes
for attr in &node.attributes {
attr_to_tokens(attr, &this_el_ident, template, expressions);
}
// navigation for this el
let debug_name = debug_name(node);
let span = span(node);
let this_nav = if let Some(prev_sib) = &prev_sib {
quote_spanned! {
span => let #this_el_ident = #debug_name;
let #this_el_ident = #prev_sib.next_sibling().unwrap_throw();
}
} else {
quote_spanned! {
span => let #this_el_ident = #debug_name;
let #this_el_ident = #parent.first_child().unwrap_throw();
}
};
navigations.push(this_nav);
// self-closing tags
// https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
if matches!(
name_str.as_str(),
"area"
| "base"
| "br"
| "col"
| "embed"
| "hr"
| "img"
| "input"
| "link"
| "meta"
| "param"
| "source"
| "track"
| "wbr"
) {
template.push_str("/>");
return this_el_ident;
} else {
template.push('>');
}
// iterate over children
let mut prev_sib = prev_sib;
for (idx, child) in node.children.iter().enumerate() {
// set next sib (for any insertions)
let next_sib = node.children.get(idx + 1).and_then(|next_sib| {
if is_component_node(next_sib) {
None
} else {
Some(child_ident(*next_el_id + 1, next_sib))
}
});
let curr_id = child_to_tokens(
child,
&this_el_ident,
if idx == 0 { None } else { prev_sib.clone() },
next_sib,
next_el_id,
template,
navigations,
expressions,
);
prev_sib = match curr_id {
PrevSibChange::Sib(id) => Some(id),
PrevSibChange::Parent => None,
PrevSibChange::Skip => prev_sib,
};
}
// TEMPLATE: close tag
template.push_str("</");
template.push_str(&name_str);
template.push('>');
this_el_ident
}
fn attr_to_tokens(
node: &Node,
el_id: &Ident,
template: &mut String,
expressions: &mut Vec<TokenStream>,
) {
let name = node
.name_as_string()
.expect("Attribute nodes must have strings as names.");
let name = if name.starts_with('_') {
name.replacen('_', "", 1)
} else {
name
};
let value = match &node.value {
Some(expr) => match expr {
syn::Expr::Lit(_) => AttributeValue::Static(node.value_as_string().unwrap()),
_ => AttributeValue::Dynamic(expr),
},
None => AttributeValue::Empty,
};
let span = node.name_span().unwrap();
// refs
if name == "ref" {
expressions.push(match &node.value {
Some(expr) => {
if let Some(ident) = expr_to_ident(expr) {
quote_spanned! {
span =>
// we can't pass by reference because the _el won't live long enough (it's dropped when template returns)
// so we clone here; this will be unnecessary if it's the last attribute, but very necessary otherwise
#ident = #el_id.clone().unchecked_into::<web_sys::Element>();
}
} else {
panic!("'ref' needs to be passed a variable name")
}
}
_ => panic!("'ref' needs to be passed a variable name"),
})
}
// Event Handlers
else if name.starts_with("on:") {
let event_name = name.replacen("on:", "", 1);
let handler = node
.value
.as_ref()
.expect("event listener attributes need a value");
expressions.push(quote_spanned! {
span => add_event_listener(#el_id.unchecked_ref(), #event_name, #handler);
});
}
// Properties
else if name.starts_with("prop:") {
let name = name.replacen("prop:", "", 1);
let value = node.value.as_ref().expect("prop: blocks need values");
expressions.push(quote_spanned! {
span => leptos_dom::property(cx, #el_id.unchecked_ref(), #name, #value.into_property(cx))
});
}
// Classes
else if name.starts_with("class:") {
let name = name.replacen("class:", "", 1);
let value = node.value.as_ref().expect("class: attributes need values");
expressions.push(quote_spanned! {
span => leptos_dom::class(cx, #el_id.unchecked_ref(), #name, #value.into_class(cx))
});
}
// Attributes
else {
match value {
// Boolean attributes: only name present in template, no value
// Nothing set programmatically
AttributeValue::Empty => {
template.push(' ');
template.push_str(&name);
}
// Static attributes (i.e., just a literal given as value, not an expression)
// are just set in the template — again, nothing programmatic
AttributeValue::Static(value) => {
template.push(' ');
template.push_str(&name);
template.push_str("=\"");
template.push_str(&value);
template.push('"');
}
// For client-side rendering, dynamic attributes don't need to be rendered in the template
// They'll immediately be set synchronously before the cloned template is mounted
AttributeValue::Dynamic(value) => {
expressions.push(quote_spanned! {
span => leptos_dom::attribute(cx, #el_id.unchecked_ref(), #name, #value.into_attribute(cx))
});
}
}
}
}
enum AttributeValue<'a> {
Static(String),
Dynamic(&'a syn::Expr),
Empty,
}
#[allow(clippy::too_many_arguments)]
fn child_to_tokens(
node: &Node,
parent: &Ident,
prev_sib: Option<Ident>,
next_sib: Option<Ident>,
next_el_id: &mut usize,
template: &mut String,
navigations: &mut Vec<TokenStream>,
expressions: &mut Vec<TokenStream>,
) -> PrevSibChange {
match node.node_type {
NodeType::Element => {
if is_component_node(node) {
component_to_tokens(node, Some(parent), next_sib, expressions)
} else {
PrevSibChange::Sib(element_to_tokens(
node,
parent,
prev_sib,
next_el_id,
template,
navigations,
expressions,
))
}
}
NodeType::Text | NodeType::Block => {
let str_value = node.value.as_ref().and_then(|expr| match expr {
syn::Expr::Lit(lit) => match &lit.lit {
syn::Lit::Str(s) => Some(s.value()),
syn::Lit::Char(c) => Some(c.value().to_string()),
syn::Lit::Int(i) => Some(i.base10_digits().to_string()),
syn::Lit::Float(f) => Some(f.base10_digits().to_string()),
_ => None,
},
_ => None,
});
// code to navigate to this text node
let span = node
.value
.as_ref()
.map(|val| val.span())
.unwrap_or_else(Span::call_site);
if let Some(v) = str_value {
*next_el_id += 1;
let name = child_ident(*next_el_id, node);
let location = if let Some(sibling) = prev_sib {
quote_spanned! {
span => let #name = #sibling.next_sibling().unwrap_throw();
}
} else {
quote_spanned! {
span => let #name = #parent.first_child().unwrap_throw();
}
};
navigations.push(location);
template.push_str(&v);
PrevSibChange::Sib(name)
} else {
// doesn't push to template, so shouldn't push to navigations
let before = match &next_sib {
Some(child) => quote! { Some(#child.clone()) },
None => quote! { None },
};
let value = node.value_as_block().expect("no block value");
expressions.push(quote! {
leptos::insert(
cx,
#parent.clone(),
#value.into_child(cx),
#before,
None,
);
});
PrevSibChange::Skip
}
}
_ => panic!("unexpected child node type"),
}
}
#[allow(clippy::too_many_arguments)]
fn component_to_tokens(
node: &Node,
parent: Option<&Ident>,
next_sib: Option<Ident>,
expressions: &mut Vec<TokenStream>,
) -> PrevSibChange {
let create_component = create_component(node);
if let Some(parent) = parent {
let before = match &next_sib {
Some(child) => quote! { Some(#child.clone()) },
None => quote! { None },
};
expressions.push(quote! {
leptos::insert(
cx,
#parent.clone(),
#create_component.into_child(cx),
#before,
None,
);
});
} else {
expressions.push(create_component)
}
PrevSibChange::Skip
}
fn create_component(node: &Node) -> TokenStream {
let component_name = ident_from_tag_name(node.name.as_ref().unwrap());
let span = node.name_span().unwrap();
let component_props_name = Ident::new(&format!("{component_name}Props"), span);
let children = if !node.children.is_empty() {
let children = client_side_rendering(&node.children);
quote! { .children(#children) }
} else {
quote! {}
};
let props = node.attributes.iter().map(|attr| {
let name = ident_from_tag_name(attr.name.as_ref().unwrap());
let value = attr.value.as_ref().expect("component props need values");
let span = attr.name_span().unwrap();
quote_spanned! {
span => .#name(#value)
}
});
// TODO children
quote_spanned! {
span => create_component(cx, || {
#component_name(
cx,
#component_props_name::builder()
#(#props)*
#children
.build(),
)
})
}
}
fn debug_name(node: &Node) -> String {
node.name_as_string().unwrap_or_else(|| {
node.value_as_string()
.expect("expected either node name or value")
})
}
fn span(node: &Node) -> Span {
node.name_span()
.unwrap_or_else(|| node.value.as_ref().unwrap().span())
}
fn child_ident(el_id: usize, node: &Node) -> Ident {
let id = format!("_el{el_id}");
match node.node_type {
NodeType::Element => Ident::new(&id, node.name_span().unwrap()),
NodeType::Text | NodeType::Block => Ident::new(&id, node.value.as_ref().unwrap().span()),
_ => panic!("invalid child node type"),
}
}
fn ident_from_tag_name(tag_name: &NodeName) -> Ident {
match tag_name {
NodeName::Path(path) => path
.path
.segments
.iter()
.last()
.map(|segment| segment.ident.clone())
.expect("element needs to have a name"),
NodeName::Block(_) => panic!("blocks not allowed in tag-name position"),
_ => Ident::new(
&tag_name.to_string().replace('-', "_").replace(':', "_"),
tag_name.span(),
),
}
}
fn expr_to_ident(expr: &syn::Expr) -> Option<&ExprPath> {
match expr {
syn::Expr::Block(block) => block.block.stmts.last().and_then(|stmt| {
if let syn::Stmt::Expr(expr) = stmt {
expr_to_ident(expr)
} else {
None
}
}),
syn::Expr::Path(path) => Some(path),
_ => None,
}
}

74
leptos_macro/src/lib.rs Normal file
View file

@ -0,0 +1,74 @@
use proc_macro::TokenStream;
use quote::ToTokens;
use syn::{parse_macro_input, DeriveInput};
use syn_rsx::{parse, Node, NodeType};
enum Mode {
Client,
Hydrate,
Dehydrate,
Static,
}
impl Default for Mode {
fn default() -> Self {
Self::Client
}
}
mod csr;
use csr::client_side_rendering;
mod component;
mod props;
#[proc_macro]
pub fn view(tokens: TokenStream) -> TokenStream {
match parse(tokens) {
Ok(nodes) => {
let mode = std::env::var("LEPTOS_MODE")
.map(|mode| match mode.to_lowercase().as_str() {
"client" => Mode::Client,
"hydrate" => Mode::Hydrate,
"dehydrate" => Mode::Dehydrate,
"static" => Mode::Static,
_ => Mode::Client,
})
.unwrap_or_default();
match mode {
Mode::Client => client_side_rendering(&nodes),
_ => todo!(),
}
}
Err(error) => error.to_compile_error(),
}
.into()
}
#[proc_macro_attribute]
pub fn component(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
match syn::parse::<component::InlinePropsBody>(s) {
Err(e) => e.to_compile_error().into(),
Ok(s) => s.to_token_stream().into(),
}
}
#[proc_macro_derive(Props, attributes(builder))]
pub fn derive_prop(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
props::impl_derive_prop(&input)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
pub(crate) fn is_component_node(node: &Node) -> bool {
if let NodeType::Element = node.node_type {
node.name_as_string()
.and_then(|node_name| node_name.chars().next())
.map(|first_char| first_char.is_ascii_uppercase())
.unwrap_or(false)
} else {
false
}
}

1270
leptos_macro/src/props.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,7 @@
[package]
name = "leptos_reactive"
version = "0.1.0"
edition = "2021"
[dependencies]
bumpalo = "3"

View file

@ -0,0 +1,96 @@
use std::{
cell::RefCell,
hash::Hash,
rc::{Rc, Weak},
};
use super::root_context::RootContext;
#[derive(Clone)]
pub struct Effect {
pub(crate) inner: Rc<EffectInner>,
}
pub(crate) struct EffectInner {
pub(crate) stack: &'static RootContext,
pub(crate) f: RefCell<Box<dyn FnMut()>>,
pub(crate) dependencies: RefCell<Vec<Weak<dyn EffectDependency>>>,
}
pub(crate) trait EffectDependency {
fn unsubscribe(&self, effect: Rc<EffectInner>);
}
impl std::fmt::Debug for Effect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Effect").finish()
}
}
impl Effect {
pub(crate) fn execute(&self) {
self.inner.execute(Rc::downgrade(&self.inner));
}
}
impl EffectInner {
pub(crate) fn execute(&self, for_stack: Weak<EffectInner>) {
// clear previous dependencies
// at this point, Effect dependencies have been added to Signal
// and any Signal changes will call Effect dependency automatically
if let Some(upgraded) = for_stack.upgrade() {
self.cleanup(upgraded);
}
// add it to the Scope stack, which means any signals called
// in the effect fn immediately below will add this Effect as a dependency
self.stack.push(for_stack);
// actually run the effect, which will re-add Signal dependencies as they're called
(self.f.borrow_mut())();
// pop it back off the stack
self.stack.pop();
}
pub(crate) fn cleanup(&self, for_subscriber: Rc<EffectInner>) {
// remove the Effect from the subscripts of each Signal to which it is subscribed
// these were called during a previous execution of the Effect
// they will be resubscribed, if necessary, during the coming execution
// this kind of dynamic dependency graph reconstruction may seem silly,
// but is actually more efficient because it avoids resubscribing with Signals
// if they are excluded by some kind of conditional logic within the Effect fn
for dep in self.dependencies.borrow().iter() {
if let Some(dep) = dep.upgrade() {
dep.unsubscribe(for_subscriber.clone());
}
}
// and clear all our dependencies on Signals; these will be built back up
// by the Signals if/when they are called again
self.dependencies.borrow_mut().clear();
}
pub(crate) fn add_dependency(&self, dep: Weak<dyn EffectDependency>) {
self.dependencies.borrow_mut().push(dep);
}
}
impl PartialEq for Effect {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl PartialEq for EffectInner {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(&self.f, &other.f) && std::ptr::eq(&self.dependencies, &other.dependencies)
}
}
impl Eq for EffectInner {}
impl Hash for EffectInner {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&self.f, state);
std::ptr::hash(&self.dependencies, state);
}
}

View file

@ -0,0 +1,74 @@
// allow because our ReadSignal call requires &'a ReadSignal
// hopefully this will make more sense at some point
#![allow(clippy::needless_borrow)]
#![feature(fn_traits)]
#![feature(unboxed_closures)]
mod effect;
mod root_context;
mod scope;
mod scope_arena;
mod signal;
pub use effect::*;
pub use root_context::*;
pub use scope::*;
pub use signal::*;
#[cfg(test)]
mod tests {
use crate::{create_scope, root_context::RootContext};
#[test]
fn compute_signal() {
let stack = Box::leak(Box::new(RootContext::new()));
let _ = create_scope(stack, |cx| {
let (a, set_a) = cx.signal(0);
let (b, set_b) = cx.signal(0);
let c = cx.memo(|| *(&a)() + *(&b)());
assert_eq!(*c.get_untracked(), 0);
set_a(|n| *n = 2);
assert_eq!(*c.get_untracked(), 2);
set_b(|n| *n = 2);
assert_eq!(*c.get_untracked(), 4);
});
}
#[test]
fn memo_with_conditional_branches() {
let stack = Box::leak(Box::new(RootContext::new()));
let _ = create_scope(stack, |cx| {
let (first_name, set_first_name) = cx.signal("Greg");
let (last_name, set_last_name) = cx.signal("Johnston");
let (show_last_name, set_show_last_name) = cx.signal(true);
let out = cx.memo(move || {
if *(&show_last_name)() {
format!("{} {}", *(&first_name)(), *(&last_name)())
} else {
(*(&first_name)()).to_string()
}
});
assert_eq!(*out.get_untracked(), "Greg Johnston");
set_first_name(|n| *n = "Murray");
assert_eq!(*out.get_untracked(), "Murray Johnston");
set_show_last_name(|n| *n = false);
assert_eq!(*out.get_untracked(), "Murray");
set_last_name(|n| *n = "Kenney");
assert_eq!(*out.get_untracked(), "Murray");
set_show_last_name(|n| *n = true);
assert_eq!(*out.get_untracked(), "Murray Kenney");
});
}
}

View file

@ -0,0 +1,36 @@
use std::{cell::RefCell, rc::Weak};
use crate::EffectInner;
pub struct RootContext {
pub(crate) stack: RefCell<Vec<Weak<EffectInner>>>,
}
impl RootContext {
pub fn new() -> Self {
Self {
stack: RefCell::new(Vec::new()),
}
}
pub(crate) fn push(&self, effect: Weak<EffectInner>) {
self.stack.borrow_mut().push(effect);
}
pub(crate) fn pop(&self) {
self.stack.borrow_mut().pop();
}
pub(crate) fn untrack<T>(&self, f: impl FnOnce() -> T) -> T {
let prev_stack = self.stack.replace(Vec::new());
let untracked_result = f();
self.stack.replace(prev_stack);
untracked_result
}
}
impl Default for RootContext {
fn default() -> Self {
Self::new()
}
}

View file

@ -0,0 +1,265 @@
use crate::scope_arena::ScopeArena;
use crate::{EffectInner, SignalState};
use super::{root_context::RootContext, Effect, ReadSignal, WriteSignal};
use std::{
any::{Any, TypeId},
cell::RefCell,
collections::{HashMap, HashSet},
marker::PhantomData,
rc::Rc,
};
pub type Scope<'a> = BoundedScope<'a, 'a>;
#[must_use = "Creating a Scope without calling its disposer will leak memory."]
pub fn create_scope<'disposer>(
root_context: &'static RootContext,
f: impl for<'a> FnOnce(Scope<'a>),
) -> ScopeDisposer<'disposer> {
let inner = ScopeInner::new(&root_context);
let boxed_inner = Box::new(inner);
let inner_ptr = Box::into_raw(boxed_inner);
// TODO safety
root_context.untrack(|| f(unsafe { Scope::new(&*inner_ptr) }));
// TODO safety
ScopeDisposer::new(move || unsafe {
// SAFETY: Safe because ptr created using Box::into_raw.
let boxed = Box::from_raw(inner_ptr);
// SAFETY: Outside of call to f.
boxed.dispose();
})
}
#[derive(Clone, Copy)]
pub struct BoundedScope<'a, 'b: 'a> {
inner: &'a ScopeInner<'a>,
/// `&'b` for covariance!
_phantom: PhantomData<&'b ()>,
}
impl<'a, 'b> BoundedScope<'a, 'b> {
fn new(inner: &'a ScopeInner<'a>) -> Self {
Self {
inner,
_phantom: PhantomData,
}
}
pub fn create_ref<T>(self, value: T) -> &'a T {
self.inner.create_ref(value)
}
pub fn signal<T>(self, value: T) -> (&'a ReadSignal<T>, &'a WriteSignal<T>) {
self.inner.signal(value)
}
pub fn signal_cloned<T>(self, value: T) -> (ReadSignal<T>, WriteSignal<T>) {
let (read, write) = self.inner.signal(value);
(read.clone(), write.clone())
}
/// An effect is an observer that runs a side effect that depends Signals.
/// It will be run once immediately. The effect automatically subscribes to the Signals
/// it reads, so it will run again when any of them change.
pub fn create_effect(self, f: impl FnMut()) {
self.inner.create_effect(f)
}
pub fn untrack<T>(&self, f: impl Fn() -> T) -> T {
self.inner.root_context.untrack(f)
}
pub fn memo<T>(self, f: impl Fn() -> T) -> &'a ReadSignal<T> {
self.inner.memo(f)
}
pub fn provide_context<T: 'static>(self, value: T) {
self.inner.provide_context(value)
}
pub fn use_context<T: 'static>(self) -> Option<&'a T> {
self.inner.use_context()
}
pub fn child_scope<F>(self, f: F) -> ScopeDisposer<'a>
where
F: for<'child_lifetime> FnOnce(BoundedScope<'child_lifetime, 'a>),
{
let mut child = ScopeInner::new(self.inner.root_context);
// SAFETY: The only fields that are accessed on self from child is `context` which does not
// have any lifetime annotations.
child.parent = Some(unsafe { &*(self.inner as *const _) });
let boxed = Box::new(child);
let ptr = Box::into_raw(boxed);
let key = self
.inner
.children
.borrow_mut()
// SAFETY: None of the fields of ptr are accessed through child_scopes therefore we can
// safely transmute the lifetime.
.insert(unsafe { std::mem::transmute(ptr) });
// SAFETY: the address of the cx lives as long as 'a because:
// - It is allocated on the heap and therefore has a stable address.
// - self.child_cx is append only. That means that the Box<cx> will not be dropped until Self is
// dropped.
f(unsafe { Scope::new(&*ptr) });
// ^^^ -> `ptr` is still accessible here after call to f.
ScopeDisposer::new(move || unsafe {
let cx = self.inner.children.borrow_mut().remove(key).unwrap();
// SAFETY: Safe because ptr created using Box::into_raw and closure cannot live longer
// than 'a.
let cx = Box::from_raw(cx);
// SAFETY: Outside of call to f.
cx.dispose();
})
}
}
struct ScopeInner<'a> {
pub(crate) root_context: &'static RootContext,
pub(crate) parent: Option<&'a ScopeInner<'a>>,
arena: bumpalo::Bump,
pub(crate) cleanup_callbacks: RefCell<Vec<&'a mut dyn FnMut()>>,
context: RefCell<HashMap<TypeId, &'a dyn Any>>,
children: RefCell<ScopeArena<*mut ScopeInner<'a>>>,
}
impl<'a> ScopeInner<'a> {
pub fn new(root_context: &'static RootContext) -> Self {
Self {
root_context,
parent: None,
arena: bumpalo::Bump::new(),
cleanup_callbacks: RefCell::new(Vec::new()),
context: RefCell::new(HashMap::new()),
children: RefCell::new(ScopeArena::new()),
}
}
pub fn create_ref<T>(&self, value: T) -> &T {
self.arena.alloc(value)
}
pub fn signal<T>(&self, value: T) -> (&ReadSignal<T>, &WriteSignal<T>) {
let state = Rc::new(SignalState {
value: RefCell::new(value),
subscriptions: RefCell::new(HashSet::new()),
});
let writer = self.create_ref(WriteSignal {
inner: Rc::downgrade(&state),
});
let reader = self.create_ref(ReadSignal {
stack: self.root_context,
inner: state,
});
(reader, writer)
}
pub fn untrack<T>(&self, f: impl Fn() -> T) -> T {
self.root_context.untrack(f)
}
pub fn memo<T>(&self, f: impl Fn() -> T) -> &ReadSignal<T> {
// the initial value should simply be an untracked call, based on initial Signal values
// we need this initial call because the Signal must always have a value
// (otherwise every computed Signal would be typed Signal<Option<T>>)
// but if we track the initial here, because we haven't created the effect yet,
// this would subscribe to the surrounding effect, which isn't what we want
// untracking the initial_value call solves this chicken-and-egg problem
let initial_value = self.untrack(&f);
// now create the signal with that untracked initial values
let (read, write) = self.signal(initial_value);
// and start tracking based on whatever Signals are inside the computed fn
self.create_effect(move || write(|n| *n = f()));
read
}
/// An effect is an observer that runs a side effect that depends Signals.
/// It will be run once immediately. The effect automatically subscribes to the Signals
/// it reads, so it will run again when any of them change.
pub fn create_effect(&self, f: impl FnMut()) {
let f = Box::new(f) as Box<dyn FnMut()>;
// TODO safety
let f: Box<dyn FnMut() + 'static> = unsafe { std::mem::transmute(f) };
// the Effect will be owned by the arena, which means we can pass
// its reference around without worrying about ownership
// because it's immediately executed, it will never be dropped
// unless no Signal has it as a dependency and it's not in the stack,
// in which case it could never be called again anyway
let effect_ref = self.arena.alloc(Effect {
inner: Rc::new(EffectInner {
stack: self.root_context,
f: RefCell::new(Box::new(f)),
dependencies: RefCell::new(Vec::new()),
}),
});
effect_ref.execute();
}
pub(crate) fn dispose(self) {
// Drop child scopes.
for (_, child) in self.children.borrow_mut().drain() {
// SAFETY: These pointers were allocated in Self::create_child_scope.
let cx = unsafe { Box::from_raw(child) };
// Dispose of cx if it has not already been disposed.
cx.dispose();
}
// Call cleanup functions in an untracked scope.
for cb in self.cleanup_callbacks.borrow_mut().drain(..) {
cb();
}
// unnecessary but explicit!
drop(self)
}
pub fn provide_context<T: 'static>(&'a self, value: T) {
let id = value.type_id();
let value = self.arena.alloc(value);
self.context.borrow_mut().insert(id, &*value);
}
pub fn use_context<T: 'static>(&'a self) -> Option<&T> {
let id = TypeId::of::<T>();
let local_value = self
.context
.borrow()
.get(&id)
.and_then(|val| val.downcast_ref::<T>());
match local_value {
Some(val) => Some(val),
None => self.parent.and_then(|parent| parent.use_context::<T>()),
}
}
}
/// A handle that allows cleaning up a [`Scope`].
pub struct ScopeDisposer<'a> {
f: Box<dyn FnOnce() + 'a>,
}
impl<'a> ScopeDisposer<'a> {
fn new(f: impl FnOnce() + 'a) -> Self {
Self { f: Box::new(f) }
}
pub unsafe fn dispose(self) {
(self.f)();
}
}

View file

@ -0,0 +1,47 @@
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub(crate) struct ScopeArena<T> {
next_idx: usize,
items: HashMap<Index, T>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ScopeId(pub usize);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct Index {
index: usize,
}
impl<T> Default for ScopeArena<T> {
fn default() -> ScopeArena<T> {
ScopeArena::new()
}
}
impl<T> ScopeArena<T> {
pub(crate) fn new() -> ScopeArena<T> {
ScopeArena {
next_idx: 0,
items: HashMap::new(),
}
}
pub(crate) fn insert(&mut self, value: T) -> Index {
let index = Index {
index: self.next_idx,
};
self.next_idx += 1;
self.items.insert(index, value);
index
}
pub(crate) fn remove(&mut self, idx: Index) -> Option<T> {
self.items.remove(&idx)
}
pub(crate) fn drain(&mut self) -> impl Iterator<Item = (Index, T)> + '_ {
self.items.drain()
}
}

View file

@ -0,0 +1,203 @@
use std::{
cell::{Ref, RefCell},
collections::HashSet,
rc::{Rc, Weak},
};
use crate::EffectInner;
use super::{root_context::RootContext, EffectDependency};
pub struct ReadSignal<T: 'static> {
pub(crate) stack: &'static RootContext,
pub(crate) inner: Rc<SignalState<T>>,
}
impl<T> Clone for ReadSignal<T>
where
T: 'static,
{
fn clone(&self) -> Self {
Self {
stack: self.stack,
inner: Rc::clone(&self.inner),
}
}
}
impl<T> PartialEq for ReadSignal<T> {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.inner, &other.inner)
}
}
impl<T> Eq for ReadSignal<T> {}
impl<T: 'static> ReadSignal<T> {
pub fn get(&self) -> ReadSignalRef<T> {
if let Some(running_effect) = self.stack.stack.borrow().last() {
if let Some(running_effect) = running_effect.upgrade() {
// add the Effect to the Signal's subscriptions
self.add_subscriber(running_effect.clone());
// add the Signal to the Effect's dependencies
running_effect
.add_dependency(Rc::downgrade(&self.inner) as Weak<dyn EffectDependency>);
}
}
self.value()
}
pub fn get_untracked(&self) -> ReadSignalRef<T> {
self.value()
}
fn value(&self) -> ReadSignalRef<T> {
ReadSignalRef {
guard: self.inner.value.borrow(),
}
}
fn add_subscriber(&self, subscriber: Rc<EffectInner>) {
self.inner.subscriptions.borrow_mut().insert(subscriber);
}
}
impl<T> EffectDependency for SignalState<T> {
fn unsubscribe(&self, effect: Rc<EffectInner>) {
self.subscriptions.borrow_mut().remove(&effect);
}
}
use std::ops::Deref;
pub struct ReadSignalRef<'a, T> {
guard: Ref<'a, T>,
}
impl<'a, T> Deref for ReadSignalRef<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.guard
}
}
impl<T> std::fmt::Debug for ReadSignal<T>
where
T: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Signal")
.field("value", &self.value())
.finish()
}
}
impl<'a, T> FnOnce<()> for &'a ReadSignal<T> {
type Output = ReadSignalRef<'a, T>;
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.get()
}
}
impl<'a, T> FnMut<()> for &'a ReadSignal<T> {
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.get()
}
}
impl<'a, T> Fn<()> for &'a ReadSignal<T> {
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.get()
}
}
pub struct SignalState<T> {
pub(crate) value: RefCell<T>,
pub(crate) subscriptions: RefCell<HashSet<Rc<EffectInner>>>,
}
pub struct WriteSignal<T> {
pub(crate) inner: Weak<SignalState<T>>,
}
impl<T> Clone for WriteSignal<T>
where
T: 'static,
{
fn clone(&self) -> Self {
Self {
inner: Weak::clone(&self.inner),
}
}
}
impl<T> WriteSignal<T> {
pub fn update(&self, update_fn: impl FnOnce(&mut T)) {
if let Some(inner) = self.inner.upgrade() {
(update_fn)(&mut inner.value.borrow_mut());
for subscription in inner.subscriptions.take().iter() {
subscription.execute(Rc::downgrade(&subscription))
}
} else {
}
}
}
impl<T, F> FnOnce<(F,)> for WriteSignal<T>
where
F: Fn(&mut T),
{
type Output = ();
extern "rust-call" fn call_once(self, args: (F,)) -> Self::Output {
self.update(args.0)
}
}
impl<T, F> FnMut<(F,)> for WriteSignal<T>
where
F: Fn(&mut T),
{
extern "rust-call" fn call_mut(&mut self, args: (F,)) -> Self::Output {
self.update(args.0)
}
}
impl<T, F> Fn<(F,)> for WriteSignal<T>
where
F: Fn(&mut T),
{
extern "rust-call" fn call(&self, args: (F,)) -> Self::Output {
self.update(args.0)
}
}
impl<T> PartialEq for WriteSignal<T> {
fn eq(&self, other: &Self) -> bool {
Weak::ptr_eq(&self.inner, &other.inner)
}
}
impl<T> Eq for WriteSignal<T> {}
impl<'a, T> std::fmt::Display for ReadSignalRef<'a, T>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.guard.fmt(f)
}
}
impl<'a, T> std::fmt::Debug for ReadSignalRef<'a, T>
where
T: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.guard.fmt(f)
}
}