Merge branch 'master' into jk/partialexpansion

This commit is contained in:
Jonathan Kelley committed 2022-02-13 12:36:02 -05:00
commit ca7ce46cdb
198 files changed
+7002 -4021

No files matched your search

+39 -1
View File
@@ -5,6 +5,43 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### New Features
- <csr-id-d2372717bd01fcff50af0572360e3f763d4c869d/> flatten props attrs
- <csr-id-47bc4e4a44a7d08d4f42102d13f0766d9d6bf358/> add "optional" flag for props
### Bug Fixes
- <csr-id-90abd9c9a08c165384fae9c1f7c3fd098d512c48/> detection of f-string formatting in components
### Commit Statistics
<csr-read-only-do-not-edit/>
- 9 commits contributed to the release over the course of 12 calendar days.
- 3 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Merge pull request #95 from DioxusLabs/jk/filedragindrop ([`ca0dd4a`](https://github.comgit//DioxusLabs/dioxus/commit/ca0dd4aa7192d483a195d420363f39d771f3e471))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- flatten props attrs ([`d237271`](https://github.comgit//DioxusLabs/dioxus/commit/d2372717bd01fcff50af0572360e3f763d4c869d))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- detection of f-string formatting in components ([`90abd9c`](https://github.comgit//DioxusLabs/dioxus/commit/90abd9c9a08c165384fae9c1f7c3fd098d512c48))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
- Merge pull request #107 from autarch/autarch/half-assed-router ([`8d3ac3f`](https://github.comgit//DioxusLabs/dioxus/commit/8d3ac3ff148aef9d10a393eda453a11c1e882f58))
- Merge pull request #127 from DioxusLabs/jk/handler-tweak ([`5bce294`](https://github.comgit//DioxusLabs/dioxus/commit/5bce294a86941090660b1cfd87809a2b0b76d2ce))
- add "optional" flag for props ([`47bc4e4`](https://github.comgit//DioxusLabs/dioxus/commit/47bc4e4a44a7d08d4f42102d13f0766d9d6bf358))
</details>
## v0.1.6 (2022-01-08)
### Documentation
@@ -64,7 +101,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 138 commits contributed to the release over the course of 352 calendar days.
- 139 commits contributed to the release over the course of 352 calendar days.
- 123 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -75,6 +112,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-core-macro v0.1.6 ([`db0a5bd`](https://github.comgit//DioxusLabs/dioxus/commit/db0a5bd6ec93803cddb3c6fda4172257b9c301c6))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- component pass thru events ([`c439b0a`](https://github.comgit//DioxusLabs/dioxus/commit/c439b0ac7e09f70a04262b7c29938d8c52197b76))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-core-macro"
version = "0.1.6"
version = "0.1.7"
authors = ["Jonathan Kelley"]
edition = "2021"
description = "Core macro for Dioxus Virtual DOM"
@@ -1,8 +0,0 @@
fn main() {
// use dioxus_core_macro::*;
// let r = html! {
// <div>
// "hello world"
// </div>
// };
}
@@ -1,22 +0,0 @@
use dioxus_core_macro::{inline_props, Props};
fn main() {}
type Element<'a> = ();
pub struct Scope<'a, T = ()> {
props: &'a T,
}
// #[inline_props]
pub fn component<'a>(
cx: Scope<'a>,
chkk: String,
chkk2: String,
r: u32,
cat: &'a str,
drd: String,
e: String,
) -> Element<'a> {
let r = chkk.len();
}
-24
View File
@@ -1,24 +0,0 @@
fn main() {}
pub mod dioxus {
pub mod prelude {
pub trait Properties {
type Builder;
const IS_STATIC: bool;
fn builder() -> Self::Builder;
unsafe fn memoize(&self, other: &Self) -> bool;
}
}
}
/// This implementation should require a "PartialEq" because it memoizes (no external references)
#[derive(PartialEq, dioxus_core_macro::Props)]
struct SomeProps {
a: String,
}
/// This implementation does not require a "PartialEq" because it does not memoize
#[derive(dioxus_core_macro::Props)]
struct SomePropsTwo<'a> {
_a: &'a str,
}
+4 -4
View File
@@ -76,7 +76,7 @@ pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::Token
/// // Using an "ID" associated with your data is a good idea.
/// data.into_iter().map(|(k, v)| rsx!(li { key: "{k}" "{v}" }))
/// }}
///
///
/// // Matching
/// {match true {
/// true => rsx!(h1 {"Top text"}),
@@ -224,18 +224,18 @@ pub fn routable_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
/// #[inline_props]
/// fn app(cx: Scope, bob: String) -> Element {
/// cx.render(rsx!("hello, {bob}"))
/// }
/// }
///
/// // is equivalent to
///
/// #[derive(PartialEq, Props)]
/// struct AppProps {
/// bob: String,
/// }
/// }
///
/// fn app(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!("hello, {bob}"))
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
+55 -2
View File
@@ -5,6 +5,58 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Documentation
- <csr-id-036a0ff49a7dade0e04c9c07071a1ff49133ee24/> add comments for the Handler
### New Features
- <csr-id-bad4b773b7bbab6a38d4f48d88d8c5a8787927ac/> add "spawn" method
- <csr-id-d2bd1751436ef4bec554bb361ba87aea1357036a/> allow providing context to the root component
### Bug Fixes
- <csr-id-d9a07ddddb45ba00e35645ac0e0ad1a4d2dd996d/> provide_root_context on root scopes
- <csr-id-c8d528b3b18e320ca0cee1542ae5fc659c1cca81/> proprogation of root context
- <csr-id-e47ead5347ce778935f8f2127fcb14f520eda0ce/> allow eventhandler to derive default
### Commit Statistics
<csr-read-only-do-not-edit/>
- 18 commits contributed to the release over the course of 13 calendar days.
- 8 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Merge pull request #169 from DioxusLabs/jk/router-userouter ([`3509602`](https://github.comgit//DioxusLabs/dioxus/commit/3509602c0bcd327a33bc8c95896775e24751da1a))
- Merge branch 'master' of github.com:DioxusLabs/dioxus ([`8899701`](https://github.comgit//DioxusLabs/dioxus/commit/88997019c5c74658bfd76344d6bb6f3565943b41))
- add miri stress test ([`e9792e9`](https://github.comgit//DioxusLabs/dioxus/commit/e9792e9b95521fcf0b0b4e240d7cf0397cd79b8f))
- add "spawn" method ([`bad4b77`](https://github.comgit//DioxusLabs/dioxus/commit/bad4b773b7bbab6a38d4f48d88d8c5a8787927ac))
- drop hooks before resetting bump arena ([`2e4f765`](https://github.comgit//DioxusLabs/dioxus/commit/2e4f7659327b69b74e20af59b6d5e65c699b6adb))
- provide_root_context on root scopes ([`d9a07dd`](https://github.comgit//DioxusLabs/dioxus/commit/d9a07ddddb45ba00e35645ac0e0ad1a4d2dd996d))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- Merge pull request #121 from DioxusLabs/jk/unify ([`b287a4c`](https://github.comgit//DioxusLabs/dioxus/commit/b287a4cab3eec9e6961a3f010846291f4f105747))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- proprogation of root context ([`c8d528b`](https://github.comgit//DioxusLabs/dioxus/commit/c8d528b3b18e320ca0cee1542ae5fc659c1cca81))
- allow providing context to the root component ([`d2bd175`](https://github.comgit//DioxusLabs/dioxus/commit/d2bd1751436ef4bec554bb361ba87aea1357036a))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
- Merge pull request #107 from autarch/autarch/half-assed-router ([`8d3ac3f`](https://github.comgit//DioxusLabs/dioxus/commit/8d3ac3ff148aef9d10a393eda453a11c1e882f58))
- Merge pull request #138 from mrxiaozhuox/master ([`8c7473d`](https://github.comgit//DioxusLabs/dioxus/commit/8c7473d1943dd133f388ec36116c9d8295861b97))
- Merge pull request #133 from mrxiaozhuox/master ([`887f69d`](https://github.comgit//DioxusLabs/dioxus/commit/887f69d5b47bdcde4fe0eab094c0cd0de23e4f3f))
- Don't expect all components to have a scope in ScopeArena.ensure_drop_safety ([`9b282d8`](https://github.comgit//DioxusLabs/dioxus/commit/9b282d877ba0fe2463687cde7ea899b7f8510425))
- add comments for the Handler ([`036a0ff`](https://github.comgit//DioxusLabs/dioxus/commit/036a0ff49a7dade0e04c9c07071a1ff49133ee24))
- allow eventhandler to derive default ([`e47ead5`](https://github.comgit//DioxusLabs/dioxus/commit/e47ead5347ce778935f8f2127fcb14f520eda0ce))
</details>
## v0.1.7 (2022-01-08)
### Documentation
@@ -138,7 +190,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 437 commits contributed to the release over the course of 358 calendar days.
- 438 commits contributed to the release over the course of 358 calendar days.
- 416 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -149,8 +201,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- Release dioxus-core v0.1.7 ([`16d73b2`](https://github.comgit//DioxusLabs/dioxus/commit/16d73b240fc446c6f6996c19ccf52bbcda2eca79))
- add title to doc comment ([`d11f322`](https://github.comgit//DioxusLabs/dioxus/commit/d11f322f554e7dbf43b988c9cfda56498cc49872))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- better document the `EventHandler` type ([`be9f1a5`](https://github.comgit//DioxusLabs/dioxus/commit/be9f1a52ad2b04f101397ae34482ea7394df653b))
- component pass thru events ([`c439b0a`](https://github.comgit//DioxusLabs/dioxus/commit/c439b0ac7e09f70a04262b7c29938d8c52197b76))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-core"
version = "0.1.7"
version = "0.1.9"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Core functionality for Dioxus - a concurrent renderer-agnostic Virtual DOM for interactive user experiences"
+1 -1
View File
@@ -94,5 +94,5 @@ Dioxus deals with arenas, lifetimes, asynchronous tasks, custom allocators, pinn
If you don't want to use a crate that uses unsafe, then this crate is not for you.
However, we are always interested in decreasing the scope of the core VirtualDom to make it easier to review. We'd be happy to welcome PRs that can eliminate unsafe code while still upholding the numerous variants required to execute certain features.
However, we are always interested in decreasing the scope of the core VirtualDom to make it easier to review. We'd be happy to welcome PRs that can eliminate unsafe code while still upholding the numerous invariants required to execute certain features.
+8 -8
View File
@@ -5,7 +5,7 @@ This document is mostly a brain-dump on how things work. A lot of this informati
Main topics covered here:
- Fiber, Concurrency, and Cooperative Scheduling
- Suspense
- Signals
- Signals
- Patches
- Diffing
- Const/Static structures
@@ -25,7 +25,7 @@ During diffing, the "caller" closure is updated if the props are not `static. Th
Hooks are a form of state that's slightly more finicky than structs but more extensible overall. Hooks cannot be used in conditionals, but are portable enough to run on most targets.
The Dioxus hook model uses a Bump arena where user's data lives.
The Dioxus hook model uses a Bump arena where user's data lives.
Initializing hooks:
- The component is created
@@ -38,7 +38,7 @@ Initializing hooks:
Running hooks:
- Each time use_hook is called, the internal hook state is fetched as &mut T
- We are guaranteed that our &mut T is not aliasing by re-generating any &mut T dependencies
- We are guaranteed that our &mut T is not aliasing by re-generating any &mut T dependencies
- The hook counter is incremented
@@ -62,7 +62,7 @@ The diffing engine in Dioxus expects the RealDom
Dioxus uses patches - not imperative methods - to modify the real dom. This speeds up the diffing operation and makes diffing cancelable which is useful for cooperative scheduling. In general, the RealDom trait exists so renderers can share "Node pointers" across runtime boundaries.
There are no contractual obligations between the VirtualDOM and RealDOM. When the VirtualDOM finishes its work, it releases a Vec of Edits (patches) which the RealDOM can use to update itself.
There are no contractual obligations between the VirtualDOM and RealDOM. When the VirtualDOM finishes its work, it releases a Vec of Edits (patches) which the RealDOM can use to update itself.
@@ -70,11 +70,11 @@ There are no contractual obligations between the VirtualDOM and RealDOM. When th
When an EventTrigger enters the queue and "progress" is called (an async function), Dioxus will get to work running scopes and diffing nodes. Scopes are run and nodes are diffed together. Dioxus records which scopes get diffed to track the progress of its work.
While descending through the stack frame, Dioxus will query the RealDom for "time remaining." When the time runs out, Dioxus will escape the stack frame by queuing whatever work it didn't get to, and then bubbling up out of "diff_node". Dioxus will also bubble out of "diff_node" if more important work gets queued while it was descending.
While descending through the stack frame, Dioxus will query the RealDom for "time remaining." When the time runs out, Dioxus will escape the stack frame by queuing whatever work it didn't get to, and then bubbling up out of "diff_node". Dioxus will also bubble out of "diff_node" if more important work gets queued while it was descending.
Once bubbled out of diff_node, Dioxus will request the next idle callback and await for it to become available. The return of this callback is a "Deadline" object which Dioxus queries through the RealDom.
Once bubbled out of diff_node, Dioxus will request the next idle callback and await for it to become available. The return of this callback is a "Deadline" object which Dioxus queries through the RealDom.
All of this is orchestrated to keep high priority events moving through the VirtualDOM and scheduling lower-priority work around the RealDOM's animations and periodic tasks.
All of this is orchestrated to keep high priority events moving through the VirtualDOM and scheduling lower-priority work around the RealDOM's animations and periodic tasks.
```js
// returns a "deadline" object
function idle() {
@@ -83,7 +83,7 @@ function idle() {
```
## Suspense
In React, "suspense" is the ability render nodes outside of the traditional lifecycle. React will wait on a future to complete, and once the data is ready, will render those nodes. React's version of suspense is designed to make working with promises in components easier.
In React, "suspense" is the ability render nodes outside of the traditional lifecycle. React will wait on a future to complete, and once the data is ready, will render those nodes. React's version of suspense is designed to make working with promises in components easier.
In Dioxus, we have similar philosophy, but the use and details of suspense is slightly different. For starters, we don't currently allow using futures in the element structure. Technically, we can allow futures - and we do with "Signals" - but the "suspense" feature itself is meant to be self-contained within a single component. This forces you to handle all the loading states within your component, instead of outside the component, keeping things a bit more containerized.
-33
View File
@@ -1,33 +0,0 @@
use dioxus::prelude::*;
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
fn main() {}
fn app(cx: Scope) -> Element {
cx.render(rsx!(div {
app2(
p: "asd"
)
}))
}
#[derive(Props)]
struct Borrowed<'a> {
p: &'a str,
}
fn app2<'a>(cx: Scope<'a, Borrowed<'a>>) -> Element {
let g = eat2(&cx);
rsx!(cx, "")
}
fn eat2(s: &ScopeState) {}
fn eat(f: &str) {}
fn bleat() {
let blah = String::from("asd");
eat(&blah);
}
@@ -1,40 +0,0 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
fn main() {
let mut dom = VirtualDom::new(parent);
let edits = dom.rebuild();
dbg!(edits);
}
fn parent(cx: Scope) -> Element {
let value = cx.use_hook(|_| String::new());
cx.render(rsx! {
div {
child(
name: value,
h1 {"hi"}
)
}
})
}
#[derive(Props)]
struct ChildProps<'a> {
name: &'a str,
children: Element<'a>,
}
fn child<'a>(cx: Scope<'a, ChildProps<'a>>) -> Element {
cx.render(rsx! {
div {
"it's nested {cx.props.name}",
&cx.props.children
}
})
}
-9
View File
@@ -1,9 +0,0 @@
use dioxus::prelude::*;
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
// very tiny hello world
fn main() {
dioxus::VirtualDom::new(|cx| rsx!(cx, "hello world"));
}
-54
View File
@@ -1,54 +0,0 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
fn main() {
let _ = VirtualDom::new(parent);
}
fn parent(cx: Scope) -> Element {
let value = cx.use_hook(|_| String::new());
cx.render(rsx! {
div {
child( name: value )
}
})
}
#[derive(Props)]
struct ChildProps<'a> {
name: &'a str,
}
fn child<'a>(cx: Scope<'a, ChildProps<'a>>) -> Element {
cx.render(rsx! {
div {
h1 { "it's nested" }
grandchild( name: cx.props.name )
}
})
}
#[derive(Props)]
struct Grandchild<'a> {
name: &'a str,
}
fn grandchild<'a>(cx: Scope<'a, Grandchild>) -> Element<'a> {
cx.render(rsx! {
div { "Hello {cx.props.name}!" }
great_grandchild( name: cx.props.name )
})
}
fn great_grandchild<'a>(cx: Scope<'a, Grandchild>) -> Element<'a> {
cx.render(rsx! {
div {
h1 { "it's nested" }
}
})
}
+496 -673
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -18,7 +18,7 @@ impl BubbleState {
}
}
/// User Events are events that are shuttled from the renderer into the VirtualDom trhough the scheduler channel.
/// User Events are events that are shuttled from the renderer into the VirtualDom through the scheduler channel.
///
/// These events will be passed to the appropriate Element given by `mounted_dom_id` and then bubbled up through the tree
/// where each listener is checked and fired if the event name matches.
-1
View File
@@ -12,7 +12,6 @@ pub(crate) mod util;
pub(crate) mod virtual_dom;
pub(crate) mod innerlude {
pub(crate) use crate::diff::*;
pub use crate::events::*;
pub use crate::lazynodes::*;
pub use crate::mutations::*;
+8
View File
@@ -143,6 +143,10 @@ impl<'a> Mutations<'a> {
self.edits.push(InsertBefore { n, root });
}
pub(crate) fn append_children(&mut self, n: u32) {
self.edits.push(AppendChildren { many: n });
}
// Remove Nodes from the dom
pub(crate) fn remove(&mut self, id: u64) {
self.edits.push(Remove { root: id });
@@ -217,6 +221,10 @@ impl<'a> Mutations<'a> {
let name = attribute.name;
self.edits.push(RemoveAttribute { name, root });
}
pub(crate) fn mark_dirty_scope(&mut self, scope: ScopeId) {
self.dirty_scopes.insert(scope);
}
}
// refs are only assigned once
+30 -25
View File
@@ -4,7 +4,7 @@
//! cheap and *very* fast to construct - building a full tree should be quick.
use crate::{
innerlude::{Element, Properties, Scope, ScopeId, ScopeState},
innerlude::{ComponentPtr, Element, Properties, Scope, ScopeId, ScopeState},
lazynodes::LazyNodes,
AnyEvent, Component,
};
@@ -21,7 +21,7 @@ use std::{
/// - the `rsx!` macro
/// - the [`NodeFactory`] API
pub enum VNode<'src> {
/// Text VNodes simply bump-allocated (or static) string slices
/// Text VNodes are simply bump-allocated (or static) string slices
///
/// # Example
///
@@ -147,13 +147,6 @@ impl<'src> VNode<'src> {
}
}
pub(crate) fn children(&self) -> &[VNode<'src>] {
match &self {
VNode::Fragment(f) => f.children,
_ => &[],
}
}
// Create an "owned" version of the vnode.
pub fn decouple(&self) -> VNode<'src> {
match *self {
@@ -175,13 +168,21 @@ impl Debug for VNode<'_> {
.field("key", &el.key)
.field("attrs", &el.attributes)
.field("children", &el.children)
.field("id", &el.id)
.finish(),
VNode::Text(t) => write!(s, "VNode::VText {{ text: {} }}", t.text),
VNode::Placeholder(_) => write!(s, "VNode::VPlaceholder"),
VNode::Placeholder(t) => write!(s, "VNode::VPlaceholder {{ id: {:?} }}", t.id),
VNode::Fragment(frag) => {
write!(s, "VNode::VFragment {{ children: {:?} }}", frag.children)
}
VNode::Component(comp) => write!(s, "VNode::VComponent {{ fc: {:?}}}", comp.user_fc),
VNode::Component(comp) => s
.debug_struct("VNode::VComponent")
.field("name", &comp.fn_name)
.field("fnptr", &comp.user_fc)
.field("key", &comp.key)
.field("scope", &comp.scope)
.field("originator", &comp.originator)
.finish(),
}
}
}
@@ -352,30 +353,31 @@ type ExternalListenerCallback<'bump, T> = BumpBox<'bump, dyn FnMut(T) + 'bump>;
///
/// ```
pub struct EventHandler<'bump, T = ()> {
pub callback: &'bump RefCell<Option<ExternalListenerCallback<'bump, T>>>,
pub callback: RefCell<Option<ExternalListenerCallback<'bump, T>>>,
}
impl<'a, T> Default for EventHandler<'a, T> {
fn default() -> Self {
Self {
callback: RefCell::new(None),
}
}
}
impl<T> EventHandler<'_, T> {
/// Call this event handler with the appropriate event type
pub fn call(&self, event: T) {
if let Some(callback) = self.callback.borrow_mut().as_mut() {
callback(event);
}
}
/// Forcibly drop the internal handler callback, releasing memory
pub fn release(&self) {
self.callback.replace(None);
}
}
impl<T> Copy for EventHandler<'_, T> {}
impl<T> Clone for EventHandler<'_, T> {
fn clone(&self) -> Self {
Self {
callback: self.callback,
}
}
}
/// Virtual Components for custom user-defined components
/// Only supports the functional syntax
pub struct VComponent<'src> {
@@ -383,7 +385,8 @@ pub struct VComponent<'src> {
pub originator: ScopeId,
pub scope: Cell<Option<ScopeId>>,
pub can_memoize: bool,
pub user_fc: *const (),
pub user_fc: ComponentPtr,
pub fn_name: &'static str,
pub props: RefCell<Option<Box<dyn AnyProps + 'src>>>,
}
@@ -405,7 +408,7 @@ impl<P> AnyProps for VComponentProps<P> {
}
// Safety:
// this will downcat the other ptr as our swallowed type!
// this will downcast the other ptr as our swallowed type!
// you *must* make this check *before* calling this method
// if your functions are not the same, then you will downcast a pointer into a different type (UB)
unsafe fn memoize(&self, other: &dyn AnyProps) -> bool {
@@ -548,6 +551,7 @@ impl<'a> NodeFactory<'a> {
component: fn(Scope<'a, P>) -> Element,
props: P,
key: Option<Arguments>,
fn_name: &'static str,
) -> VNode<'a>
where
P: Properties + 'a,
@@ -556,8 +560,9 @@ impl<'a> NodeFactory<'a> {
key: key.map(|f| self.raw_text(f).0),
scope: Default::default(),
can_memoize: P::IS_STATIC,
user_fc: component as *const (),
user_fc: component as ComponentPtr,
originator: self.scope.scope_id(),
fn_name,
props: RefCell::new(Some(Box::new(VComponentProps {
// local_props: RefCell::new(Some(props)),
// heap_props: RefCell::new(None),
@@ -677,7 +682,7 @@ impl<'a> NodeFactory<'a> {
pub fn event_handler<T>(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> {
let handler: &mut dyn FnMut(T) = self.bump.alloc(f);
let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) };
let callback = self.bump.alloc(RefCell::new(Some(caller)));
let callback = RefCell::new(Some(caller));
EventHandler { callback }
}
}
+125 -76
View File
@@ -13,7 +13,9 @@ use std::{
rc::Rc,
};
pub(crate) type FcSlot = *const ();
/// for traceability, we use the raw fn pointer to identify the function
/// we also get the component name, but that's not necessarily unique in the app
pub(crate) type ComponentPtr = *mut std::os::raw::c_void;
pub(crate) struct Heuristic {
hook_arena_size: usize,
@@ -28,7 +30,7 @@ pub(crate) struct ScopeArena {
pub scope_gen: Cell<usize>,
pub bump: Bump,
pub scopes: RefCell<FxHashMap<ScopeId, *mut ScopeState>>,
pub heuristics: RefCell<FxHashMap<FcSlot, Heuristic>>,
pub heuristics: RefCell<FxHashMap<ComponentPtr, Heuristic>>,
pub free_scopes: RefCell<Vec<*mut ScopeState>>,
pub nodes: RefCell<Slab<*const VNode<'static>>>,
pub tasks: Rc<TaskQueue>,
@@ -70,7 +72,7 @@ impl ScopeArena {
}
/// Safety:
/// - Obtaining a mutable refernece to any Scope is unsafe
/// - Obtaining a mutable reference to any Scope is unsafe
/// - Scopes use interior mutability when sharing data into components
pub(crate) fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
unsafe { self.scopes.borrow().get(&id).map(|f| &**f) }
@@ -82,7 +84,7 @@ impl ScopeArena {
pub(crate) fn new_with_key(
&self,
fc_ptr: *const (),
fc_ptr: ComponentPtr,
vcomp: Box<dyn AnyProps>,
parent_scope: Option<ScopeId>,
container: ElementId,
@@ -94,14 +96,14 @@ impl ScopeArena {
// Get the height of the scope
let height = parent_scope
.map(|id| self.get_scope(id).map(|scope| scope.height))
.map(|id| self.get_scope(id).map(|scope| scope.height + 1))
.flatten()
.unwrap_or_default();
let parent_scope = parent_scope.map(|f| self.get_scope_raw(f)).flatten();
/*
This scopearena aggressively reuse old scopes when possible.
This scopearena aggressively reuses old scopes when possible.
We try to minimize the new allocations for props/arenas.
However, this will probably lead to some sort of fragmentation.
@@ -110,31 +112,62 @@ impl ScopeArena {
if let Some(old_scope) = self.free_scopes.borrow_mut().pop() {
// reuse the old scope
let scope = unsafe { &mut *old_scope };
scope.props.get_mut().replace(vcomp);
scope.container = container;
scope.our_arena_idx = new_scope_id;
scope.parent_scope = parent_scope;
scope.height = height;
scope.fnptr = fc_ptr;
scope.props.get_mut().replace(vcomp);
scope.subtree.set(subtree);
scope.our_arena_idx = new_scope_id;
scope.container = container;
scope.frames[0].reset();
scope.frames[1].reset();
scope.shared_contexts.get_mut().clear();
scope.items.get_mut().listeners.clear();
scope.items.get_mut().borrowed_props.clear();
scope.hook_idx.set(0);
scope.hook_vals.get_mut().clear();
let any_item = self.scopes.borrow_mut().insert(new_scope_id, scope);
debug_assert!(any_item.is_none());
} else {
// else create a new scope
let (node_capacity, hook_capacity) = self
.heuristics
.borrow()
.get(&fc_ptr)
.map(|h| (h.node_arena_size, h.hook_arena_size))
.unwrap_or_default();
self.scopes.borrow_mut().insert(
new_scope_id,
self.bump.alloc(ScopeState::new(
height,
self.bump.alloc(ScopeState {
container,
new_scope_id,
our_arena_idx: new_scope_id,
parent_scope,
vcomp,
self.tasks.clone(),
self.heuristics
.borrow()
.get(&fc_ptr)
.map(|h| (h.node_arena_size, h.hook_arena_size))
.unwrap_or_default(),
)),
height,
fnptr: fc_ptr,
props: RefCell::new(Some(vcomp)),
frames: [BumpFrame::new(node_capacity), BumpFrame::new(node_capacity)],
// todo: subtrees
subtree: Cell::new(0),
is_subtree_root: Cell::new(false),
generation: 0.into(),
tasks: self.tasks.clone(),
shared_contexts: Default::default(),
items: RefCell::new(SelfReferentialItems {
listeners: Default::default(),
borrowed_props: Default::default(),
}),
hook_arena: Bump::new(),
hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
hook_idx: Default::default(),
}),
);
}
@@ -189,8 +222,6 @@ impl ScopeArena {
/// This also makes sure that drop order is consistent and predictable. All resources that rely on being dropped will
/// be dropped.
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
log::trace!("Ensuring drop safety for scope {:?}", scope_id);
if let Some(scope) = self.get_scope(scope_id) {
let mut items = scope.items.borrow_mut();
@@ -198,13 +229,9 @@ impl ScopeArena {
// run the hooks (which hold an &mut Reference)
// recursively call ensure_drop_safety on all children
items.borrowed_props.drain(..).for_each(|comp| {
let scope_id = comp
.scope
.get()
.expect("VComponents should be associated with a valid Scope");
self.ensure_drop_safety(scope_id);
if let Some(scope_id) = comp.scope.get() {
self.ensure_drop_safety(scope_id);
}
drop(comp.props.take());
});
@@ -220,18 +247,18 @@ impl ScopeArena {
// Cycle to the next frame and then reset it
// This breaks any latent references, invalidating every pointer referencing into it.
// Remove all the outdated listeners
log::trace!("Running scope {:?}", id);
self.ensure_drop_safety(id);
// todo: we *know* that this is aliased by the contents of the scope itself
let scope = unsafe { &mut *self.get_scope_raw(id).expect("could not find scope") };
log::trace!("running scope {:?} symbol: {:?}", id, scope.fnptr);
// Safety:
// - We dropped the listeners, so no more &mut T can be used while these are held
// - All children nodes that rely on &mut T are replaced with a new reference
scope.hook_idx.set(0);
// book keeping to ensure safety around the borrowed data
{
// Safety:
// - We've dropped all references to the wip bump frame with "ensure_drop_safety"
@@ -244,8 +271,6 @@ impl ScopeArena {
debug_assert!(items.borrowed_props.is_empty());
}
// safety: this is definitely not dropped
/*
If the component returns None, then we fill in a placeholder node. This will wipe what was there.
An alternate approach is to leave the Real Dom the same, but that can lead to safety issues and a lot more checks.
@@ -287,14 +312,13 @@ impl ScopeArena {
while let Some(id) = cur_el.take() {
if let Some(el) = nodes.get(id.0) {
log::trace!("Found valid receiver element");
let real_el = unsafe { &**el };
log::debug!("looking for listener on {:?}", real_el);
if let VNode::Element(real_el) = real_el {
for listener in real_el.listeners.borrow().iter() {
if listener.event == event.name {
log::trace!("Found valid receiver event");
log::debug!("calling listener {:?}", listener.event);
if state.canceled.get() {
// stop bubbling if canceled
break;
@@ -424,6 +448,7 @@ pub struct ScopeState {
pub(crate) container: ElementId,
pub(crate) our_arena_idx: ScopeId,
pub(crate) height: u32,
pub(crate) fnptr: ComponentPtr,
// todo: subtrees
pub(crate) is_subtree_root: Cell<bool>,
@@ -452,43 +477,6 @@ pub struct SelfReferentialItems<'a> {
// Public methods exposed to libraries and components
impl ScopeState {
fn new(
height: u32,
container: ElementId,
our_arena_idx: ScopeId,
parent_scope: Option<*mut ScopeState>,
vcomp: Box<dyn AnyProps>,
tasks: Rc<TaskQueue>,
(node_capacity, hook_capacity): (usize, usize),
) -> Self {
ScopeState {
container,
our_arena_idx,
parent_scope,
height,
props: RefCell::new(Some(vcomp)),
frames: [BumpFrame::new(node_capacity), BumpFrame::new(node_capacity)],
// todo: subtrees
subtree: Cell::new(0),
is_subtree_root: Cell::new(false),
generation: 0.into(),
tasks,
shared_contexts: Default::default(),
items: RefCell::new(SelfReferentialItems {
listeners: Default::default(),
borrowed_props: Default::default(),
}),
hook_arena: Bump::new(),
hook_vals: RefCell::new(Vec::with_capacity(hook_capacity)),
hook_idx: Default::default(),
}
}
/// Get the subtree ID that this scope belongs to.
///
/// Each component has its own subtree ID - the root subtree has an ID of 0. This ID is used by the renderer to route
@@ -670,6 +658,60 @@ impl ScopeState {
value
}
/// Provide a context for the root component from anywhere in your app.
///
///
/// # Example
///
/// ```rust, ignore
/// struct SharedState(&'static str);
///
/// static App: Component = |cx| {
/// cx.use_hook(|_| cx.provide_root_context(SharedState("world")));
/// rsx!(cx, Child {})
/// }
///
/// static Child: Component = |cx| {
/// let state = cx.consume_state::<SharedState>();
/// rsx!(cx, div { "hello {state.0}" })
/// }
/// ```
pub fn provide_root_context<T: 'static>(&self, value: T) -> Rc<T> {
let value = Rc::new(value);
// if we *are* the root component, then we can just provide the context directly
if self.scope_id() == ScopeId(0) {
self.shared_contexts
.borrow_mut()
.insert(TypeId::of::<T>(), value.clone())
.map(|f| f.downcast::<T>().ok())
.flatten();
return value;
}
let mut search_parent = self.parent_scope;
while let Some(parent) = search_parent.take() {
let parent = unsafe { &*parent };
if parent.scope_id() == ScopeId(0) {
let exists = parent
.shared_contexts
.borrow_mut()
.insert(TypeId::of::<T>(), value.clone());
if exists.is_some() {
log::warn!("Context already provided to parent scope - replacing it");
}
return value;
}
search_parent = parent.parent_scope;
}
unreachable!("all apps have a root scope")
}
/// Try to retrieve a SharedState with type T from the any parent Scope.
pub fn consume_context<T: 'static>(&self) -> Option<Rc<T>> {
if let Some(shared) = self.shared_contexts.borrow().get(&TypeId::of::<T>()) {
@@ -700,6 +742,11 @@ impl ScopeState {
self.tasks.push_fut(fut)
}
/// Spawns the future but does not return the TaskId
pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
self.push_future(fut);
}
// todo: attach some state to the future to know if we should poll it
pub fn remove_future(&self, id: TaskId) {
self.tasks.remove_fut(id);
@@ -840,13 +887,15 @@ impl ScopeState {
self.frames[0].reset();
self.frames[1].reset();
// Finally, free up the hook values
self.hook_arena.reset();
// Free up the hook values
self.hook_vals.get_mut().drain(..).for_each(|state| {
let as_mut = unsafe { &mut *state };
let boxed = unsafe { bumpalo::boxed::Box::from_raw(as_mut) };
drop(boxed);
});
// Finally, clear the hook arena
self.hook_arena.reset();
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ use crate::innerlude::*;
pub struct ElementIdIterator<'a> {
vdom: &'a VirtualDom,
// Heuristcally we should never bleed into 5 completely nested fragments/components
// Heuristically we should never bleed into 5 completely nested fragments/components
// Smallvec lets us stack allocate our little stack machine so the vast majority of cases are sane
stack: smallvec::SmallVec<[(u16, &'a VNode<'a>); 5]>,
}
+61 -54
View File
@@ -2,6 +2,7 @@
//!
//! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust.
use crate::diff::DiffState;
use crate::innerlude::*;
use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
use futures_util::{future::poll_fn, StreamExt};
@@ -9,12 +10,12 @@ use fxhash::FxHashSet;
use indexmap::IndexSet;
use std::{collections::VecDeque, iter::FromIterator, task::Poll};
/// A virtual node s ystem that progresses user events and diffs UI trees.
/// A virtual node system that progresses user events and diffs UI trees.
///
///
/// ## Guide
///
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
///
/// ```rust, ignore
/// #[derive(Props, PartialEq)]
@@ -212,7 +213,7 @@ impl VirtualDom {
let scopes = ScopeArena::new(channel.0.clone());
scopes.new_with_key(
root as *const _,
root as ComponentPtr,
Box::new(VComponentProps {
props: root_props,
memo: |_a, _b| unreachable!("memo on root will neve be run"),
@@ -233,7 +234,7 @@ impl VirtualDom {
/// Get the [`Scope`] for the root component.
///
/// This is useful for traversing the tree from the root for heuristics or alternsative renderers that use Dioxus
/// This is useful for traversing the tree from the root for heuristics or alternative renderers that use Dioxus
/// directly.
///
/// This method is equivalent to calling `get_scope(ScopeId(0))`
@@ -448,6 +449,7 @@ impl VirtualDom {
/// apply_mutations(mutations);
/// }
/// ```
#[allow(unused)]
pub fn work_with_deadline(&mut self, mut deadline: impl FnMut() -> bool) -> Vec<Mutations> {
let mut committed_mutations = vec![];
@@ -467,36 +469,41 @@ impl VirtualDom {
h1.cmp(&h2).reverse()
});
log::debug!("dirty_scopes: {:?}", self.dirty_scopes);
if let Some(scopeid) = self.dirty_scopes.pop() {
if !ran_scopes.contains(&scopeid) {
ran_scopes.insert(scopeid);
self.scopes.run_scope(scopeid);
let (old, new) = (self.scopes.wip_head(scopeid), self.scopes.fin_head(scopeid));
diff_state.stack.push(DiffInstruction::Diff { new, old });
diff_state.stack.scope_stack.push(scopeid);
diff_state.diff_scope(scopeid);
let scope = scopes.get_scope(scopeid).unwrap();
diff_state.stack.element_stack.push(scope.container);
let DiffState { mutations, .. } = diff_state;
log::debug!("succesffuly resolved scopes {:?}", mutations.dirty_scopes);
for scope in &mutations.dirty_scopes {
self.dirty_scopes.remove(scope);
}
committed_mutations.push(mutations);
// todo: pause the diff machine
// if diff_state.work(&mut deadline) {
// let DiffState { mutations, .. } = diff_state;
// for scope in &mutations.dirty_scopes {
// self.dirty_scopes.remove(scope);
// }
// committed_mutations.push(mutations);
// } else {
// // leave the work in an incomplete state
// //
// // todo: we should store the edits and re-apply them later
// // for now, we just dump the work completely (threadsafe)
// return committed_mutations;
// }
}
}
if diff_state.work(&mut deadline) {
let DiffState { mutations, .. } = diff_state;
for scope in &mutations.dirty_scopes {
self.dirty_scopes.remove(scope);
}
committed_mutations.push(mutations);
} else {
// leave the work in an incomplete state
//
// todo: we should store the edits and re-apply them later
// for now, we just dump the work completely (threadsafe)
return committed_mutations;
}
}
committed_mutations
@@ -524,13 +531,15 @@ impl VirtualDom {
let mut diff_state = DiffState::new(&self.scopes);
self.scopes.run_scope(scope_id);
diff_state
.stack
.create_node(self.scopes.fin_head(scope_id), MountType::Append);
diff_state.stack.element_stack.push(ElementId(0));
diff_state.stack.scope_stack.push(scope_id);
diff_state.work(|| false);
diff_state.element_stack.push(ElementId(0));
diff_state.scope_stack.push(scope_id);
let node = self.scopes.fin_head(scope_id);
let created = diff_state.create_node(node);
diff_state.mutations.append_children(created as u32);
self.dirty_scopes.clear();
assert!(self.dirty_scopes.is_empty());
@@ -577,12 +586,11 @@ impl VirtualDom {
);
diff_machine.force_diff = true;
diff_machine.stack.push(DiffInstruction::Diff { old, new });
diff_machine.stack.scope_stack.push(scope_id);
diff_machine.scope_stack.push(scope_id);
let scope = diff_machine.scopes.get_scope(scope_id).unwrap();
diff_machine.stack.element_stack.push(scope.container);
diff_machine.work(|| false);
diff_machine.element_stack.push(scope.container);
diff_machine.diff_node(old, new);
diff_machine.mutations
}
@@ -618,13 +626,13 @@ impl VirtualDom {
///
/// let dom = VirtualDom::new(Base);
/// let nodes = dom.render_nodes(rsx!("div"));
/// ```
/// ```
pub fn diff_vnodes<'a>(&'a self, old: &'a VNode<'a>, new: &'a VNode<'a>) -> Mutations<'a> {
let mut machine = DiffState::new(&self.scopes);
machine.stack.push(DiffInstruction::Diff { new, old });
machine.stack.element_stack.push(ElementId(0));
machine.stack.scope_stack.push(ScopeId(0));
machine.work(|| false);
machine.element_stack.push(ElementId(0));
machine.scope_stack.push(ScopeId(0));
machine.diff_node(old, new);
machine.mutations
}
@@ -643,11 +651,11 @@ impl VirtualDom {
/// ```
pub fn create_vnodes<'a>(&'a self, nodes: LazyNodes<'a, '_>) -> Mutations<'a> {
let mut machine = DiffState::new(&self.scopes);
machine.stack.element_stack.push(ElementId(0));
machine
.stack
.create_node(self.render_vnodes(nodes), MountType::Append);
machine.work(|| false);
machine.scope_stack.push(ScopeId(0));
machine.element_stack.push(ElementId(0));
let node = self.render_vnodes(nodes);
let created = machine.create_node(node);
machine.mutations.append_children(created as u32);
machine.mutations
}
@@ -672,16 +680,15 @@ impl VirtualDom {
let (old, new) = (self.render_vnodes(left), self.render_vnodes(right));
let mut create = DiffState::new(&self.scopes);
create.stack.scope_stack.push(ScopeId(0));
create.stack.element_stack.push(ElementId(0));
create.stack.create_node(old, MountType::Append);
create.work(|| false);
create.scope_stack.push(ScopeId(0));
create.element_stack.push(ElementId(0));
let created = create.create_node(old);
create.mutations.append_children(created as u32);
let mut edit = DiffState::new(&self.scopes);
edit.stack.scope_stack.push(ScopeId(0));
edit.stack.element_stack.push(ElementId(0));
edit.stack.push(DiffInstruction::Diff { old, new });
edit.work(|| false);
edit.scope_stack.push(ScopeId(0));
edit.element_stack.push(ElementId(0));
edit.diff_node(old, new);
(create.mutations, edit.mutations)
}
+1
View File
@@ -0,0 +1 @@
struct_lit_width = 80
+28 -112
View File
@@ -36,18 +36,9 @@ fn test_original_diff() {
assert_eq!(
mutations.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateElement {
root: 2,
tag: "div"
},
CreateTextNode {
root: 3,
text: "Hello, world!"
},
CreateElement { root: 1, tag: "div" },
CreateElement { root: 2, tag: "div" },
CreateTextNode { root: 3, text: "Hello, world!" },
AppendChildren { many: 1 },
AppendChildren { many: 1 },
AppendChildren { many: 1 },
@@ -81,34 +72,13 @@ fn create() {
assert_eq!(
mutations.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateElement {
root: 2,
tag: "div"
},
CreateTextNode {
root: 3,
text: "Hello, world!"
},
CreateElement {
root: 4,
tag: "div"
},
CreateElement {
root: 5,
tag: "div"
},
CreateTextNode {
root: 6,
text: "hello"
},
CreateTextNode {
root: 7,
text: "world"
},
CreateElement { root: 1, tag: "div" },
CreateElement { root: 2, tag: "div" },
CreateTextNode { root: 3, text: "Hello, world!" },
CreateElement { root: 4, tag: "div" },
CreateElement { root: 5, tag: "div" },
CreateTextNode { root: 6, text: "hello" },
CreateTextNode { root: 7, text: "world" },
AppendChildren { many: 2 },
AppendChildren { many: 1 },
AppendChildren { many: 2 },
@@ -135,32 +105,14 @@ fn create_list() {
assert_eq!(
mutations.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateTextNode {
root: 2,
text: "hello"
},
CreateElement { root: 1, tag: "div" },
CreateTextNode { root: 2, text: "hello" },
AppendChildren { many: 1 },
CreateElement {
root: 3,
tag: "div"
},
CreateTextNode {
root: 4,
text: "hello"
},
CreateElement { root: 3, tag: "div" },
CreateTextNode { root: 4, text: "hello" },
AppendChildren { many: 1 },
CreateElement {
root: 5,
tag: "div"
},
CreateTextNode {
root: 6,
text: "hello"
},
CreateElement { root: 5, tag: "div" },
CreateTextNode { root: 6, text: "hello" },
AppendChildren { many: 1 },
AppendChildren { many: 3 },
]
@@ -185,22 +137,10 @@ fn create_simple() {
assert_eq!(
mutations.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateElement {
root: 2,
tag: "div"
},
CreateElement {
root: 3,
tag: "div"
},
CreateElement {
root: 4,
tag: "div"
},
CreateElement { root: 1, tag: "div" },
CreateElement { root: 2, tag: "div" },
CreateElement { root: 3, tag: "div" },
CreateElement { root: 4, tag: "div" },
AppendChildren { many: 4 },
]
);
@@ -235,36 +175,18 @@ fn create_components() {
mutations.edits,
[
CreateElement { root: 1, tag: "h1" },
CreateElement {
root: 2,
tag: "div"
},
CreateTextNode {
root: 3,
text: "abc1"
},
CreateElement { root: 2, tag: "div" },
CreateTextNode { root: 3, text: "abc1" },
AppendChildren { many: 1 },
CreateElement { root: 4, tag: "p" },
CreateElement { root: 5, tag: "h1" },
CreateElement {
root: 6,
tag: "div"
},
CreateTextNode {
root: 7,
text: "abc2"
},
CreateElement { root: 6, tag: "div" },
CreateTextNode { root: 7, text: "abc2" },
AppendChildren { many: 1 },
CreateElement { root: 8, tag: "p" },
CreateElement { root: 9, tag: "h1" },
CreateElement {
root: 10,
tag: "div"
},
CreateTextNode {
root: 11,
text: "abc3"
},
CreateElement { root: 10, tag: "div" },
CreateTextNode { root: 11, text: "abc3" },
AppendChildren { many: 1 },
CreateElement { root: 12, tag: "p" },
AppendChildren { many: 9 },
@@ -285,14 +207,8 @@ fn anchors() {
assert_eq!(
mutations.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateTextNode {
root: 2,
text: "hello"
},
CreateElement { root: 1, tag: "div" },
CreateTextNode { root: 2, text: "hello" },
AppendChildren { many: 1 },
CreatePlaceholder { root: 3 },
AppendChildren { many: 2 },
+60 -196
View File
@@ -1,4 +1,5 @@
#![allow(unused, non_upper_case_globals)]
//! Diffing Tests
//!
//! These tests only verify that the diffing algorithm works properly for single components.
@@ -31,26 +32,14 @@ fn html_and_rsx_generate_the_same_output() {
assert_eq!(
create.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateTextNode {
root: 2,
text: "Hello world"
},
CreateElement { root: 1, tag: "div" },
CreateTextNode { root: 2, text: "Hello world" },
AppendChildren { many: 1 },
AppendChildren { many: 1 },
]
);
assert_eq!(
change.edits,
[SetText {
text: "Goodbye world",
root: 2
},]
);
assert_eq!(change.edits, [SetText { text: "Goodbye world", root: 2 },]);
}
/// Should result in 3 elements on the stack
@@ -67,32 +56,14 @@ fn fragments_create_properly() {
assert_eq!(
create.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateTextNode {
root: 2,
text: "Hello a"
},
CreateElement { root: 1, tag: "div" },
CreateTextNode { root: 2, text: "Hello a" },
AppendChildren { many: 1 },
CreateElement {
root: 3,
tag: "div"
},
CreateTextNode {
root: 4,
text: "Hello b"
},
CreateElement { root: 3, tag: "div" },
CreateTextNode { root: 4, text: "Hello b" },
AppendChildren { many: 1 },
CreateElement {
root: 5,
tag: "div"
},
CreateTextNode {
root: 6,
text: "Hello c"
},
CreateElement { root: 5, tag: "div" },
CreateTextNode { root: 6, text: "Hello c" },
AppendChildren { many: 1 },
AppendChildren { many: 3 },
]
@@ -116,10 +87,7 @@ fn empty_fragments_create_anchors() {
assert_eq!(
change.edits,
[
CreateElement {
root: 2,
tag: "div"
},
CreateElement { root: 2, tag: "div" },
ReplaceWith { m: 1, root: 1 }
]
);
@@ -138,29 +106,15 @@ fn empty_fragments_create_many_anchors() {
create.edits,
[CreatePlaceholder { root: 1 }, AppendChildren { many: 1 }]
);
assert_eq!(
change.edits,
[
CreateElement {
root: 2,
tag: "div"
},
CreateElement {
root: 3,
tag: "div"
},
CreateElement {
root: 4,
tag: "div"
},
CreateElement {
root: 5,
tag: "div"
},
CreateElement {
root: 6,
tag: "div"
},
CreateElement { root: 2, tag: "div" },
CreateElement { root: 3, tag: "div" },
CreateElement { root: 4, tag: "div" },
CreateElement { root: 5, tag: "div" },
CreateElement { root: 6, tag: "div" },
ReplaceWith { m: 5, root: 1 }
]
);
@@ -188,32 +142,14 @@ fn empty_fragments_create_anchors_with_many_children() {
assert_eq!(
change.edits,
[
CreateElement {
tag: "div",
root: 2,
},
CreateTextNode {
text: "hello: 0",
root: 3
},
CreateElement { tag: "div", root: 2 },
CreateTextNode { text: "hello: 0", root: 3 },
AppendChildren { many: 1 },
CreateElement {
tag: "div",
root: 4,
},
CreateTextNode {
text: "hello: 1",
root: 5
},
CreateElement { tag: "div", root: 4 },
CreateTextNode { text: "hello: 1", root: 5 },
AppendChildren { many: 1 },
CreateElement {
tag: "div",
root: 6,
},
CreateTextNode {
text: "hello: 2",
root: 7
},
CreateElement { tag: "div", root: 6 },
CreateTextNode { text: "hello: 2", root: 7 },
AppendChildren { many: 1 },
ReplaceWith { root: 1, m: 3 }
]
@@ -236,23 +172,11 @@ fn many_items_become_fragment() {
assert_eq!(
create.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateTextNode {
text: "hello",
root: 2
},
CreateElement { root: 1, tag: "div" },
CreateTextNode { text: "hello", root: 2 },
AppendChildren { many: 1 },
CreateElement {
root: 3,
tag: "div"
},
CreateTextNode {
text: "hello",
root: 4
},
CreateElement { root: 3, tag: "div" },
CreateTextNode { text: "hello", root: 4 },
AppendChildren { many: 1 },
AppendChildren { many: 2 },
]
@@ -315,7 +239,7 @@ fn two_fragments_with_differrent_elements_are_differet() {
// replace the divs with new h1s
CreateElement { tag: "h1", root: 7 },
ReplaceWith { root: 1, m: 1 },
CreateElement { tag: "h1", root: 8 },
CreateElement { tag: "h1", root: 1 }, // notice how 1 gets re-used
ReplaceWith { root: 2, m: 1 },
]
);
@@ -339,39 +263,27 @@ fn two_fragments_with_differrent_elements_are_differet_shorter() {
assert_eq!(
create.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateElement {
root: 2,
tag: "div"
},
CreateElement {
root: 3,
tag: "div"
},
CreateElement {
root: 4,
tag: "div"
},
CreateElement {
root: 5,
tag: "div"
},
CreateElement { root: 1, tag: "div" },
CreateElement { root: 2, tag: "div" },
CreateElement { root: 3, tag: "div" },
CreateElement { root: 4, tag: "div" },
CreateElement { root: 5, tag: "div" },
CreateElement { root: 6, tag: "p" },
AppendChildren { many: 6 },
]
);
// note: key reuse is always the last node that got used
// slab maintains a linked list, essentially
assert_eq!(
change.edits,
[
Remove { root: 3 },
Remove { root: 4 },
Remove { root: 5 },
CreateElement { root: 7, tag: "h1" },
ReplaceWith { root: 1, m: 1 },
CreateElement { root: 8, tag: "h1" },
CreateElement { root: 5, tag: "h1" }, // 3 gets reused
ReplaceWith { root: 1, m: 1 }, // 1 gets deleted
CreateElement { root: 1, tag: "h1" }, // 1 gets reused
ReplaceWith { root: 2, m: 1 },
]
);
@@ -395,14 +307,8 @@ fn two_fragments_with_same_elements_are_differet() {
assert_eq!(
create.edits,
[
CreateElement {
root: 1,
tag: "div"
},
CreateElement {
root: 2,
tag: "div"
},
CreateElement { root: 1, tag: "div" },
CreateElement { root: 2, tag: "div" },
CreateElement { root: 3, tag: "p" },
AppendChildren { many: 3 },
]
@@ -410,18 +316,9 @@ fn two_fragments_with_same_elements_are_differet() {
assert_eq!(
change.edits,
[
CreateElement {
root: 4,
tag: "div"
},
CreateElement {
root: 5,
tag: "div"
},
CreateElement {
root: 6,
tag: "div"
},
CreateElement { root: 4, tag: "div" },
CreateElement { root: 5, tag: "div" },
CreateElement { root: 6, tag: "div" },
InsertAfter { root: 2, n: 3 },
]
);
@@ -628,14 +525,8 @@ fn keyed_diffing_additions() {
assert_eq!(
change.edits,
[
CreateElement {
root: 6,
tag: "div"
},
CreateElement {
root: 7,
tag: "div"
},
CreateElement { root: 6, tag: "div" },
CreateElement { root: 7, tag: "div" },
InsertAfter { n: 2, root: 5 }
]
);
@@ -663,14 +554,8 @@ fn keyed_diffing_additions_and_moves_on_ends() {
change.edits,
[
// create 11, 12
CreateElement {
tag: "div",
root: 5
},
CreateElement {
tag: "div",
root: 6
},
CreateElement { tag: "div", root: 5 },
CreateElement { tag: "div", root: 6 },
InsertAfter { root: 3, n: 2 },
// move 7 to the front
PushRoot { root: 4 },
@@ -684,13 +569,13 @@ fn keyed_diffing_additions_and_moves_in_middle() {
let dom = new_dom();
let left = rsx!({
[/**/ 4, 5, 6, 7 /**/].iter().map(|f| {
[/**/ 1, 2, 3, 4 /**/].iter().map(|f| {
rsx! { div { key: "{f}" }}
})
});
let right = rsx!({
[/**/ 7, 4, 13, 17, 5, 11, 12, 6 /**/].iter().map(|f| {
[/**/ 4, 1, 7, 8, 2, 5, 6, 3 /**/].iter().map(|f| {
rsx! { div { key: "{f}" }}
})
});
@@ -701,26 +586,14 @@ fn keyed_diffing_additions_and_moves_in_middle() {
assert_eq!(
change.edits,
[
// create 13, 17
CreateElement {
tag: "div",
root: 5
},
CreateElement {
tag: "div",
root: 6
},
InsertBefore { root: 2, n: 2 },
// create 11, 12
CreateElement {
tag: "div",
root: 7
},
CreateElement {
tag: "div",
root: 8
},
// create 5, 6
CreateElement { tag: "div", root: 5 },
CreateElement { tag: "div", root: 6 },
InsertBefore { root: 3, n: 2 },
// create 7, 8
CreateElement { tag: "div", root: 7 },
CreateElement { tag: "div", root: 8 },
InsertBefore { root: 2, n: 2 },
// move 7
PushRoot { root: 4 },
InsertBefore { root: 1, n: 1 }
@@ -756,16 +629,10 @@ fn controlled_keyed_diffing_out_of_order() {
// remove 7
// create 9 and insert before 6
CreateElement {
root: 5,
tag: "div"
},
CreateElement { root: 5, tag: "div" },
InsertBefore { n: 1, root: 3 },
// create 0 and insert before 5
CreateElement {
root: 6,
tag: "div"
},
CreateElement { root: 6, tag: "div" },
InsertBefore { n: 1, root: 2 },
]
);
@@ -792,10 +659,7 @@ fn controlled_keyed_diffing_out_of_order_max_test() {
assert_eq!(
changes.edits,
[
CreateElement {
root: 6,
tag: "div"
},
CreateElement { root: 6, tag: "div" },
InsertBefore { n: 1, root: 3 },
PushRoot { root: 4 },
InsertBefore { n: 1, root: 1 },
+4 -16
View File
@@ -42,14 +42,8 @@ fn test_early_abort() {
assert_eq!(
edits.edits,
[
CreateElement {
tag: "div",
root: 1,
},
CreateTextNode {
text: "Hello, world!",
root: 2,
},
CreateElement { tag: "div", root: 1 },
CreateTextNode { text: "Hello, world!", root: 2 },
AppendChildren { many: 1 },
AppendChildren { many: 1 },
]
@@ -65,14 +59,8 @@ fn test_early_abort() {
assert_eq!(
edits.edits,
[
CreateElement {
tag: "div",
root: 2,
},
CreateTextNode {
text: "Hello, world!",
root: 4,
},
CreateElement { tag: "div", root: 1 }, // keys get reused
CreateTextNode { text: "Hello, world!", root: 2 }, // keys get reused
AppendChildren { many: 1 },
ReplaceWith { root: 3, m: 1 },
]
+39 -81
View File
@@ -1,4 +1,5 @@
#![allow(unused, non_upper_case_globals)]
#![allow(non_snake_case)]
//! Tests for the lifecycle of components.
use dioxus::prelude::*;
@@ -27,12 +28,7 @@ fn manual_diffing() {
};
let value = Arc::new(Mutex::new("Hello"));
let mut dom = VirtualDom::new_with_props(
App,
AppProps {
value: value.clone(),
},
);
let mut dom = VirtualDom::new_with_props(App, AppProps { value: value.clone() });
let _ = dom.rebuild();
@@ -45,7 +41,7 @@ fn manual_diffing() {
#[test]
fn events_generate() {
static App: Component = |cx| {
fn app(cx: Scope) -> Element {
let count = cx.use_hook(|_| 0);
let inner = match *count {
@@ -66,7 +62,7 @@ fn events_generate() {
cx.render(inner)
};
let mut dom = VirtualDom::new(App);
let mut dom = VirtualDom::new(app);
let mut channel = dom.get_scheduler_channel();
assert!(dom.has_work());
@@ -74,28 +70,12 @@ fn events_generate() {
assert_eq!(
edits.edits,
[
CreateElement {
tag: "div",
root: 1,
},
NewEventListener {
event_name: "click",
scope: ScopeId(0),
root: 1,
},
CreateElement {
tag: "div",
root: 2,
},
CreateTextNode {
text: "nested",
root: 3,
},
CreateElement { tag: "div", root: 1 },
NewEventListener { event_name: "click", scope: ScopeId(0), root: 1 },
CreateElement { tag: "div", root: 2 },
CreateTextNode { text: "nested", root: 3 },
AppendChildren { many: 1 },
CreateTextNode {
text: "Click me!",
root: 4,
},
CreateTextNode { text: "Click me!", root: 4 },
AppendChildren { many: 2 },
AppendChildren { many: 1 },
]
@@ -104,7 +84,7 @@ fn events_generate() {
#[test]
fn components_generate() {
static App: Component = |cx| {
fn app(cx: Scope) -> Element {
let render_phase = cx.use_hook(|_| 0);
*render_phase += 1;
@@ -121,106 +101,84 @@ fn components_generate() {
})
};
static Child: Component = |cx| {
fn Child(cx: Scope) -> Element {
log::debug!("Running child");
cx.render(rsx! {
h1 {}
})
};
}
let mut dom = VirtualDom::new(App);
let mut dom = VirtualDom::new(app);
let edits = dom.rebuild();
assert_eq!(
edits.edits,
[
CreateTextNode {
text: "Text0",
root: 1,
},
CreateTextNode { text: "Text0", root: 1 },
AppendChildren { many: 1 },
]
);
let edits = dom.hard_diff(ScopeId(0));
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateElement {
tag: "div",
root: 2,
},
CreateElement { tag: "div", root: 2 },
ReplaceWith { root: 1, m: 1 },
]
);
let edits = dom.hard_diff(ScopeId(0));
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateTextNode {
text: "Text2",
root: 3,
},
CreateTextNode { text: "Text2", root: 1 },
ReplaceWith { root: 2, m: 1 },
]
);
let edits = dom.hard_diff(ScopeId(0));
// child {}
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateElement { tag: "h1", root: 4 },
ReplaceWith { root: 3, m: 1 },
CreateElement { tag: "h1", root: 2 },
ReplaceWith { root: 1, m: 1 },
]
);
let edits = dom.hard_diff(ScopeId(0));
// placeholder
assert_eq!(
edits.edits,
[CreatePlaceholder { root: 5 }, ReplaceWith { root: 4, m: 1 },]
dom.hard_diff(ScopeId(0)).edits,
[CreatePlaceholder { root: 1 }, ReplaceWith { root: 2, m: 1 },]
);
let edits = dom.hard_diff(ScopeId(0));
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateTextNode {
text: "text 3",
root: 6,
},
ReplaceWith { root: 5, m: 1 },
CreateTextNode { text: "text 3", root: 2 },
ReplaceWith { root: 1, m: 1 },
]
);
let edits = dom.hard_diff(ScopeId(0));
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateTextNode {
text: "text 0",
root: 7,
},
CreateTextNode {
text: "text 1",
root: 8,
},
ReplaceWith { root: 6, m: 2 },
CreateTextNode { text: "text 0", root: 1 },
CreateTextNode { text: "text 1", root: 3 },
ReplaceWith { root: 2, m: 2 },
]
);
let edits = dom.hard_diff(ScopeId(0));
assert_eq!(
edits.edits,
dom.hard_diff(ScopeId(0)).edits,
[
CreateElement { tag: "h1", root: 9 },
ReplaceWith { root: 7, m: 1 },
Remove { root: 8 },
CreateElement { tag: "h1", root: 2 },
ReplaceWith { root: 1, m: 1 },
Remove { root: 3 },
]
);
}
#[test]
fn component_swap() {
static App: Component = |cx| {
fn app(cx: Scope) -> Element {
let render_phase = cx.use_hook(|_| 0);
*render_phase += 1;
@@ -296,7 +254,7 @@ fn component_swap() {
})
};
let mut dom = VirtualDom::new(App);
let mut dom = VirtualDom::new(app);
let edits = dom.rebuild();
dbg!(&edits);
+111 -6
View File
@@ -1,3 +1,4 @@
#![allow(non_snake_case)]
/*
Stress Miri as much as possible.
@@ -152,12 +153,7 @@ fn free_works_on_root_props() {
}
}
let mut dom = new_dom(
app,
Custom {
val: String::from("asd"),
},
);
let mut dom = new_dom(app, Custom { val: String::from("asd") });
dom.rebuild();
}
@@ -313,3 +309,112 @@ fn leak_thru_children() {
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
}
#[test]
fn test_pass_thru() {
#[inline_props]
fn NavContainer<'a>(cx: Scope, children: Element<'a>) -> Element {
cx.render(rsx! {
header {
nav { children }
}
})
}
fn NavMenu(cx: Scope) -> Element {
rsx!(cx,
NavBrand {}
div {
NavStart {}
NavEnd {}
}
)
}
fn NavBrand(cx: Scope) -> Element {
rsx!(cx, div {})
}
fn NavStart(cx: Scope) -> Element {
rsx!(cx, div {})
}
fn NavEnd(cx: Scope) -> Element {
rsx!(cx, div {})
}
#[inline_props]
fn MainContainer<'a>(
cx: Scope,
nav: Element<'a>,
body: Element<'a>,
footer: Element<'a>,
) -> Element {
cx.render(rsx! {
div {
class: "columns is-mobile",
div {
class: "column is-full",
nav,
body,
footer,
}
}
})
}
fn app(cx: Scope) -> Element {
let nav = cx.render(rsx! {
NavContainer {
NavMenu {}
}
});
let body = cx.render(rsx! {
div {}
});
let footer = cx.render(rsx! {
div {}
});
cx.render(rsx! {
MainContainer {
nav: nav,
body: body,
footer: footer,
}
})
}
let mut dom = new_dom(app, ());
let _ = dom.rebuild();
for _ in 0..40 {
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(1)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(1)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(1)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(2)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(2)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(2)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(3)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(3)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(3)));
dom.work_with_deadline(|| false);
}
}
+107
View File
@@ -0,0 +1,107 @@
#![allow(unused, non_upper_case_globals)]
#![allow(non_snake_case)]
//! Diffing Tests
//!
//! These tests only verify that the diffing algorithm works properly for single components.
//!
//! It does not validated that component lifecycles work properly. This is done in another test file.
use dioxus::{prelude::*, DomEdit, ScopeId};
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
mod test_logging;
fn new_dom() -> VirtualDom {
const IS_LOGGING_ENABLED: bool = false;
test_logging::set_up_logging(IS_LOGGING_ENABLED);
VirtualDom::new(|cx| rsx!(cx, "hi"))
}
use DomEdit::*;
/// Should push the text node onto the stack and modify it
#[test]
fn nested_passthru_creates() {
fn app(cx: Scope) -> Element {
cx.render(rsx! {
Child {
Child {
Child {
div {
"hi"
}
}
}
}
})
};
#[inline_props]
fn Child<'a>(cx: Scope, children: Element<'a>) -> Element {
cx.render(rsx! { children })
};
let mut dom = VirtualDom::new(app);
let mut channel = dom.get_scheduler_channel();
assert!(dom.has_work());
let edits = dom.rebuild();
assert_eq!(
edits.edits,
[
CreateElement { tag: "div", root: 1 },
CreateTextNode { text: "hi", root: 2 },
AppendChildren { many: 1 },
AppendChildren { many: 1 },
]
)
}
/// Should push the text node onto the stack and modify it
#[test]
fn nested_passthru_creates_add() {
fn app(cx: Scope) -> Element {
cx.render(rsx! {
Child {
"1"
Child {
"2"
Child {
"3"
div {
"hi"
}
}
}
}
})
};
#[inline_props]
fn Child<'a>(cx: Scope, children: Element<'a>) -> Element {
cx.render(rsx! {
children
})
};
let mut dom = VirtualDom::new(app);
let mut channel = dom.get_scheduler_channel();
assert!(dom.has_work());
let edits = dom.rebuild();
assert_eq!(
edits.edits,
[
CreateTextNode { text: "1", root: 1 },
CreateTextNode { text: "2", root: 2 },
CreateTextNode { text: "3", root: 3 },
CreateElement { tag: "div", root: 4 },
CreateTextNode { text: "hi", root: 5 },
AppendChildren { many: 1 },
AppendChildren { many: 4 },
]
)
}
+97 -6
View File
@@ -1,6 +1,6 @@
#![allow(unused, non_upper_case_globals)]
#![allow(unused, non_upper_case_globals, non_snake_case)]
use dioxus::{prelude::*, DomEdit, Mutations};
use dioxus::{prelude::*, DomEdit, Mutations, SchedulerMsg, ScopeId};
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
@@ -29,11 +29,102 @@ fn shared_state_test() {
assert_eq!(
edits,
[
CreateTextNode {
root: 1,
text: "Hello, world!"
},
CreateTextNode { root: 1, text: "Hello, world!" },
AppendChildren { many: 1 },
]
);
}
#[test]
fn swap_test() {
struct MySharedState(&'static str);
fn app(cx: Scope) -> Element {
let val = cx.use_hook(|_| 0);
*val += 1;
cx.provide_context(MySharedState("world!"));
let child = match *val % 2 {
0 => rsx!(
Child1 {
Child1 { }
Child2 { }
}
),
_ => rsx!(
Child2 {
Child2 { }
Child2 { }
}
),
};
cx.render(rsx!(
Router {
div { child }
}
))
}
#[inline_props]
fn Router<'a>(cx: Scope, children: Element<'a>) -> Element<'a> {
cx.render(rsx!(div { children }))
}
#[inline_props]
fn Child1<'a>(cx: Scope, children: Element<'a>) -> Element {
let shared = cx.consume_context::<MySharedState>().unwrap();
println!("Child1: {}", shared.0);
cx.render(rsx! {
div {
"{shared.0}",
children
}
})
}
#[inline_props]
fn Child2<'a>(cx: Scope, children: Element<'a>) -> Element {
let shared = cx.consume_context::<MySharedState>().unwrap();
println!("Child2: {}", shared.0);
cx.render(rsx! {
h1 {
"{shared.0}",
children
}
})
}
let mut dom = VirtualDom::new(app);
let Mutations { edits, .. } = dom.rebuild();
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(1)));
// dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(2)));
// dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(3)));
// dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
// dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
// dom.work_with_deadline(|| false);
// dom.handle_message(SchedulerMsg::Immediate(ScopeId(0)));
// dom.work_with_deadline(|| false);
}
+2 -8
View File
@@ -68,15 +68,9 @@ fn conditional_rendering() {
mutations.edits,
[
CreateElement { root: 1, tag: "h1" },
CreateTextNode {
root: 2,
text: "hello"
},
CreateTextNode { root: 2, text: "hello" },
AppendChildren { many: 1 },
CreateElement {
root: 3,
tag: "span"
},
CreateElement { root: 3, tag: "span" },
CreateTextNode { root: 4, text: "a" },
AppendChildren { many: 1 },
CreatePlaceholder { root: 5 },
+89 -5
View File
@@ -5,6 +5,76 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Documentation
- <csr-id-a239d2ba6ac7f1f3d09de16c022ce8ca52cf0f63/> fix web doc example and use &mut for builders everywhere
### New Features
- <csr-id-430cde7068d308f2783e33d278fd0c0efa659c1b/> default asset server
- <csr-id-95e93ed0bcf6c69990f4cf3c6448b2bf5da96c36/> remove dioxus id on non-event elements
- <csr-id-eb138848ec7a8978f0ed7c717374684d2315dc03/> also hide placeholder node
- <csr-id-05331ddd8033f6997d4916179b62f4d62f832988/> wire up both desktop and web
- <csr-id-8f4aa84f1a4f2443b34d81ee42490564e168de53/> bool attr white list
- <csr-id-5bf6c96f9fed04de949403202bafcbeadb5d2030/> setup a typescript build
### Bug Fixes
- <csr-id-22308eb26a9ea48b14f5f5abb833aa90a4e3fc40/> custom protocol receiver type
- <csr-id-6bc45b1c5064a4e2b04d452c52a8167ad179691e/> clippy
- <csr-id-bad36162af764291f5a031b6233d151f61d745a4/> wry pathing
- <csr-id-be614e6535e6e13e6ff93e9c6a171c1c002e6b01/> cursor jumping and use set instead of lsit
- <csr-id-92561612c727e73356d7d36e16af39aacf02a56d/> format code
- <csr-id-2073b400df55f0c6d8bed7371b2313be6c064e6e/> check `href` null
- <csr-id-21232285d9d84168d9003969ddd254fc22951e4b/> add exclusion list
- <csr-id-327f9015481809d8e5b9e69f26202e8d66dd198e/> check `href` null
- <csr-id-8089023a6c3a54957af9c9c05c9dee6088b059ef/> prevent `submit` default
### Commit Statistics
<csr-read-only-do-not-edit/>
- 26 commits contributed to the release over the course of 11 calendar days.
- 17 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- custom protocol receiver type ([`22308eb`](https://github.comgit//DioxusLabs/dioxus/commit/22308eb26a9ea48b14f5f5abb833aa90a4e3fc40))
- default asset server ([`430cde7`](https://github.comgit//DioxusLabs/dioxus/commit/430cde7068d308f2783e33d278fd0c0efa659c1b))
- fix web doc example and use &mut for builders everywhere ([`a239d2b`](https://github.comgit//DioxusLabs/dioxus/commit/a239d2ba6ac7f1f3d09de16c022ce8ca52cf0f63))
- Merge pull request #111 from DioxusLabs/jk/props-attrs ([`0369fe7`](https://github.comgit//DioxusLabs/dioxus/commit/0369fe72fb247409da300a54ef11ba9155d0efb3))
- clippy ([`6bc45b1`](https://github.comgit//DioxusLabs/dioxus/commit/6bc45b1c5064a4e2b04d452c52a8167ad179691e))
- Merge pull request #113 from DioxusLabs/jk/desktop-cursor-jump ([`20a2940`](https://github.comgit//DioxusLabs/dioxus/commit/20a29409b22510b001fdbee349724adb7b44d401))
- wry pathing ([`bad3616`](https://github.comgit//DioxusLabs/dioxus/commit/bad36162af764291f5a031b6233d151f61d745a4))
- remove dioxus id on non-event elements ([`95e93ed`](https://github.comgit//DioxusLabs/dioxus/commit/95e93ed0bcf6c69990f4cf3c6448b2bf5da96c36))
- also hide placeholder node ([`eb13884`](https://github.comgit//DioxusLabs/dioxus/commit/eb138848ec7a8978f0ed7c717374684d2315dc03))
- drag and drop support ([`9ae981a`](https://github.comgit//DioxusLabs/dioxus/commit/9ae981a1af4b5474ce16e27e070794d59128c12a))
- feat(events:focus): add missing `onfocusin` event ([`007d06d`](https://github.comgit//DioxusLabs/dioxus/commit/007d06d602f1adfaa51c87ec89b2afe90d8cdef9))
- cursor jumping and use set instead of lsit ([`be614e6`](https://github.comgit//DioxusLabs/dioxus/commit/be614e6535e6e13e6ff93e9c6a171c1c002e6b01))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- feat(example:todomvc): add editing support ([`9849f68`](https://github.comgit//DioxusLabs/dioxus/commit/9849f68f257200fac511c048bfb1a076243b86d3))
- Merge pull request #101 from alexkirsz/ci ([`29bf424`](https://github.comgit//DioxusLabs/dioxus/commit/29bf424b0976b95ff645bb128d0e758cf0186614))
- Merge pull request #139 from DioxusLabs/jk/provide-context-any ([`70f2ef4`](https://github.comgit//DioxusLabs/dioxus/commit/70f2ef43db5b6737bd9bcbfc1aa21c834ce4b395))
- Merge branch 'master' into jk/unify ([`824defa`](https://github.comgit//DioxusLabs/dioxus/commit/824defa2dbcc16d66588b3976699d89b65a8a068))
- wire up both desktop and web ([`05331dd`](https://github.comgit//DioxusLabs/dioxus/commit/05331ddd8033f6997d4916179b62f4d62f832988))
- format code ([`9256161`](https://github.comgit//DioxusLabs/dioxus/commit/92561612c727e73356d7d36e16af39aacf02a56d))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
- bool attr white list ([`8f4aa84`](https://github.comgit//DioxusLabs/dioxus/commit/8f4aa84f1a4f2443b34d81ee42490564e168de53))
- setup a typescript build ([`5bf6c96`](https://github.comgit//DioxusLabs/dioxus/commit/5bf6c96f9fed04de949403202bafcbeadb5d2030))
- check `href` null ([`2073b40`](https://github.comgit//DioxusLabs/dioxus/commit/2073b400df55f0c6d8bed7371b2313be6c064e6e))
- add exclusion list ([`2123228`](https://github.comgit//DioxusLabs/dioxus/commit/21232285d9d84168d9003969ddd254fc22951e4b))
- check `href` null ([`327f901`](https://github.comgit//DioxusLabs/dioxus/commit/327f9015481809d8e5b9e69f26202e8d66dd198e))
- prevent `submit` default ([`8089023`](https://github.comgit//DioxusLabs/dioxus/commit/8089023a6c3a54957af9c9c05c9dee6088b059ef))
</details>
## v0.1.5 (2022-01-08)
### Documentation
@@ -37,6 +107,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- <csr-id-f782e142118fb7acf1b88a0f3fbb03e4a5e3e91e/> omg what a dumb mistake
- <csr-id-4a0068f09918adbc299150edcf777f342ced0dd3/> bless up, no more segfaults
- <csr-id-7dfe89c9581f45a445f17f9fe4bb94e61f67e971/> wire up event delegator for webview
- <csr-id-46fd6ac3450ca5ebf9aecb2d59a5a92b2a68bdd0/> link open in browser
- <csr-id-f006f50317f4b75fac353bc988db057a281ba7f8/> move `rpc` to handler
- <csr-id-9e04ce5342850d2e0a01dde169807d6f6eb16566/> `open_browser` bool attribute
- <csr-id-c737c424b05ad8453e8770a14a0d210fb0c7c2fe/> link open in browser
- <csr-id-a0f60152bc7e5866f114ed469809ce8be70d17d4/> link open in browser
### Bug Fixes
@@ -48,13 +123,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- <csr-id-a33f7701fcf5f917fea8719253650b5ad92554fd/> tags
- <csr-id-601078f9cf78a58d7502a377676ac94f3cf037bf/> desktop and mobile
- <csr-id-ba9e1dbb8fa24048a6c9ccef8a8722688226a845/> messed up how lifetimes worked, need to render once per component
- <csr-id-62b637f8b0eaf616c49461fa23b9251a79abc147/> error pattern
- <csr-id-5233ee97d9314f7f0e0bdf05c56d2a9e4201a596/> format code
### Commit Statistics
<csr-read-only-do-not-edit/>
- 91 commits contributed to the release over the course of 151 calendar days.
- 78 commits where understood as [conventional](https://www.conventionalcommits.org).
- 98 commits contributed to the release over the course of 151 calendar days.
- 84 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
@@ -64,11 +141,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- add exclusion list ([`2123228`](https://github.comgit//DioxusLabs/dioxus/commit/21232285d9d84168d9003969ddd254fc22951e4b))
- Release dioxus-desktop v0.1.5 ([`cd0dcac`](https://github.comgit//DioxusLabs/dioxus/commit/cd0dcacaf2862f26d29acb21d98f75d41b940e3f))
- handle bool attrs properly ([`8d685f4`](https://github.comgit//DioxusLabs/dioxus/commit/8d685f40b7e0ef6521c60310d8687291e9b9c48a))
- link open in browser ([`46fd6ac`](https://github.comgit//DioxusLabs/dioxus/commit/46fd6ac3450ca5ebf9aecb2d59a5a92b2a68bdd0))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- error pattern ([`62b637f`](https://github.comgit//DioxusLabs/dioxus/commit/62b637f8b0eaf616c49461fa23b9251a79abc147))
- move `rpc` to handler ([`f006f50`](https://github.comgit//DioxusLabs/dioxus/commit/f006f50317f4b75fac353bc988db057a281ba7f8))
- `open_browser` bool attribute ([`9e04ce5`](https://github.comgit//DioxusLabs/dioxus/commit/9e04ce5342850d2e0a01dde169807d6f6eb16566))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- format code ([`5233ee9`](https://github.comgit//DioxusLabs/dioxus/commit/5233ee97d9314f7f0e0bdf05c56d2a9e4201a596))
- link open in browser ([`c737c42`](https://github.comgit//DioxusLabs/dioxus/commit/c737c424b05ad8453e8770a14a0d210fb0c7c2fe))
- Merge pull request #89 from DioxusLabs/jk/simplify-example-run ([`8b6aa8b`](https://github.comgit//DioxusLabs/dioxus/commit/8b6aa8b880b6cb5c95e0c0743aad4e4e74388e05))
- link open in browser ([`a0f6015`](https://github.comgit//DioxusLabs/dioxus/commit/a0f60152bc7e5866f114ed469809ce8be70d17d4))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
- Merge pull request #80 from DioxusLabs/jk/router2dotoh ([`cdc2d8e`](https://github.comgit//DioxusLabs/dioxus/commit/cdc2d8ec6d123245c2ea5f6d10af02b6a6833994))
- clear warnigns ([`175a6a1`](https://github.comgit//DioxusLabs/dioxus/commit/175a6a199c6738d8d0c7646ba0ec3fc4406c6535))
+9 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-desktop"
version = "0.1.5"
version = "0.1.6"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Dioxus VirtualDOM renderer for a remote webview instance"
@@ -12,7 +12,7 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus-core = { path = "../core", version ="^0.1.7", features = ["serialize"] }
dioxus-core = { path = "../core", version = "^0.1.9", features = ["serialize"] }
argh = "0.1.4"
serde = "1.0.120"
serde_json = "1.0.61"
@@ -27,8 +27,12 @@ tokio = { version = "1.12.0", features = [
"rt",
"time",
], optional = true, default-features = false }
dioxus-core-macro = { path = "../core-macro", version ="^0.1.6"}
dioxus-html = { path = "../html", features = ["serialize"], version ="^0.1.4"}
dioxus-core-macro = { path = "../core-macro", version = "^0.1.7" }
dioxus-html = { path = "../html", features = ["serialize"], version = "^0.1.6" }
webbrowser = "0.5.5"
mime_guess = "2.0.3"
dioxus-interpreter-js = { path = "../interpreter", version = "^0.0.0" }
[features]
default = ["tokio_runtime"]
@@ -37,3 +41,4 @@ tokio_runtime = ["tokio"]
[dev-dependencies]
dioxus-hooks = { path = "../hooks" }
# image = "0.24.0" # enable this when generating a new desktop image
-34
View File
@@ -1,34 +0,0 @@
use dioxus::prelude::*;
use dioxus_core as dioxus;
use dioxus_core_macro::*;
use dioxus_hooks::*;
use dioxus_html as dioxus_elements;
use std::time::Duration;
fn main() {
dioxus_desktop::launch(app);
}
fn app(cx: Scope) -> Element {
let count = use_state(&cx, || 0);
use_future(&cx, || {
let count = count.for_async();
async move {
loop {
tokio::time::sleep(Duration::from_millis(1000)).await;
*count.modify() += 1;
}
}
});
cx.render(rsx! {
div {
h1 { "High-Five counter: {count}" }
button {
onclick: move |_| count.set(0),
"Click me!"
}
}
})
}
+48 -5
View File
@@ -1,3 +1,4 @@
use wry::application::window::Icon;
use wry::{
application::{
event_loop::EventLoop,
@@ -13,12 +14,12 @@ pub(crate) type DynEventHandlerFn = dyn Fn(&mut EventLoop<()>, &mut WebView);
pub struct DesktopConfig {
pub window: WindowBuilder,
pub file_drop_handler: Option<Box<dyn Fn(&Window, FileDropEvent) -> bool>>,
pub protocos: Vec<WryProtocl>,
pub protocols: Vec<WryProtocol>,
pub(crate) pre_rendered: Option<String>,
pub(crate) event_handler: Option<Box<DynEventHandlerFn>>,
}
pub type WryProtocl = (
pub type WryProtocol = (
String,
Box<dyn Fn(&HttpRequest) -> WryResult<HttpResponse> + 'static>,
);
@@ -31,7 +32,7 @@ impl DesktopConfig {
Self {
event_handler: None,
window,
protocos: Vec::new(),
protocols: Vec::new(),
file_drop_handler: None,
pre_rendered: None,
}
@@ -71,11 +72,25 @@ impl DesktopConfig {
self
}
pub fn with_custom_protocol<F>(mut self, name: String, handler: F) -> Self
pub fn with_custom_protocol<F>(&mut self, name: String, handler: F) -> &mut Self
where
F: Fn(&HttpRequest) -> WryResult<HttpResponse> + 'static,
{
self.protocos.push((name, Box::new(handler)));
self.protocols.push((name, Box::new(handler)));
self
}
pub fn with_icon(&mut self, icon: Icon) -> &mut Self {
self.window.window.window_icon = Some(icon);
self
}
}
impl DesktopConfig {
pub(crate) fn with_default_icon(mut self) -> Self {
let bin: &[u8] = include_bytes!("default_icon.bin");
let rgba = Icon::from_rgba(bin.to_owned(), 460, 460).expect("image parse failed");
self.window.window.window_icon = Some(rgba);
self
}
}
@@ -85,3 +100,31 @@ impl Default for DesktopConfig {
Self::new()
}
}
// dirty trick, avoid introducing `image` at runtime
// TODO: use serde when `Icon` impl serde
//
// This function should only be enabled when generating new icons.
//
// #[test]
// #[ignore]
// fn prepare_default_icon() {
// use image::io::Reader as ImageReader;
// use image::ImageFormat;
// use std::fs::File;
// use std::io::Cursor;
// use std::io::Write;
// use std::path::PathBuf;
// let png: &[u8] = include_bytes!("default_icon.png");
// let mut reader = ImageReader::new(Cursor::new(png));
// reader.set_format(ImageFormat::Png);
// let icon = reader.decode().unwrap();
// let bin = PathBuf::from(file!())
// .parent()
// .unwrap()
// .join("default_icon.bin");
// println!("{:?}", bin);
// let mut file = File::create(bin).unwrap();
// file.write_all(icon.as_bytes()).unwrap();
// println!("({}, {})", icon.width(), icon.height())
// }
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

+104 -89
View File
@@ -1,100 +1,115 @@
use std::cell::RefCell;
use std::rc::Rc;
use dioxus::prelude::Scope;
use dioxus_core as dioxus;
use dioxus_core::{Context, Element, LazyNodes, NodeFactory, Properties};
use dioxus_core_macro::Props;
use dioxus_core::ScopeState;
use wry::application::event_loop::EventLoopProxy;
/*
This module provides a set of Dioxus components to easily manage windows, tabs, etc.
use crate::UserWindowEvent;
Windows can be created anywhere in the tree, making them very flexible for things like modals, etc.
type ProxyType = EventLoopProxy<UserWindowEvent>;
*/
pub struct DesktopContext {}
/// Desktop-Window handle api context
///
/// you can use this context control some window event
///
/// you can use `cx.consume_context::<DesktopContext>` to get this context
///
/// ```rust
/// let desktop = cx.consume_context::<DesktopContext>().unwrap();
/// ```
#[derive(Clone)]
pub struct DesktopContext {
proxy: ProxyType,
}
impl DesktopContext {
fn add_window(&mut self) {
//
pub(crate) fn new(proxy: ProxyType) -> Self {
Self { proxy }
}
fn close_window(&mut self) {
//
/// trigger the drag-window event
///
/// Moves the window with the left mouse button until the button is released.
///
/// you need use it in `onmousedown` event:
/// ```rust
/// onmousedown: move |_| { desktop.drag_window(); }
/// ```
pub fn drag(&self) {
let _ = self.proxy.send_event(UserWindowEvent::DragWindow);
}
/// set window minimize state
pub fn set_minimized(&self, minimized: bool) {
let _ = self.proxy.send_event(UserWindowEvent::Minimize(minimized));
}
/// set window maximize state
pub fn set_maximized(&self, maximized: bool) {
let _ = self.proxy.send_event(UserWindowEvent::Maximize(maximized));
}
/// set window visible or not
pub fn set_visible(&self, visible: bool) {
let _ = self.proxy.send_event(UserWindowEvent::Visible(visible));
}
/// close window
pub fn close(&self) {
let _ = self.proxy.send_event(UserWindowEvent::CloseWindow);
}
/// set window to focus
pub fn focus(&self) {
let _ = self.proxy.send_event(UserWindowEvent::FocusWindow);
}
/// change window to fullscreen
pub fn set_fullscreen(&self, fullscreen: bool) {
let _ = self
.proxy
.send_event(UserWindowEvent::Fullscreen(fullscreen));
}
/// set resizable state
pub fn set_resizable(&self, resizable: bool) {
let _ = self.proxy.send_event(UserWindowEvent::Resizable(resizable));
}
/// set the window always on top
pub fn set_always_on_top(&self, top: bool) {
let _ = self.proxy.send_event(UserWindowEvent::AlwaysOnTop(top));
}
// set cursor visible or not
pub fn set_cursor_visible(&self, visible: bool) {
let _ = self
.proxy
.send_event(UserWindowEvent::CursorVisible(visible));
}
// set cursor grab
pub fn set_cursor_grab(&self, grab: bool) {
let _ = self.proxy.send_event(UserWindowEvent::CursorGrab(grab));
}
/// set window title
pub fn set_title(&self, title: &str) {
let _ = self
.proxy
.send_event(UserWindowEvent::SetTitle(String::from(title)));
}
/// change window to borderless
pub fn set_decorations(&self, decoration: bool) {
let _ = self
.proxy
.send_event(UserWindowEvent::SetDecorations(decoration));
}
}
enum WindowHandlers {
Resized(Box<dyn Fn()>),
Moved(Box<dyn Fn()>),
CloseRequested(Box<dyn Fn()>),
Destroyed(Box<dyn Fn()>),
DroppedFile(Box<dyn Fn()>),
HoveredFile(Box<dyn Fn()>),
HoverFileCancelled(Box<dyn Fn()>),
ReceivedTimeText(Box<dyn Fn()>),
Focused(Box<dyn Fn()>),
}
#[derive(Props)]
pub struct WebviewWindowProps<'a> {
onclose: &'a dyn FnMut(()),
onopen: &'a dyn FnMut(()),
/// focuse me
onfocused: &'a dyn FnMut(()),
children: Element,
}
/// A handle to a
///
///
///
///
///
///
///
///
///
pub fn WebviewWindow(cx: Scope<WebviewWindowProps>) -> Element {
let dtcx = cx.consume_state::<RefCell<DesktopContext>>()?;
cx.use_hook(|_| {});
// render the children directly
todo!()
// cx.render(LazyNodes::new(move |f: NodeFactory| {
// f.fragment_from_iter(cx.children())
// }))
}
pub struct WindowHandle {}
/// Get a handle to the current window from inside a component
pub fn use_current_window(cx: Scope) -> Option<WindowHandle> {
todo!()
}
#[test]
fn syntax_works() {
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
use dioxus_core_macro::*;
use dioxus_hooks::*;
use dioxus_html as dioxus_elements;
static App: Component = |cx| {
cx.render(rsx! {
// left window
WebviewWindow {
onclose: move |evt| {}
onopen: move |evt| {}
onfocused: move |evt| {}
div {
}
}
})
};
/// use this function can get the `DesktopContext` context.
pub fn use_window(cx: &ScopeState) -> &Rc<DesktopContext> {
cx.use_hook(|_| cx.consume_context::<DesktopContext>())
.as_ref()
.unwrap()
}
+12 -15
View File
@@ -1,18 +1,15 @@
<!DOCTYPE html>
<html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8" />
</head>
<body>
<div id="main">
</div>
</body>
<script type="text/javascript" src="index.js">
</script>
<head>
<title>Dioxus app</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="main"></div>
<script>
import("./index.js").then(function (module) {
module.main();
});
</script>
</body>
</html>
-446
View File
@@ -1,446 +0,0 @@
const bool_attrs = {
allowfullscreen: true,
allowpaymentrequest: true,
async: true,
autofocus: true,
autoplay: true,
checked: true,
controls: true,
default: true,
defer: true,
disabled: true,
formnovalidate: true,
hidden: true,
ismap: true,
itemscope: true,
loop: true,
multiple: true,
muted: true,
nomodule: true,
novalidate: true,
open: true,
playsinline: true,
readonly: true,
required: true,
reversed: true,
selected: true,
truespeed: true,
};
function serialize_event(event) {
switch (event.type) {
case "copy":
case "cut":
case "past":
return {};
case "compositionend":
case "compositionstart":
case "compositionupdate":
return {
data: event.data,
};
case "keydown":
case "keypress":
case "keyup":
return {
char_code: event.charCode,
key: event.key,
alt_key: event.altKey,
ctrl_key: event.ctrlKey,
meta_key: event.metaKey,
key_code: event.keyCode,
shift_key: event.shiftKey,
locale: "locale",
location: event.location,
repeat: event.repeat,
which: event.which,
// locale: event.locale,
};
case "focus":
case "blur":
return {};
case "change":
let target = event.target;
let value;
if (target.type === "checkbox" || target.type === "radio") {
value = target.checked ? "true" : "false";
} else {
value = target.value ?? target.textContent;
}
return {
value: value,
};
case "input":
case "invalid":
case "reset":
case "submit": {
let target = event.target;
let value = target.value ?? target.textContent;
if (target.type == "checkbox") {
value = target.checked ? "true" : "false";
}
return {
value: value,
};
}
case "click":
case "contextmenu":
case "doubleclick":
case "drag":
case "dragend":
case "dragenter":
case "dragexit":
case "dragleave":
case "dragover":
case "dragstart":
case "drop":
case "mousedown":
case "mouseenter":
case "mouseleave":
case "mousemove":
case "mouseout":
case "mouseover":
case "mouseup":
return {
alt_key: event.altKey,
button: event.button,
buttons: event.buttons,
client_x: event.clientX,
client_y: event.clientY,
ctrl_key: event.ctrlKey,
meta_key: event.metaKey,
page_x: event.pageX,
page_y: event.pageY,
screen_x: event.screenX,
screen_y: event.screenY,
shift_key: event.shiftKey,
};
case "pointerdown":
case "pointermove":
case "pointerup":
case "pointercancel":
case "gotpointercapture":
case "lostpointercapture":
case "pointerenter":
case "pointerleave":
case "pointerover":
case "pointerout":
return {
alt_key: event.altKey,
button: event.button,
buttons: event.buttons,
client_x: event.clientX,
client_y: event.clientY,
ctrl_key: event.ctrlKey,
meta_key: event.metaKey,
page_x: event.pageX,
page_y: event.pageY,
screen_x: event.screenX,
screen_y: event.screenY,
shift_key: event.shiftKey,
pointer_id: event.pointerId,
width: event.width,
height: event.height,
pressure: event.pressure,
tangential_pressure: event.tangentialPressure,
tilt_x: event.tiltX,
tilt_y: event.tiltY,
twist: event.twist,
pointer_type: event.pointerType,
is_primary: event.isPrimary,
};
case "select":
return {};
case "touchcancel":
case "touchend":
case "touchmove":
case "touchstart":
return {
alt_key: event.altKey,
ctrl_key: event.ctrlKey,
meta_key: event.metaKey,
shift_key: event.shiftKey,
// changed_touches: event.changedTouches,
// target_touches: event.targetTouches,
// touches: event.touches,
};
case "scroll":
return {};
case "wheel":
return {
delta_x: event.deltaX,
delta_y: event.deltaY,
delta_z: event.deltaZ,
delta_mode: event.deltaMode,
};
case "animationstart":
case "animationend":
case "animationiteration":
return {
animation_name: event.animationName,
elapsed_time: event.elapsedTime,
pseudo_element: event.pseudoElement,
};
case "transitionend":
return {
property_name: event.propertyName,
elapsed_time: event.elapsedTime,
pseudo_element: event.pseudoElement,
};
case "abort":
case "canplay":
case "canplaythrough":
case "durationchange":
case "emptied":
case "encrypted":
case "ended":
case "error":
case "loadeddata":
case "loadedmetadata":
case "loadstart":
case "pause":
case "play":
case "playing":
case "progress":
case "ratechange":
case "seeked":
case "seeking":
case "stalled":
case "suspend":
case "timeupdate":
case "volumechange":
case "waiting":
return {};
case "toggle":
return {};
default:
return {};
}
}
class Interpreter {
constructor(root) {
this.root = root;
this.stack = [root];
this.listeners = {
onclick: {},
};
this.lastNodeWasText = false;
this.nodes = [root];
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
return this.stack.pop();
}
PushRoot(edit) {
const id = edit.root;
const node = this.nodes[id];
this.stack.push(node);
}
AppendChildren(edit) {
let root = this.stack[this.stack.length - (1 + edit.many)];
let to_add = this.stack.splice(this.stack.length - edit.many);
for (let i = 0; i < edit.many; i++) {
root.appendChild(to_add[i]);
}
}
ReplaceWith(edit) {
let root = this.nodes[edit.root];
let els = this.stack.splice(this.stack.length - edit.m);
root.replaceWith(...els);
}
InsertAfter(edit) {
let old = this.nodes[edit.root];
let new_nodes = this.stack.splice(this.stack.length - edit.n);
old.after(...new_nodes);
}
InsertBefore(edit) {
let old = this.nodes[edit.root];
let new_nodes = this.stack.splice(this.stack.length - edit.n);
old.before(...new_nodes);
}
Remove(edit) {
let node = this.nodes[edit.root];
if (node !== undefined) {
node.remove();
}
}
CreateTextNode(edit) {
const node = document.createTextNode(edit.text);
this.nodes[edit.root] = node;
this.stack.push(node);
}
CreateElement(edit) {
const tagName = edit.tag;
const el = document.createElement(tagName);
this.nodes[edit.root] = el;
el.setAttribute("dioxus-id", edit.root);
this.stack.push(el);
}
CreateElementNs(edit) {
let el = document.createElementNS(edit.ns, edit.tag);
this.stack.push(el);
this.nodes[edit.root] = el;
}
CreatePlaceholder(edit) {
let el = document.createElement("pre");
el.hidden = true;
this.stack.push(el);
this.nodes[edit.root] = el;
}
RemoveEventListener(edit) {}
NewEventListener(edit) {
const event_name = edit.event_name;
const mounted_node_id = edit.root;
const scope = edit.scope;
const element = this.nodes[edit.root];
element.setAttribute(
`dioxus-event-${event_name}`,
`${scope}.${mounted_node_id}`
);
if (this.listeners[event_name] === undefined) {
this.listeners[event_name] = true;
this.root.addEventListener(event_name, (event) => {
const target = event.target;
const real_id = target.getAttribute(`dioxus-id`);
const should_prevent_default = target.getAttribute(
`dioxus-prevent-default`
);
let contents = serialize_event(event);
if (should_prevent_default === `on${event.type}`) {
event.preventDefault();
}
if (real_id == null) {
return;
}
rpc.call("user_event", {
event: event_name,
mounted_dom_id: parseInt(real_id),
contents: contents,
});
});
}
}
SetText(edit) {
this.nodes[edit.root].textContent = edit.text;
}
SetAttribute(edit) {
// console.log("setting attr", edit);
const name = edit.field;
const value = edit.value;
const ns = edit.ns;
const node = this.nodes[edit.root];
if (ns == "style") {
node.style[name] = value;
} else if (ns != null || ns != undefined) {
node.setAttributeNS(ns, name, value);
} else {
switch (name) {
case "value":
if (value != node.value) {
node.value = value;
}
break;
case "checked":
node.checked = value === "true";
break;
case "selected":
node.selected = value === "true";
break;
case "dangerous_inner_html":
node.innerHTML = value;
break;
default:
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if (value == "false" && bool_attrs.hasOwnProperty(name)) {
node.removeAttribute(name);
} else {
node.setAttribute(name, value);
}
}
}
}
RemoveAttribute(edit) {
const name = edit.field;
const node = this.nodes[edit.root];
node.removeAttribute(name);
if (name === "value") {
node.value = null;
}
if (name === "checked") {
node.checked = false;
}
if (name === "selected") {
node.selected = false;
}
}
handleEdits(edits) {
this.stack.push(this.root);
for (let x = 0; x < edits.length; x++) {
let edit = edits[x];
let f = this[edit.type];
f.call(this, edit);
}
}
}
function main() {
let root = window.document.getElementById("main");
window.interpreter = new Interpreter(root);
rpc.call("initialize");
}
main();
+184 -65
View File
@@ -1,60 +1,15 @@
//! Dioxus Desktop Renderer
//!
//! Render the Dioxus VirtualDom using the platform's native WebView implementation.
//!
//! # Desktop
//!
//! One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory.
//!
//! Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc.
//!
//!
//! ## Getting Set up
//!
//! Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project:
//!
//! ```shell
//! $ cargo new --bin demo
//! $ cd app
//! ```
//!
//! Add Dioxus with the `desktop` feature:
//!
//! ```shell
//! $ cargo add dioxus --features desktop
//! ```
//!
//! Edit your `main.rs`:
//!
//! ```rust
//! // main.rs
//! use dioxus::prelude::*;
//!
//! fn main() {
//! dioxus::desktop::launch(app);
//! }
//!
//! fn app(cx: Scope) -> Element {
//! cx.render(rsx!{
//! div {
//! "hello world!"
//! }
//! })
//! }
//! ```
//!
//!
//! To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/).
//!
//! ## Future Steps
//!
//! Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
#![doc = include_str!("readme.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
pub mod cfg;
pub mod desktop_context;
pub mod escape;
pub mod events;
use cfg::DesktopConfig;
pub use desktop_context::use_window;
use desktop_context::DesktopContext;
use dioxus_core::*;
use std::{
collections::{HashMap, VecDeque},
@@ -69,7 +24,7 @@ use tao::{
pub use wry;
pub use wry::application as tao;
use wry::{
application::event_loop::EventLoopProxy,
application::{event_loop::EventLoopProxy, window::Fullscreen},
webview::RpcRequest,
webview::{WebView, WebViewBuilder},
};
@@ -149,7 +104,7 @@ pub fn launch_with_props<P: 'static + Send>(
props: P,
builder: impl FnOnce(&mut DesktopConfig) -> &mut DesktopConfig,
) {
let mut cfg = DesktopConfig::new();
let mut cfg = DesktopConfig::default().with_default_icon();
builder(&mut cfg);
let event_loop = EventLoop::with_user_event();
@@ -174,6 +129,7 @@ pub fn launch_with_props<P: 'static + Send>(
let mut webview = WebViewBuilder::new(window)
.unwrap()
.with_transparent(cfg.window.window.transparent)
.with_url("dioxus://index.html/")
.unwrap()
.with_rpc_handler(move |_window: &Window, req: RpcRequest| {
@@ -187,37 +143,77 @@ pub fn launch_with_props<P: 'static + Send>(
is_ready.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = proxy.send_event(UserWindowEvent::Update);
}
"browser_open" => {
println!("browser_open");
let data = req.params.unwrap();
log::trace!("Open browser: {:?}", data);
if let Some(arr) = data.as_array() {
if let Some(temp) = arr[0].as_object() {
if temp.contains_key("href") {
let url = temp.get("href").unwrap().as_str().unwrap();
if let Err(e) = webbrowser::open(url) {
log::error!("Open Browser error: {:?}", e);
}
}
}
}
}
_ => {}
}
None
})
.with_custom_protocol("dioxus".into(), move |request| {
.with_custom_protocol(String::from("dioxus"), move |request| {
// Any content that that uses the `dioxus://` scheme will be shuttled through this handler as a "special case"
// For now, we only serve two pieces of content which get included as bytes into the final binary.
let path = request.uri().replace("dioxus://", "");
if path.trim_end_matches('/') == "index.html" {
// all assets shouldbe called from index.html
let trimmed = path.trim_start_matches("index.html/");
if trimmed.is_empty() {
wry::http::ResponseBuilder::new()
.mimetype("text/html")
.body(include_bytes!("./index.html").to_vec())
} else if path.trim_end_matches('/') == "index.html/index.js" {
} else if trimmed == "index.js" {
wry::http::ResponseBuilder::new()
.mimetype("text/javascript")
.body(include_bytes!("./index.js").to_vec())
.body(dioxus_interpreter_js::INTERPRTER_JS.as_bytes().to_vec())
} else {
wry::http::ResponseBuilder::new()
.status(wry::http::status::StatusCode::NOT_FOUND)
.body(format!("Not found: {}", path).as_bytes().to_vec())
// Read the file content from file path
use std::fs::read;
let path_buf = std::path::Path::new(trimmed).canonicalize()?;
let cur_path = std::path::Path::new(".").canonicalize()?;
if !path_buf.starts_with(cur_path) {
return wry::http::ResponseBuilder::new()
.status(wry::http::status::StatusCode::FORBIDDEN)
.body(String::from("Forbidden").into_bytes());
}
if !path_buf.exists() {
return wry::http::ResponseBuilder::new()
.status(wry::http::status::StatusCode::NOT_FOUND)
.body(String::from("Not Found").into_bytes());
}
let mime = mime_guess::from_path(&path_buf).first_or_octet_stream();
// do not let path searching to go two layers beyond the caller level
let data = read(path_buf)?;
let meta = format!("{}", mime);
wry::http::ResponseBuilder::new().mimetype(&meta).body(data)
}
})
.with_file_drop_handler(move |window, evet| {
if let Some(handler) = file_handler.as_ref() {
return handler(window, evet);
}
false
file_handler
.as_ref()
.map(|handler| handler(window, evet))
.unwrap_or_default()
});
for (name, handler) in cfg.protocos.drain(..) {
for (name, handler) in cfg.protocols.drain(..) {
webview = webview.with_custom_protocol(name, handler)
}
@@ -243,6 +239,109 @@ pub fn launch_with_props<P: 'static + Send>(
//
match _evt {
UserWindowEvent::Update => desktop.try_load_ready_webviews(),
UserWindowEvent::DragWindow => {
// this loop just run once, because dioxus-desktop is unsupport multi-window.
for webview in desktop.webviews.values() {
let window = webview.window();
// start to drag the window.
// if the drag_window have any err. we don't do anything.
if window.fullscreen().is_some() {
return;
}
let _ = window.drag_window();
}
}
UserWindowEvent::CloseWindow => {
// close window
*control_flow = ControlFlow::Exit;
}
UserWindowEvent::Visible(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_visible(state);
}
}
UserWindowEvent::Minimize(state) => {
// this loop just run once, because dioxus-desktop is unsupport multi-window.
for webview in desktop.webviews.values() {
let window = webview.window();
// change window minimized state.
window.set_minimized(state);
}
}
UserWindowEvent::Maximize(state) => {
// this loop just run once, because dioxus-desktop is unsupport multi-window.
for webview in desktop.webviews.values() {
let window = webview.window();
// change window maximized state.
window.set_maximized(state);
}
}
UserWindowEvent::Fullscreen(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
let current_monitor = window.current_monitor();
if current_monitor.is_none() {
return;
}
let fullscreen = if state {
Some(Fullscreen::Borderless(current_monitor))
} else {
None
};
window.set_fullscreen(fullscreen);
}
}
UserWindowEvent::FocusWindow => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_focus();
}
}
UserWindowEvent::Resizable(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_resizable(state);
}
}
UserWindowEvent::AlwaysOnTop(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_always_on_top(state);
}
}
UserWindowEvent::CursorVisible(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_cursor_visible(state);
}
}
UserWindowEvent::CursorGrab(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
let _ = window.set_cursor_grab(state);
}
}
UserWindowEvent::SetTitle(content) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_title(&content);
}
}
UserWindowEvent::SetDecorations(state) => {
for webview in desktop.webviews.values() {
let window = webview.window();
window.set_decorations(state);
}
}
}
}
Event::MainEventsCleared => {}
@@ -257,6 +356,21 @@ pub fn launch_with_props<P: 'static + Send>(
pub enum UserWindowEvent {
Update,
DragWindow,
CloseWindow,
FocusWindow,
Visible(bool),
Minimize(bool),
Maximize(bool),
Resizable(bool),
AlwaysOnTop(bool),
Fullscreen(bool),
CursorVisible(bool),
CursorGrab(bool),
SetTitle(String),
SetDecorations(bool),
}
pub struct DesktopController {
@@ -283,6 +397,7 @@ impl DesktopController {
let return_sender = sender.clone();
let proxy = evt.clone();
let desktop_context_proxy = proxy.clone();
std::thread::spawn(move || {
// We create the runtime as multithreaded, so you can still "spawn" onto multiple threads
let runtime = tokio::runtime::Builder::new_multi_thread()
@@ -294,6 +409,10 @@ impl DesktopController {
let mut dom =
VirtualDom::new_with_props_and_scheduler(root, props, (sender, receiver));
let window_context = DesktopContext::new(desktop_context_proxy);
dom.base_scope().provide_context(window_context);
let edits = dom.rebuild();
edit_queue
+51
View File
@@ -0,0 +1,51 @@
Dioxus Desktop Renderer
Render the Dioxus VirtualDom using the platform's native WebView implementation.
# Desktop
One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory.
Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc.
## Getting Set up
Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project:
```shell
$ cargo new --bin demo
$ cd app
```
Add Dioxus with the `desktop` feature:
```shell
$ cargo add dioxus --features desktop
```
Edit your `main.rs`:
```rust
// main.rs
use dioxus::prelude::*;
fn main() {
dioxus::desktop::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx!{
div {
"hello world!"
}
})
}
```
To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/).
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
+35 -1
View File
@@ -5,6 +5,39 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Bug Fixes
- <csr-id-c092bd43edf1891c427722bc9ca04e11c9359069/> use_state
- <csr-id-a8952a9ee8d8831fa911cef4e7035293c3a9f88b/> exampels
### Commit Statistics
<csr-read-only-do-not-edit/>
- 9 commits contributed to the release over the course of 21 calendar days.
- 3 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Merge pull request #169 from DioxusLabs/jk/router-userouter ([`3509602`](https://github.comgit//DioxusLabs/dioxus/commit/3509602c0bcd327a33bc8c95896775e24751da1a))
- Merge pull request #158 from DioxusLabs/jk/router-onchange ([`08988e1`](https://github.comgit//DioxusLabs/dioxus/commit/08988e1bfec35eadb30e50b5d677dbb36af91b9b))
- use_state ([`c092bd4`](https://github.comgit//DioxusLabs/dioxus/commit/c092bd43edf1891c427722bc9ca04e11c9359069))
- exampels ([`a8952a9`](https://github.comgit//DioxusLabs/dioxus/commit/a8952a9ee8d8831fa911cef4e7035293c3a9f88b))
- Merge branch 'master' into jk/update-hooks ([`5c4bd08`](https://github.comgit//DioxusLabs/dioxus/commit/5c4bd0881bc10572440d9272ceb8ca774431c406))
- modify usestate to be borrowed ([`58839f4`](https://github.comgit//DioxusLabs/dioxus/commit/58839f47bae3c49cadd4b41da9a5debebb1def99))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
</details>
## v0.1.6 (2022-01-08)
### Documentation
@@ -52,7 +85,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 93 commits contributed to the release over the course of 358 calendar days.
- 94 commits contributed to the release over the course of 358 calendar days.
- 82 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -63,6 +96,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`b804c69`](https://github.comgit//DioxusLabs/dioxus/commit/b804c691d5ade4776390bb3d334cc9cd8efa4a49))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- component pass thru events ([`c439b0a`](https://github.comgit//DioxusLabs/dioxus/commit/c439b0ac7e09f70a04262b7c29938d8c52197b76))
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-hooks"
version = "0.1.6"
version = "0.1.7"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Dioxus VirtualDOM renderer for a remote webview instance"
@@ -12,4 +12,4 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus-core = { path = "../../packages/core", version ="^0.1.7"}
dioxus-core = { path = "../../packages/core", version = "^0.1.9" }
+22 -42
View File
@@ -16,45 +16,25 @@ pub use usefuture::*;
mod usesuspense;
pub use usesuspense::*;
// #[macro_export]
// macro_rules! to_owned {
// ($($es:ident),+) => {$(
// #[allow(unused_mut)]
// let mut $es = $es.to_owned();
// )*}
// }
// /// Calls `for_async` on the series of paramters.
// ///
// /// If the type is Clone, then it will be cloned. However, if the type is not `clone`
// /// then it must have a `for_async` method for Rust to lower down into.
// ///
// /// See: how use_state implements `for_async` but *not* through the trait.
// #[macro_export]
// macro_rules! for_async {
// ($($es:ident),+) => {$(
// #[allow(unused_mut)]
// let mut $es = $es.for_async();
// )*}
// }
// /// This is a marker trait that uses decoherence.
// ///
// /// It is *not* meant for hooks to actually implement, but rather defer to their
// /// underlying implementation if they *don't* implement the trait.
// ///
// ///
// pub trait AsyncHook {
// type Output;
// fn for_async(self) -> Self::Output;
// }
// impl<T> AsyncHook for T
// where
// T: ToOwned<Owned = T>,
// {
// type Output = T;
// fn for_async(self) -> Self::Output {
// self
// }
// }
#[macro_export]
/// A helper macro for using hooks in async environements.
///
/// # Usage
///
///
/// ```
/// let (data) = use_ref(&cx, || {});
///
/// let handle_thing = move |_| {
/// to_owned![data]
/// cx.spawn(async move {
/// // do stuff
/// });
/// }
/// ```
macro_rules! to_owned {
($($es:ident),+) => {$(
#[allow(unused_mut)]
let mut $es = $es.to_owned();
)*}
}
+1 -1
View File
@@ -33,7 +33,7 @@ impl<T> ProvidedStateInner<T> {
/// This hook provides some relatively light ergonomics around shared state.
///
/// It is not a substitute for a proper state management system, but it is capable enough to provide use_state - type
/// ergonimics in a pinch, with zero cost.
/// ergonomics in a pinch, with zero cost.
///
/// # Example
///
+346
View File
@@ -0,0 +1,346 @@
#![warn(clippy::pedantic)]
use dioxus_core::prelude::*;
use std::{
cell::{RefCell, RefMut},
fmt::{Debug, Display},
rc::Rc,
};
/// Store state between component renders.
///
/// ## Dioxus equivalent of useState, designed for Rust
///
/// The Dioxus version of `useState` for state management inside components. It allows you to ergonomically store and
/// modify state between component renders. When the state is updated, the component will re-render.
///
///
/// ```ignore
/// const Example: Component = |cx| {
/// let (count, set_count) = use_state(&cx, || 0);
///
/// cx.render(rsx! {
/// div {
/// h1 { "Count: {count}" }
/// button { onclick: move |_| set_count(a - 1), "Increment" }
/// button { onclick: move |_| set_count(a + 1), "Decrement" }
/// }
/// ))
/// }
/// ```
pub fn use_state<'a, T: 'static>(
cx: &'a ScopeState,
initial_state_fn: impl FnOnce() -> T,
) -> (&'a T, &'a UseState<T>) {
let hook = cx.use_hook(move |_| {
let current_val = Rc::new(initial_state_fn());
let update_callback = cx.schedule_update();
let slot = Rc::new(RefCell::new(current_val.clone()));
let setter = Rc::new({
crate::to_owned![update_callback, slot];
move |new| {
{
let mut slot = slot.borrow_mut();
// if there's only one reference (weak or otherwise), we can just swap the values
// Typically happens when the state is set multiple times - we don't want to create a new Rc for each new value
if let Some(val) = Rc::get_mut(&mut slot) {
*val = new;
} else {
*slot = Rc::new(new);
}
}
update_callback();
}
});
UseState {
current_val,
update_callback,
setter,
slot,
}
});
hook.current_val = hook.slot.borrow().clone();
(hook.current_val.as_ref(), hook)
}
pub struct UseState<T: 'static> {
pub(crate) current_val: Rc<T>,
pub(crate) update_callback: Rc<dyn Fn()>,
pub(crate) setter: Rc<dyn Fn(T)>,
pub(crate) slot: Rc<RefCell<Rc<T>>>,
}
impl<T: 'static> UseState<T> {
/// Get the current value of the state by cloning its container Rc.
///
/// This is useful when you are dealing with state in async contexts but need
/// to know the current value. You are not given a reference to the state.
///
/// # Examples
/// An async context might need to know the current value:
///
/// ```rust, ignore
/// fn component(cx: Scope) -> Element {
/// let (count, set_count) = use_state(&cx, || 0);
/// cx.spawn({
/// let set_count = set_count.to_owned();
/// async move {
/// let current = set_count.current();
/// }
/// })
/// }
/// ```
#[must_use]
pub fn current(&self) -> Rc<T> {
self.slot.borrow().clone()
}
/// Get the `setter` function directly without the `UseState` wrapper.
///
/// This is useful for passing the setter function to other components.
///
/// However, for most cases, calling `to_owned` o`UseState`te is the
/// preferred way to get "anoth`set_state`tate handle.
///
///
/// # Examples
/// A component might require an `Rc<dyn Fn(T)>` as an input to set a value.
///
/// ```rust, ignore
/// fn component(cx: Scope) -> Element {
/// let (value, set_value) = use_state(&cx, || 0);
///
/// rsx!{
/// Component {
/// handler: set_val.setter()
/// }
/// }
/// }
/// ```
#[must_use]
pub fn setter(&self) -> Rc<dyn Fn(T)> {
self.setter.clone()
}
/// Set the state to a new value, using the current state value as a reference.
///
/// This is similar to passing a closure to React's `set_value` function.
///
/// # Examples
///
/// Basic usage:
/// ```rust
/// # use dioxus_core::prelude::*;
/// # use dioxus_hooks::*;
/// fn component(cx: Scope) -> Element {
/// let (value, set_value) = use_state(&cx, || 0);
///
/// // to increment the value
/// set_value.modify(|v| v + 1);
///
/// // usage in async
/// cx.spawn({
/// let set_value = set_value.to_owned();
/// async move {
/// set_value.modify(|v| v + 1);
/// }
/// });
///
/// # todo!()
/// }
/// ```
pub fn modify(&self, f: impl FnOnce(&T) -> T) {
let new_val = {
let current = self.slot.borrow();
f(current.as_ref())
};
(self.setter)(new_val);
}
/// Get the value of the state when this handle was created.
///
/// This method is useful when you want an `Rc` around the data to cheaply
/// pass it around your app.
///
/// ## Warning
///
/// This will return a stale value if used within async contexts.
///
/// Try `current` to get the real current value of the state.
///
/// ## Example
///
/// ```rust, ignore
/// # use dioxus_core::prelude::*;
/// # use dioxus_hooks::*;
/// fn component(cx: Scope) -> Element {
/// let (value, set_value) = use_state(&cx, || 0);
///
/// let as_rc = set_value.get();
/// assert_eq!(as_rc.as_ref(), &0);
///
/// # todo!()
/// }
/// ```
#[must_use]
pub fn get(&self) -> &Rc<T> {
&self.current_val
}
/// Mark the component that create this [`UseState`] as dirty, forcing it to re-render.
///
/// ```rust, ignore
/// fn component(cx: Scope) -> Element {
/// let (count, set_count) = use_state(&cx, || 0);
/// cx.spawn({
/// let set_count = set_count.to_owned();
/// async move {
/// // for the component to re-render
/// set_count.needs_update();
/// }
/// })
/// }
/// ```
pub fn needs_update(&self) {
(self.update_callback)();
}
}
impl<T: Clone> UseState<T> {
/// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
/// current value.
///
/// This is essentially cloning the underlying value and then setting it,
/// giving you a mutable handle in the process. This method is intended for
/// types that are cheaply cloneable.
///
/// If you are comfortable dealing with `RefMut`, then you can use `make_mut` to get
/// the underlying slot. However, be careful with `RefMut` since you might panic
/// if the `RefCell` is left open.
///
/// # Examples
///
/// ```
/// let (val, set_val) = use_state(&cx, || 0);
///
/// set_val.with_mut(|v| *v = 1);
/// ```
pub fn with_mut(&self, apply: impl FnOnce(&mut T)) {
let mut slot = self.slot.borrow_mut();
let mut inner = slot.as_ref().to_owned();
apply(&mut inner);
if let Some(new) = Rc::get_mut(&mut slot) {
*new = inner;
} else {
*slot = Rc::new(inner);
}
self.needs_update();
}
/// Get a mutable handle to the value by calling `ToOwned::to_owned` on the
/// current value.
///
/// This is essentially cloning the underlying value and then setting it,
/// giving you a mutable handle in the process. This method is intended for
/// types that are cheaply cloneable.
///
/// # Warning
/// Be careful with `RefMut` since you might panic if the `RefCell` is left open!
///
/// # Examples
///
/// ```
/// let (val, set_val) = use_state(&cx, || 0);
///
/// set_val.with_mut(|v| *v = 1);
/// ```
#[must_use]
pub fn make_mut(&self) -> RefMut<T> {
let mut slot = self.slot.borrow_mut();
self.needs_update();
if Rc::strong_count(&*slot) > 0 {
*slot = Rc::new(slot.as_ref().to_owned());
}
RefMut::map(slot, |rc| Rc::get_mut(rc).expect("the hard count to be 0"))
}
}
impl<T: 'static> Clone for UseState<T> {
fn clone(&self) -> Self {
UseState {
current_val: self.current_val.clone(),
update_callback: self.update_callback.clone(),
setter: self.setter.clone(),
slot: self.slot.clone(),
}
}
}
impl<'a, T: 'static + Display> std::fmt::Display for UseState<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.current_val)
}
}
impl<T> PartialEq<UseState<T>> for UseState<T> {
fn eq(&self, other: &UseState<T>) -> bool {
// some level of memoization for UseState
Rc::ptr_eq(&self.slot, &other.slot)
}
}
impl<T: Debug> Debug for UseState<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.current_val)
}
}
impl<'a, T> std::ops::Deref for UseState<T> {
type Target = Rc<dyn Fn(T)>;
fn deref(&self) -> &Self::Target {
&self.setter
}
}
#[test]
fn api_makes_sense() {
#[allow(unused)]
fn app(cx: Scope) -> Element {
let (val, set_val) = use_state(&cx, || 0);
set_val(0);
set_val.modify(|v| v + 1);
let real_current = set_val.current();
match val {
10 => {
set_val(20);
set_val.modify(|v| v + 1);
}
20 => {}
_ => {
println!("{real_current}");
}
}
cx.spawn({
crate::to_owned![set_val];
async move {
set_val.modify(|f| f + 1);
}
});
cx.render(LazyNodes::new(|f| f.static_text("asd")))
}
}
-215
View File
@@ -1,215 +0,0 @@
use super::owned::UseStateOwned;
use std::{
cell::{Ref, RefMut},
fmt::{Debug, Display},
rc::Rc,
};
pub struct UseState<'a, T: 'static>(pub(crate) &'a UseStateOwned<T>);
impl<T> Copy for UseState<'_, T> {}
impl<'a, T: 'static> Clone for UseState<'a, T> {
fn clone(&self) -> Self {
UseState(self.0)
}
}
impl<T: Debug> Debug for UseState<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0.current_val)
}
}
impl<'a, T: 'static> UseState<'a, T> {
/// Tell the Dioxus Scheduler that we need to be processed
pub fn needs_update(&self) {
if !self.0.update_scheuled.get() {
self.0.update_scheuled.set(true);
(self.0.update_callback)();
}
}
pub fn set(&self, new_val: T) {
*self.0.wip.borrow_mut() = Some(new_val);
self.needs_update();
}
pub fn get(&self) -> &'a T {
&self.0.current_val
}
pub fn get_rc(&self) -> &'a Rc<T> {
&self.0.current_val
}
/// Get the current status of the work-in-progress data
pub fn get_wip(&self) -> Ref<Option<T>> {
self.0.wip.borrow()
}
/// Get the current status of the work-in-progress data
pub fn get_wip_mut(&self) -> RefMut<Option<T>> {
self.0.wip.borrow_mut()
}
pub fn classic(self) -> (&'a T, Rc<dyn Fn(T)>) {
(&self.0.current_val, self.setter())
}
pub fn setter(&self) -> Rc<dyn Fn(T)> {
let slot = self.0.wip.clone();
let callback = self.0.update_callback.clone();
Rc::new(move |new| {
callback();
*slot.borrow_mut() = Some(new)
})
}
pub fn wtih(&self, f: impl FnOnce(&mut T)) {
let mut val = self.0.wip.borrow_mut();
if let Some(inner) = val.as_mut() {
f(inner);
}
}
pub fn for_async(&self) -> UseStateOwned<T> {
let UseStateOwned {
current_val,
wip,
update_callback,
update_scheuled,
} = self.0;
UseStateOwned {
current_val: current_val.clone(),
wip: wip.clone(),
update_callback: update_callback.clone(),
update_scheuled: update_scheuled.clone(),
}
}
}
impl<'a, T: 'static + ToOwned<Owned = T>> UseState<'a, T> {
/// Gain mutable access to the new value via [`RefMut`].
///
/// If `modify` is called, then the component will re-render.
///
/// This method is only available when the value is a `ToOwned` type.
///
/// Mutable access is derived by calling "ToOwned" (IE cloning) on the current value.
///
/// To get a reference to the current value, use `.get()`
pub fn modify(self) -> RefMut<'a, T> {
// make sure we get processed
self.needs_update();
// Bring out the new value, cloning if it we need to
// "get_mut" is locked behind "ToOwned" to make it explicit that cloning occurs to use this
RefMut::map(self.0.wip.borrow_mut(), |slot| {
if slot.is_none() {
*slot = Some(self.0.current_val.as_ref().to_owned());
}
slot.as_mut().unwrap()
})
}
pub fn inner(self) -> T {
self.0.current_val.as_ref().to_owned()
}
}
impl<'a, T> std::ops::Deref for UseState<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.get()
}
}
// enable displaty for the handle
impl<'a, T: 'static + Display> std::fmt::Display for UseState<'a, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.current_val)
}
}
impl<'a, V, T: PartialEq<V>> PartialEq<V> for UseState<'a, T> {
fn eq(&self, other: &V) -> bool {
self.get() == other
}
}
impl<'a, O, T: std::ops::Not<Output = O> + Copy> std::ops::Not for UseState<'a, T> {
type Output = O;
fn not(self) -> Self::Output {
!*self.get()
}
}
/*
Convenience methods for UseState.
Note!
This is not comprehensive.
This is *just* meant to make common operations easier.
*/
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
impl<'a, T: Copy + Add<T, Output = T>> Add<T> for UseState<'a, T> {
type Output = T;
fn add(self, rhs: T) -> Self::Output {
self.0.current_val.add(rhs)
}
}
impl<'a, T: Copy + Add<T, Output = T>> AddAssign<T> for UseState<'a, T> {
fn add_assign(&mut self, rhs: T) {
self.set(self.0.current_val.add(rhs));
}
}
/// Sub
impl<'a, T: Copy + Sub<T, Output = T>> Sub<T> for UseState<'a, T> {
type Output = T;
fn sub(self, rhs: T) -> Self::Output {
self.0.current_val.sub(rhs)
}
}
impl<'a, T: Copy + Sub<T, Output = T>> SubAssign<T> for UseState<'a, T> {
fn sub_assign(&mut self, rhs: T) {
self.set(self.0.current_val.sub(rhs));
}
}
/// MUL
impl<'a, T: Copy + Mul<T, Output = T>> Mul<T> for UseState<'a, T> {
type Output = T;
fn mul(self, rhs: T) -> Self::Output {
self.0.current_val.mul(rhs)
}
}
impl<'a, T: Copy + Mul<T, Output = T>> MulAssign<T> for UseState<'a, T> {
fn mul_assign(&mut self, rhs: T) {
self.set(self.0.current_val.mul(rhs));
}
}
/// DIV
impl<'a, T: Copy + Div<T, Output = T>> Div<T> for UseState<'a, T> {
type Output = T;
fn div(self, rhs: T) -> Self::Output {
self.0.current_val.div(rhs)
}
}
impl<'a, T: Copy + Div<T, Output = T>> DivAssign<T> for UseState<'a, T> {
fn div_assign(&mut self, rhs: T) {
self.set(self.0.current_val.div(rhs));
}
}
-78
View File
@@ -1,78 +0,0 @@
mod handle;
mod owned;
pub use handle::*;
pub use owned::*;
use dioxus_core::prelude::*;
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
/// Store state between component renders!
///
/// ## Dioxus equivalent of useState, designed for Rust
///
/// The Dioxus version of `useState` for state management inside components. It allows you to ergonomically store and
/// modify state between component renders. When the state is updated, the component will re-render.
///
/// Dioxus' use_state basically wraps a RefCell with helper methods and integrates it with the VirtualDOM update system.
///
/// [`use_state`] exposes a few helper methods to modify the underlying state:
/// - `.set(new)` allows you to override the "work in progress" value with a new value
/// - `.get_mut()` allows you to modify the WIP value
/// - `.get_wip()` allows you to access the WIP value
/// - `.deref()` provides the previous value (often done implicitly, though a manual dereference with `*` might be required)
///
/// Additionally, a ton of std::ops traits are implemented for the `UseState` wrapper, meaning any mutative type operations
/// will automatically be called on the WIP value.
///
/// ## Combinators
///
/// On top of the methods to set/get state, `use_state` also supports fancy combinators to extend its functionality:
/// - `.classic()` and `.split()` convert the hook into the classic React-style hook
/// ```rust
/// let (state, set_state) = use_state(&cx, || 10).split()
/// ```
///
///
/// Usage:
///
/// ```ignore
/// const Example: Component = |cx| {
/// let counter = use_state(&cx, || 0);
///
/// cx.render(rsx! {
/// div {
/// h1 { "Counter: {counter}" }
/// button { onclick: move |_| counter += 1, "Increment" }
/// button { onclick: move |_| counter -= 1, "Decrement" }
/// }
/// ))
/// }
/// ```
pub fn use_state<'a, T: 'static>(
cx: &'a ScopeState,
initial_state_fn: impl FnOnce() -> T,
) -> UseState<'a, T> {
let hook = cx.use_hook(move |_| UseStateOwned {
current_val: Rc::new(initial_state_fn()),
update_callback: cx.schedule_update(),
wip: Rc::new(RefCell::new(None)),
update_scheuled: Cell::new(false),
});
hook.update_scheuled.set(false);
let mut new_val = hook.wip.borrow_mut();
if new_val.is_some() {
// if there's only one reference (weak or otherwise), we can just swap the values
if let Some(val) = Rc::get_mut(&mut hook.current_val) {
*val = new_val.take().unwrap();
} else {
hook.current_val = Rc::new(new_val.take().unwrap());
}
}
UseState(hook)
}
-99
View File
@@ -1,99 +0,0 @@
use std::{
cell::{Cell, Ref, RefCell, RefMut},
fmt::{Debug, Display},
rc::Rc,
};
pub struct UseStateOwned<T: 'static> {
// this will always be outdated
pub(crate) current_val: Rc<T>,
pub(crate) wip: Rc<RefCell<Option<T>>>,
pub(crate) update_callback: Rc<dyn Fn()>,
pub(crate) update_scheuled: Cell<bool>,
}
impl<T> UseStateOwned<T> {
pub fn get(&self) -> Ref<Option<T>> {
self.wip.borrow()
}
pub fn set(&self, new_val: T) {
*self.wip.borrow_mut() = Some(new_val);
(self.update_callback)();
}
pub fn modify(&self) -> RefMut<Option<T>> {
(self.update_callback)();
self.wip.borrow_mut()
}
}
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
impl<T: Debug> Debug for UseStateOwned<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.current_val)
}
}
// enable displaty for the handle
impl<'a, T: 'static + Display> std::fmt::Display for UseStateOwned<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.current_val)
}
}
impl<'a, T: Copy + Add<T, Output = T>> Add<T> for UseStateOwned<T> {
type Output = T;
fn add(self, rhs: T) -> Self::Output {
self.current_val.add(rhs)
}
}
impl<'a, T: Copy + Add<T, Output = T>> AddAssign<T> for UseStateOwned<T> {
fn add_assign(&mut self, rhs: T) {
self.set(self.current_val.add(rhs));
}
}
/// Sub
impl<'a, T: Copy + Sub<T, Output = T>> Sub<T> for UseStateOwned<T> {
type Output = T;
fn sub(self, rhs: T) -> Self::Output {
self.current_val.sub(rhs)
}
}
impl<'a, T: Copy + Sub<T, Output = T>> SubAssign<T> for UseStateOwned<T> {
fn sub_assign(&mut self, rhs: T) {
self.set(self.current_val.sub(rhs));
}
}
/// MUL
impl<'a, T: Copy + Mul<T, Output = T>> Mul<T> for UseStateOwned<T> {
type Output = T;
fn mul(self, rhs: T) -> Self::Output {
self.current_val.mul(rhs)
}
}
impl<'a, T: Copy + Mul<T, Output = T>> MulAssign<T> for UseStateOwned<T> {
fn mul_assign(&mut self, rhs: T) {
self.set(self.current_val.mul(rhs));
}
}
/// DIV
impl<'a, T: Copy + Div<T, Output = T>> Div<T> for UseStateOwned<T> {
type Output = T;
fn div(self, rhs: T) -> Self::Output {
self.current_val.div(rhs)
}
}
impl<'a, T: Copy + Div<T, Output = T>> DivAssign<T> for UseStateOwned<T> {
fn div_assign(&mut self, rhs: T) {
self.set(self.current_val.div(rhs));
}
}
+33 -2
View File
@@ -5,6 +5,36 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Bug Fixes
- <csr-id-43e78d56f72e23ada939f5688a6bd2fdd9b8292d/> rustfmt
### Commit Statistics
<csr-read-only-do-not-edit/>
- 7 commits contributed to the release over the course of 19 calendar days.
- 1 commit where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- rustfmt ([`43e78d5`](https://github.comgit//DioxusLabs/dioxus/commit/43e78d56f72e23ada939f5688a6bd2fdd9b8292d))
- Add gap and row_gap to style_trait_methods ([`5f4a724`](https://github.comgit//DioxusLabs/dioxus/commit/5f4a72446e63441628e18bb19fd9b2d9f65f9d52))
- Merge pull request #111 from DioxusLabs/jk/props-attrs ([`0369fe7`](https://github.comgit//DioxusLabs/dioxus/commit/0369fe72fb247409da300a54ef11ba9155d0efb3))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- Merge pull request #113 from DioxusLabs/jk/desktop-cursor-jump ([`20a2940`](https://github.comgit//DioxusLabs/dioxus/commit/20a29409b22510b001fdbee349724adb7b44d401))
- feat(events:focus): add missing `onfocusin` event ([`007d06d`](https://github.comgit//DioxusLabs/dioxus/commit/007d06d602f1adfaa51c87ec89b2afe90d8cdef9))
- feat(example:todomvc): add editing support ([`9849f68`](https://github.comgit//DioxusLabs/dioxus/commit/9849f68f257200fac511c048bfb1a076243b86d3))
</details>
## v0.1.4 (2022-01-08)
### Documentation
@@ -42,7 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 60 commits contributed to the release over the course of 184 calendar days.
- 61 commits contributed to the release over the course of 184 calendar days.
- 52 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -53,8 +83,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- enable prevent_default everywhere ([`9dff700`](https://github.comgit//DioxusLabs/dioxus/commit/9dff700c220dd9e0da2ee028900e82fd24f9d0dd))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- component pass thru events ([`c439b0a`](https://github.comgit//DioxusLabs/dioxus/commit/c439b0ac7e09f70a04262b7c29938d8c52197b76))
- memoize dom in the prescence of identical components ([`cb2782b`](https://github.comgit//DioxusLabs/dioxus/commit/cb2782b4bb34cdaadfff590bfee930ae3ac6536c))
- new versions of everything ([`4ea5c99`](https://github.comgit//DioxusLabs/dioxus/commit/4ea5c990d72b1645724ab0a88ffea2baf28e2835))
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-html"
version = "0.1.4"
version = "0.1.6"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "HTML Element pack for Dioxus - a concurrent renderer-agnostic Virtual DOM for interactive user experiences"
@@ -11,7 +11,7 @@ documentation = "https://docs.rs/dioxus"
keywords = ["dom", "ui", "gui", "react", "wasm"]
[dependencies]
dioxus-core = { path = "../core", version ="^0.1.7"}
dioxus-core = { path = "../core", version = "^0.1.9" }
serde = { version = "1", features = ["derive"], optional = true }
serde_repr = { version = "0.1", optional = true }
+9 -9
View File
@@ -42,7 +42,7 @@ The HTML namespace is defined mostly with macros. However, the expanded form wou
struct base;
impl DioxusElement for base {
const TAG_NAME: &'static str = "base";
const NAME_SPACE: Option<&'static str> = None;
const NAME_SPACE: Option<&'static str> = None;
}
impl base {
#[inline]
@@ -60,7 +60,7 @@ Because attributes are defined as methods on the unit struct, they guard the att
## How to extend it:
Whenever the rsx! macro is called, it relies on a module `dioxus_elements` to be in scope. When you enable the `html` feature in dioxus, this module gets imported in the prelude. However, you can extend this with your own set of custom elements by making your own `dioxus_elements` module and re-exporting the html namespace.
Whenever the rsx! macro is called, it relies on a module `dioxus_elements` to be in scope. When you enable the `html` feature in dioxus, this module gets imported in the prelude. However, you can extend this with your own set of custom elements by making your own `dioxus_elements` module and re-exporting the html namespace.
```rust
mod dioxus_elements {
@@ -68,13 +68,13 @@ mod dioxus_elements {
struct my_element;
impl DioxusElement for my_element {
const TAG_NAME: &'static str = "base";
const NAME_SPACE: Option<&'static str> = None;
const NAME_SPACE: Option<&'static str> = None;
}
}
```
## Limitations:
-
-
## How to work around it:
If an attribute in Dioxus is invalid (defined incorrectly) - first, make an issue - but then, you can work around it. The raw builder API is actually somewhat ergonomic to work with, and the NodeFactory type exposes a bunch of methods to make any type of tree - even invalid ones! So obviously, be careful, but there's basically anything you can do.
@@ -87,19 +87,19 @@ cx.render(rsx!{
{LazyNodes::new(move |f| {
f.raw_element(
// tag name
"custom_element",
"custom_element",
// attributes
&[f.attr("billy", format_args!("goat"))],
&[f.attr("billy", format_args!("goat"))],
// listeners
&[f.listener(onclick(move |_| {}))],
&[f.listener(onclick(move |_| {}))],
// children
&[cx.render(rsx!(div {} ))],
&[cx.render(rsx!(div {} ))],
// key
None
None
)
})}
}
+1 -6
View File
@@ -1047,7 +1047,7 @@ impl input {
/// - `text`
/// - `time`
/// - `url`
/// - `week`
/// - `week`
pub fn r#type<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
cx.attr("type", val, None, false)
}
@@ -1100,11 +1100,6 @@ impl label {
cx.attr("for", val, None, false)
}
}
impl a {
pub fn prevent_default<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
cx.attr("dioxus-prevent-default", val, None, false)
}
}
builder_constructors! {
// SVG components
+3
View File
@@ -3,6 +3,8 @@ use dioxus_core::exports::bumpalo;
use dioxus_core::*;
pub mod on {
use std::collections::HashMap;
use super::*;
macro_rules! event_directory {
( $(
@@ -484,6 +486,7 @@ pub mod on {
#[derive(Debug)]
pub struct FormData {
pub value: String,
pub values: HashMap<String, String>,
/* DOMEvent: Send + SyncTarget relatedTarget */
}
+22
View File
@@ -49,6 +49,10 @@ macro_rules! aria_trait_methods {
}
pub trait GlobalAttributes {
/// Prevent the default action for this element.
///
/// For more information, see the MDN docs:
/// <https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault>
fn prevent_default<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
cx.attr("dioxus-prevent-default", val, None, false)
}
@@ -399,6 +403,9 @@ pub trait GlobalAttributes {
/// Specify the font weight of the text.
font_weight: "font-weight",
/// Sets gaps (gutters) between rows and columns. Shorthand for row_gap and column_gap.
gap: "gap",
/// Specify the height of an element.
height: "height",
@@ -531,6 +538,9 @@ pub trait GlobalAttributes {
/// Specify the location of the right edge of the positioned element.
right: "right",
/// Specifies the gap between the rows in a multi_column element.
row_gap: "row-gap",
/// Specifies the length of the tab character.
tab_size: "tab-size",
@@ -597,6 +607,11 @@ pub trait GlobalAttributes {
/// Specifies the speed curve of the transition effect.
transition_timing_function: "transition-timing-function",
/// The user-select CSS property controls whether the user can select text.
/// This doesn't have any effect on content loaded as part of a browser's user interface (its chrome), except in textboxes.
user_select: "user-select",
webkit_user_select: "-webkit-user-select",
/// Sets the vertical positioning of an element relative to the current text baseline.
vertical_align: "vertical-align",
@@ -679,6 +694,13 @@ pub trait GlobalAttributes {
}
pub trait SvgAttributes {
/// Prevent the default action for this element.
///
/// For more information, see the MDN docs:
/// <https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault>
fn prevent_default<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
cx.attr("dioxus-prevent-default", val, None, false)
}
aria_trait_methods! {
accent_height: "accent-height",
accumulate: "accumulate",
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "dioxus-interpreter-js"
version = "0.0.0"
edition = "2018"
authors = ["Jonathan Kelley"]
description = "JS Intepreter for Dioxus - a concurrent renderer-agnostic Virtual DOM for interactive user experiences"
license = "MIT OR Apache-2.0"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com"
documentation = "https://docs.rs/dioxus"
keywords = ["dom", "ui", "gui", "react", "wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
wasm-bindgen = { version = "0.2.79", optional = true }
js-sys = { version = "0.3.56", optional = true }
web-sys = { version = "0.3.56", optional = true, features = ["Element", "Node"] }
[features]
default = []
web = ["wasm-bindgen", "js-sys", "web-sys"]
+7
View File
@@ -0,0 +1,7 @@
# JS Interpreter
After diffing old and new trees, the Dioxus VirtualDom produces patches that are used to modify the existing Dom. We can send these patches anywhere - including targets without WASM support.
In renderers with support for JavaScript, we use the interpreter from this repository - written in TypeScript - to patch the Dom. This lets us circumvent any overhead on the Rust <-> Dom boundary and keep consistency in our interpreter implementation in web/webview targets.
For now - both Dioxus Web and Dioxus Desktop (webview) use the same interpreter code with tweaks.
+67
View File
@@ -0,0 +1,67 @@
#![allow(clippy::unused_unit, non_upper_case_globals)]
use js_sys::Function;
use wasm_bindgen::prelude::*;
use web_sys::{Element, Node};
#[wasm_bindgen(module = "/src/interpreter.js")]
extern "C" {
pub type Interpreter;
#[wasm_bindgen(constructor)]
pub fn new(arg: Element) -> Interpreter;
#[wasm_bindgen(method)]
pub fn set_node(this: &Interpreter, id: usize, node: Node);
#[wasm_bindgen(method)]
pub fn PushRoot(this: &Interpreter, root: u64);
#[wasm_bindgen(method)]
pub fn AppendChildren(this: &Interpreter, many: u32);
#[wasm_bindgen(method)]
pub fn ReplaceWith(this: &Interpreter, root: u64, m: u32);
#[wasm_bindgen(method)]
pub fn InsertAfter(this: &Interpreter, root: u64, n: u32);
#[wasm_bindgen(method)]
pub fn InsertBefore(this: &Interpreter, root: u64, n: u32);
#[wasm_bindgen(method)]
pub fn Remove(this: &Interpreter, root: u64);
#[wasm_bindgen(method)]
pub fn CreateTextNode(this: &Interpreter, text: JsValue, root: u64);
#[wasm_bindgen(method)]
pub fn CreateElement(this: &Interpreter, tag: &str, root: u64);
#[wasm_bindgen(method)]
pub fn CreateElementNs(this: &Interpreter, tag: &str, root: u64, ns: &str);
#[wasm_bindgen(method)]
pub fn CreatePlaceholder(this: &Interpreter, root: u64);
#[wasm_bindgen(method)]
pub fn NewEventListener(this: &Interpreter, name: &str, root: u64, handler: &Function);
#[wasm_bindgen(method)]
pub fn RemoveEventListener(this: &Interpreter, root: u64, name: &str);
#[wasm_bindgen(method)]
pub fn SetText(this: &Interpreter, root: u64, text: JsValue);
#[wasm_bindgen(method)]
pub fn SetAttribute(
this: &Interpreter,
root: u64,
field: &str,
value: JsValue,
ns: Option<&str>,
);
#[wasm_bindgen(method)]
pub fn RemoveAttribute(this: &Interpreter, root: u64, field: &str);
}
+574
View File
@@ -0,0 +1,574 @@
export function main() {
let root = window.document.getElementById("main");
if (root != null) {
window.interpreter = new Interpreter(root);
window.rpc.call("initialize");
}
}
export class Interpreter {
constructor(root) {
this.root = root;
this.stack = [root];
this.listeners = {};
this.handlers = {};
this.lastNodeWasText = false;
this.nodes = [root];
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
return this.stack.pop();
}
PushRoot(root) {
const node = this.nodes[root];
this.stack.push(node);
}
AppendChildren(many) {
let root = this.stack[this.stack.length - (1 + many)];
let to_add = this.stack.splice(this.stack.length - many);
for (let i = 0; i < many; i++) {
root.appendChild(to_add[i]);
}
}
ReplaceWith(root_id, m) {
let root = this.nodes[root_id];
let els = this.stack.splice(this.stack.length - m);
root.replaceWith(...els);
}
InsertAfter(root, n) {
let old = this.nodes[root];
let new_nodes = this.stack.splice(this.stack.length - n);
old.after(...new_nodes);
}
InsertBefore(root, n) {
let old = this.nodes[root];
let new_nodes = this.stack.splice(this.stack.length - n);
old.before(...new_nodes);
}
Remove(root) {
let node = this.nodes[root];
if (node !== undefined) {
node.remove();
}
}
CreateTextNode(text, root) {
// todo: make it so the types are okay
const node = document.createTextNode(text);
this.nodes[root] = node;
this.stack.push(node);
}
CreateElement(tag, root) {
const el = document.createElement(tag);
// el.setAttribute("data-dioxus-id", `${root}`);
this.nodes[root] = el;
this.stack.push(el);
}
CreateElementNs(tag, root, ns) {
let el = document.createElementNS(ns, tag);
this.stack.push(el);
this.nodes[root] = el;
}
CreatePlaceholder(root) {
let el = document.createElement("pre");
el.hidden = true;
this.stack.push(el);
this.nodes[root] = el;
}
NewEventListener(event_name, root, handler) {
const element = this.nodes[root];
element.setAttribute("data-dioxus-id", `${root}`);
if (this.listeners[event_name] === undefined) {
this.listeners[event_name] = 0;
this.handlers[event_name] = handler;
this.root.addEventListener(event_name, handler);
} else {
this.listeners[event_name]++;
}
}
RemoveEventListener(root, event_name) {
const element = this.nodes[root];
element.removeAttribute(`data-dioxus-id`);
this.listeners[event_name]--;
if (this.listeners[event_name] === 0) {
this.root.removeEventListener(event_name, this.handlers[event_name]);
delete this.listeners[event_name];
delete this.handlers[event_name];
}
}
SetText(root, text) {
this.nodes[root].textContent = text;
}
SetAttribute(root, field, value, ns) {
const name = field;
const node = this.nodes[root];
if (ns === "style") {
// @ts-ignore
node.style[name] = value;
} else if (ns != null || ns !== undefined) {
node.setAttributeNS(ns, name, value);
} else {
switch (name) {
case "value":
if (value !== node.value) {
node.value = value;
}
break;
case "checked":
node.checked = value === "true";
break;
case "selected":
node.selected = value === "true";
break;
case "dangerous_inner_html":
node.innerHTML = value;
break;
default:
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if (value === "false" && bool_attrs.hasOwnProperty(name)) {
node.removeAttribute(name);
} else {
node.setAttribute(name, value);
}
}
}
}
RemoveAttribute(root, name) {
const node = this.nodes[root];
if (name === "value") {
node.value = "";
} else if (name === "checked") {
node.checked = false;
} else if (name === "selected") {
node.selected = false;
} else if (name === "dangerous_inner_html") {
node.innerHTML = "";
} else {
node.removeAttribute(name);
}
}
handleEdits(edits) {
this.stack.push(this.root);
for (let edit of edits) {
this.handleEdit(edit);
}
}
handleEdit(edit) {
switch (edit.type) {
case "PushRoot":
this.PushRoot(edit.root);
break;
case "AppendChildren":
this.AppendChildren(edit.many);
break;
case "ReplaceWith":
this.ReplaceWith(edit.root, edit.m);
break;
case "InsertAfter":
this.InsertAfter(edit.root, edit.n);
break;
case "InsertBefore":
this.InsertBefore(edit.root, edit.n);
break;
case "Remove":
this.Remove(edit.root);
break;
case "CreateTextNode":
this.CreateTextNode(edit.text, edit.root);
break;
case "CreateElement":
this.CreateElement(edit.tag, edit.root);
break;
case "CreateElementNs":
this.CreateElementNs(edit.tag, edit.root, edit.ns);
break;
case "CreatePlaceholder":
this.CreatePlaceholder(edit.root);
break;
case "RemoveEventListener":
this.RemoveEventListener(edit.root, edit.event_name);
break;
case "NewEventListener":
// this handler is only provided on desktop implementations since this
// method is not used by the web implementation
let handler = (event) => {
let target = event.target;
if (target != null) {
let realId = target.getAttribute(`data-dioxus-id`);
let shouldPreventDefault = target.getAttribute(
`dioxus-prevent-default`
);
if (event.type === "click") {
// todo call prevent default if it's the right type of event
if (shouldPreventDefault !== `onclick`) {
if (target.tagName === "A") {
event.preventDefault();
const href = target.getAttribute("href");
if (href !== "" && href !== null && href !== undefined) {
window.rpc.call("browser_open", { href });
}
}
}
// also prevent buttons from submitting
if (target.tagName === "BUTTON") {
event.preventDefault();
}
}
// walk the tree to find the real element
while (realId == null) {
// we've reached the root we don't want to send an event
if (target.parentElement === null) {
return;
}
target = target.parentElement;
realId = target.getAttribute(`data-dioxus-id`);
}
shouldPreventDefault = target.getAttribute(
`dioxus-prevent-default`
);
let contents = serialize_event(event);
if (shouldPreventDefault === `on${event.type}`) {
event.preventDefault();
}
if (event.type === "submit") {
event.preventDefault();
}
if (target.tagName === "FORM") {
for (let x = 0; x < target.elements.length; x++) {
let element = target.elements[x];
let name = element.getAttribute("name");
if (name != null) {
if (element.getAttribute("type") === "checkbox") {
// @ts-ignore
contents.values[name] = element.checked ? "true" : "false";
} else {
// @ts-ignore
contents.values[name] =
element.value ?? element.textContent;
}
}
}
}
if (realId == null) {
return;
}
window.rpc.call("user_event", {
event: edit.event_name,
mounted_dom_id: parseInt(realId),
contents: contents,
});
}
};
this.NewEventListener(edit.event_name, edit.root, handler);
break;
case "SetText":
this.SetText(edit.root, edit.text);
break;
case "SetAttribute":
this.SetAttribute(edit.root, edit.field, edit.value, edit.ns);
break;
case "RemoveAttribute":
this.RemoveAttribute(edit.root, edit.name);
break;
}
}
}
export function serialize_event(event) {
switch (event.type) {
case "copy":
case "cut":
case "past": {
return {};
}
case "compositionend":
case "compositionstart":
case "compositionupdate": {
let { data } = event;
return {
data,
};
}
case "keydown":
case "keypress":
case "keyup": {
let {
charCode,
key,
altKey,
ctrlKey,
metaKey,
keyCode,
shiftKey,
location,
repeat,
which,
} = event;
return {
char_code: charCode,
key: key,
alt_key: altKey,
ctrl_key: ctrlKey,
meta_key: metaKey,
key_code: keyCode,
shift_key: shiftKey,
location: location,
repeat: repeat,
which: which,
locale: "locale",
};
}
case "focus":
case "blur": {
return {};
}
case "change": {
let target = event.target;
let value;
if (target.type === "checkbox" || target.type === "radio") {
value = target.checked ? "true" : "false";
} else {
value = target.value ?? target.textContent;
}
return {
value: value,
};
}
case "input":
case "invalid":
case "reset":
case "submit": {
let target = event.target;
let value = target.value ?? target.textContent;
if (target.type === "checkbox") {
value = target.checked ? "true" : "false";
}
return {
value: value,
values: {},
};
}
case "click":
case "contextmenu":
case "doubleclick":
case "drag":
case "dragend":
case "dragenter":
case "dragexit":
case "dragleave":
case "dragover":
case "dragstart":
case "drop":
case "mousedown":
case "mouseenter":
case "mouseleave":
case "mousemove":
case "mouseout":
case "mouseover":
case "mouseup": {
const {
altKey,
button,
buttons,
clientX,
clientY,
ctrlKey,
metaKey,
pageX,
pageY,
screenX,
screenY,
shiftKey,
} = event;
return {
alt_key: altKey,
button: button,
buttons: buttons,
client_x: clientX,
client_y: clientY,
ctrl_key: ctrlKey,
meta_key: metaKey,
page_x: pageX,
page_y: pageY,
screen_x: screenX,
screen_y: screenY,
shift_key: shiftKey,
};
}
case "pointerdown":
case "pointermove":
case "pointerup":
case "pointercancel":
case "gotpointercapture":
case "lostpointercapture":
case "pointerenter":
case "pointerleave":
case "pointerover":
case "pointerout": {
const {
altKey,
button,
buttons,
clientX,
clientY,
ctrlKey,
metaKey,
pageX,
pageY,
screenX,
screenY,
shiftKey,
pointerId,
width,
height,
pressure,
tangentialPressure,
tiltX,
tiltY,
twist,
pointerType,
isPrimary,
} = event;
return {
alt_key: altKey,
button: button,
buttons: buttons,
client_x: clientX,
client_y: clientY,
ctrl_key: ctrlKey,
meta_key: metaKey,
page_x: pageX,
page_y: pageY,
screen_x: screenX,
screen_y: screenY,
shift_key: shiftKey,
pointer_id: pointerId,
width: width,
height: height,
pressure: pressure,
tangential_pressure: tangentialPressure,
tilt_x: tiltX,
tilt_y: tiltY,
twist: twist,
pointer_type: pointerType,
is_primary: isPrimary,
};
}
case "select": {
return {};
}
case "touchcancel":
case "touchend":
case "touchmove":
case "touchstart": {
const { altKey, ctrlKey, metaKey, shiftKey } = event;
return {
// changed_touches: event.changedTouches,
// target_touches: event.targetTouches,
// touches: event.touches,
alt_key: altKey,
ctrl_key: ctrlKey,
meta_key: metaKey,
shift_key: shiftKey,
};
}
case "scroll": {
return {};
}
case "wheel": {
const { deltaX, deltaY, deltaZ, deltaMode } = event;
return {
delta_x: deltaX,
delta_y: deltaY,
delta_z: deltaZ,
delta_mode: deltaMode,
};
}
case "animationstart":
case "animationend":
case "animationiteration": {
const { animationName, elapsedTime, pseudoElement } = event;
return {
animation_name: animationName,
elapsed_time: elapsedTime,
pseudo_element: pseudoElement,
};
}
case "transitionend": {
const { propertyName, elapsedTime, pseudoElement } = event;
return {
property_name: propertyName,
elapsed_time: elapsedTime,
pseudo_element: pseudoElement,
};
}
case "abort":
case "canplay":
case "canplaythrough":
case "durationchange":
case "emptied":
case "encrypted":
case "ended":
case "error":
case "loadeddata":
case "loadedmetadata":
case "loadstart":
case "pause":
case "play":
case "playing":
case "progress":
case "ratechange":
case "seeked":
case "seeking":
case "stalled":
case "suspend":
case "timeupdate":
case "volumechange":
case "waiting": {
return {};
}
case "toggle": {
return {};
}
default: {
return {};
}
}
}
const bool_attrs = {
allowfullscreen: true,
allowpaymentrequest: true,
async: true,
autofocus: true,
autoplay: true,
checked: true,
controls: true,
default: true,
defer: true,
disabled: true,
formnovalidate: true,
hidden: true,
ismap: true,
itemscope: true,
loop: true,
multiple: true,
muted: true,
nomodule: true,
novalidate: true,
open: true,
playsinline: true,
readonly: true,
required: true,
reversed: true,
selected: true,
truespeed: true,
};
+7
View File
@@ -0,0 +1,7 @@
pub static INTERPRTER_JS: &str = include_str!("./interpreter.js");
#[cfg(feature = "web")]
mod bindings;
#[cfg(feature = "web")]
pub use bindings::Interpreter;
+2 -2
View File
@@ -20,7 +20,7 @@ async fn main() -> tide::Result<()> {
}
```
Dioxus LiveView runs your Dioxus apps on the server
Dioxus LiveView runs your Dioxus apps on the server
@@ -36,7 +36,7 @@ async fn main() {
async fn order_shoes(mut req: WebsocketRequest) -> Response {
let stream = req.upgrade();
dioxus::liveview::launch(App, stream).await;
dioxus::liveview::launch(App, stream).await;
}
fn App(cx: Scope) -> Element {
+22 -1
View File
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Commit Statistics
<csr-read-only-do-not-edit/>
- 1 commit contributed to the release over the course of 7 calendar days.
- 0 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
</details>
## v0.0.3 (2022-01-08)
### Documentation
@@ -28,7 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 32 commits contributed to the release over the course of 151 calendar days.
- 33 commits contributed to the release over the course of 151 calendar days.
- 21 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -39,6 +59,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`b804c69`](https://github.comgit//DioxusLabs/dioxus/commit/b804c691d5ade4776390bb3d334cc9cd8efa4a49))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
+6 -1
View File
@@ -12,4 +12,9 @@ license = "MIT/Apache-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus-desktop = { path = "../desktop", version ="^0.1.5"}
dioxus-desktop = { path = "../desktop", version = "^0.1.6" }
[lib]
doctest = false
# tests suspended until package ready
test = false
+7
View File
@@ -0,0 +1,7 @@
[tasks.test]
command = "cargo"
args = [
"test",
"--no-run",
]
+1 -1
View File
@@ -21,7 +21,7 @@ $ cargo install --git https://github.com/BrainiumLLC/cargo-mobile
And then initialize your app for the right platform. Use the `winit` template for now. Right now, there's no "Dioxus" template in cargo-mobile.
```shell
$ cargo mobile init
$ cargo mobile init
```
We're going to completely clear out the `dependencies` it generates for us, swapping out `winit` with `dioxus-mobile`.
+57 -1
View File
@@ -5,6 +5,54 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### New Features
- <csr-id-e24957fc191476184816fe5dee249f691170d4ae/> enable use_router
- <csr-id-29ed7ebece26e9d53925af55f2f34a8fd8241405/> connect an onchange listener
- <csr-id-d2372717bd01fcff50af0572360e3f763d4c869d/> flatten props attrs
### Bug Fixes
- <csr-id-5ee9d6c4348a2f51adac827f715fb138918d1dc6/> attach router listener to subscriber list
- <csr-id-a21e7d4dd168129da06f535f9dc4b1de724617cb/> use_route should subscribe to changes to the route
### Commit Statistics
<csr-read-only-do-not-edit/>
- 18 commits contributed to the release over the course of 14 calendar days.
- 7 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Merge pull request #169 from DioxusLabs/jk/router-userouter ([`3509602`](https://github.comgit//DioxusLabs/dioxus/commit/3509602c0bcd327a33bc8c95896775e24751da1a))
- enable use_router ([`e24957f`](https://github.comgit//DioxusLabs/dioxus/commit/e24957fc191476184816fe5dee249f691170d4ae))
- add docs to router UseRouteListener ([`79e0993`](https://github.comgit//DioxusLabs/dioxus/commit/79e09934aa685d03d6e0b323723bc1cd537d74d9))
- Merge pull request #166 from DioxusLabs/jk/default-assets-desktop ([`ccbb955`](https://github.comgit//DioxusLabs/dioxus/commit/ccbb955b7b24bd4e1c5aa40e813a2872ae474a69))
- rustfmt ([`9da46eb`](https://github.comgit//DioxusLabs/dioxus/commit/9da46eb7bc207997ca7779c58fcb2a9645dfa9d0))
- Make log message in Link component trace level, not debug ([`72c6bb3`](https://github.comgit//DioxusLabs/dioxus/commit/72c6bb3d0b7253f084f7e3bcf55d458cb4adeedb))
- attach router listener to subscriber list ([`5ee9d6c`](https://github.comgit//DioxusLabs/dioxus/commit/5ee9d6c4348a2f51adac827f715fb138918d1dc6))
- connect an onchange listener ([`29ed7eb`](https://github.comgit//DioxusLabs/dioxus/commit/29ed7ebece26e9d53925af55f2f34a8fd8241405))
- use_route should subscribe to changes to the route ([`a21e7d4`](https://github.comgit//DioxusLabs/dioxus/commit/a21e7d4dd168129da06f535f9dc4b1de724617cb))
- Merge pull request #95 from DioxusLabs/jk/filedragindrop ([`ca0dd4a`](https://github.comgit//DioxusLabs/dioxus/commit/ca0dd4aa7192d483a195d420363f39d771f3e471))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- flatten props attrs ([`d237271`](https://github.comgit//DioxusLabs/dioxus/commit/d2372717bd01fcff50af0572360e3f763d4c869d))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
- Merge pull request #138 from mrxiaozhuox/master ([`8c7473d`](https://github.comgit//DioxusLabs/dioxus/commit/8c7473d1943dd133f388ec36116c9d8295861b97))
- Add a warning when Link it called outside of a Router context ([`6408058`](https://github.comgit//DioxusLabs/dioxus/commit/64080588d02c54a1d380116cbecdd17de16d2392))
- Merge pull request #133 from mrxiaozhuox/master ([`887f69d`](https://github.comgit//DioxusLabs/dioxus/commit/887f69d5b47bdcde4fe0eab094c0cd0de23e4f3f))
- Fix handling of re-renders in the Router ([`81c094e`](https://github.comgit//DioxusLabs/dioxus/commit/81c094ed29fcdc5c6099492dd6ab09a59b79252c))
</details>
## v0.1.0 (2022-01-08)
### Documentation
@@ -33,7 +81,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 42 commits contributed to the release over the course of 352 calendar days.
- 50 commits contributed to the release over the course of 352 calendar days.
- 35 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -44,8 +92,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`b804c69`](https://github.comgit//DioxusLabs/dioxus/commit/b804c691d5ade4776390bb3d334cc9cd8efa4a49))
- More WIP router implementation ([`e06eac1`](https://github.comgit//DioxusLabs/dioxus/commit/e06eac1ce5c6bb0a6680482574d82b16a141a626))
- Implement UseRoute segment method ([`c9408da`](https://github.comgit//DioxusLabs/dioxus/commit/c9408da7310423b1676fab6d41635f9a8000d89e))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Implement router matching for path parameters ([`f8a7e1c`](https://github.comgit//DioxusLabs/dioxus/commit/f8a7e1cd8255fd7d0116384247e0e305bb73bf3d))
- Commit WIP on router ([`3c6142f`](https://github.comgit//DioxusLabs/dioxus/commit/3c6142fb9d8b5f715adf0fb30c2f3534b9ecd923))
- Add more trace messages to the RouterService code ([`3a5b417`](https://github.comgit//DioxusLabs/dioxus/commit/3a5b417ad1639a31e9aac9f41b05d8b3f074b128))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- Fix typo in RouterService struct's "registered_routes" field name ([`d367e0f`](https://github.comgit//DioxusLabs/dioxus/commit/d367e0f89f1b31484bde42efaf10c3531aed1d64))
- Add title prop to Link ([`e22ba5b`](https://github.comgit//DioxusLabs/dioxus/commit/e22ba5b1e52fe00e08e0b6ac0abae29b6068b8f0))
- add prevent default attribute and upgrade router ([`427b126`](https://github.comgit//DioxusLabs/dioxus/commit/427b126bc17336d5d14d56eb7fddb8e07752495f))
- memoize dom in the prescence of identical components ([`cb2782b`](https://github.comgit//DioxusLabs/dioxus/commit/cb2782b4bb34cdaadfff590bfee930ae3ac6536c))
- bump all versions ([`4f92ba4`](https://github.comgit//DioxusLabs/dioxus/commit/4f92ba41602d706449c1bddabd49829873ee72eb))
+13 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-router"
version = "0.1.0"
version = "0.1.1"
edition = "2018"
description = "Dioxus VirtualDOM renderer for the web browser using websys"
license = "MIT/Apache-2.0"
@@ -11,9 +11,9 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus-core = { path = "../core", version ="^0.1.7", default-features = false }
dioxus-html = { path = "../html", version ="^0.1.4", default-features = false }
dioxus-core-macro = { path = "../core-macro", version ="^0.1.6"}
dioxus-core = { path = "../core", version = "^0.1.9", default-features = false }
dioxus-html = { path = "../html", version = "^0.1.6", default-features = false }
dioxus-core-macro = { path = "../core-macro", version = "^0.1.7" }
serde = "1"
url = "2.2.2"
@@ -43,9 +43,18 @@ web = ["web-sys", "gloo", "js-sys", "wasm-bindgen"]
desktop = []
mobile = []
derive = []
wasm_test = []
[dev-dependencies]
console_error_panic_hook = "0.1.7"
dioxus-web = { path = "../web" }
log = "0.4.14"
wasm-logger = "0.2.0"
wasm-bindgen-test = "0.3"
gloo-utils = "0.1.2"
[dev-dependencies.web-sys]
version = "0.3"
features = [
"Document",
]
+10
View File
@@ -0,0 +1,10 @@
[tasks.test-with-browser]
extend = "core::wasm-pack-base"
command = "wasm-pack"
args = [
"test",
"@@split(DIOXUS_TEST_FLAGS, )",
"--",
"--features",
"${DIOXUS_TEST_FEATURES}",
]
+2 -2
View File
@@ -5,7 +5,7 @@ DioxusRouter adds React-Router style routing to your Dioxus apps. Works in brows
```rust
fn app() {
cx.render(rsx! {
Routes {
Router {
Route { to: "/", Component {} },
Route { to: "/blog", Blog {} },
Route { to: "/blog/:id", BlogPost {} },
@@ -16,7 +16,7 @@ fn app() {
Then, in your route, you can choose to parse the Route any way you want through `use_route`.
```rust
let id: usize = use_route(&cx).path("id")?;
let id: usize = use_route(&cx).segment("id")?;
let state: CustomState = use_route(&cx).parse()?;
```
+5 -13
View File
@@ -1,8 +1,9 @@
#![allow(non_snake_case)]
use dioxus_core::prelude::*;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
use dioxus_router::*;
use serde::{Deserialize, Serialize};
fn main() {
console_error_panic_hook::set_once();
@@ -25,26 +26,17 @@ static APP: Component = |cx| {
fn Home(cx: Scope) -> Element {
cx.render(rsx! {
div {
h1 { "Home" }
}
h1 { "Home" }
})
}
fn BlogList(cx: Scope) -> Element {
cx.render(rsx! {
div {
}
div { "Blog List" }
})
}
fn BlogPost(cx: Scope) -> Element {
let id = use_route(&cx).segment::<usize>("id")?;
cx.render(rsx! {
div {
}
})
cx.render(rsx! { div { "{id:?}" } })
}
+23 -12
View File
@@ -11,7 +11,7 @@ pub struct LinkProps<'a> {
/// The url that gets pushed to the history stack
///
/// You can either put it your own inline method or just autoderive the route using `derive(Routable)`
/// You can either put in your own inline method or just autoderive the route using `derive(Routable)`
///
/// ```rust, ignore
///
@@ -31,6 +31,9 @@ pub struct LinkProps<'a> {
#[props(default, strip_option)]
id: Option<&'a str>,
#[props(default, strip_option)]
title: Option<&'a str>,
children: Element<'a>,
#[props(default)]
@@ -38,17 +41,25 @@ pub struct LinkProps<'a> {
}
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
let service = cx.consume_context::<RouterService>()?;
cx.render(rsx! {
a {
href: "{cx.props.to}",
class: format_args!("{}", cx.props.class.unwrap_or("")),
id: format_args!("{}", cx.props.id.unwrap_or("")),
// log::trace!("render Link to {}", cx.props.to);
if let Some(service) = cx.consume_context::<RouterService>() {
return cx.render(rsx! {
a {
href: "{cx.props.to}",
class: format_args!("{}", cx.props.class.unwrap_or("")),
id: format_args!("{}", cx.props.id.unwrap_or("")),
title: format_args!("{}", cx.props.title.unwrap_or("")),
prevent_default: "onclick",
onclick: move |_| service.push_route(cx.props.to),
prevent_default: "onclick",
onclick: move |_| service.push_route(cx.props.to),
&cx.props.children
}
})
&cx.props.children
}
});
}
log::warn!(
"Attempted to create a Link to {} outside of a Router context",
cx.props.to,
);
None
}
+2 -1
View File
@@ -30,6 +30,7 @@ pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
Some(ctx) => ctx.total_route.to_string(),
None => cx.props.to.to_string(),
};
// log::trace!("total route for {} is {}", cx.props.to, total_route);
// provide our route context
let route_context = cx.provide_context(RouteContext {
@@ -47,7 +48,7 @@ pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
Some(RouteInner {})
});
log::trace!("Checking route {}", cx.props.to);
// log::trace!("Checking route {}", cx.props.to);
if router_root.should_render(cx.scope_id()) {
cx.render(rsx!(&cx.props.children))
+13 -3
View File
@@ -11,17 +11,27 @@ use crate::RouterService;
pub struct RouterProps<'a> {
children: Element<'a>,
#[props(default, strip_option)]
onchange: Option<&'a Fn(&'a str)>,
#[props(default)]
onchange: EventHandler<'a, String>,
}
#[allow(non_snake_case)]
pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element {
cx.use_hook(|_| {
log::debug!("running router {:?}", cx.scope_id());
let svc = cx.use_hook(|_| {
let update = cx.schedule_update_any();
cx.provide_context(RouterService::new(update, cx.scope_id()))
});
let any_pending = svc.pending_events.borrow().len() > 0;
svc.pending_events.borrow_mut().clear();
if any_pending {
let location = svc.current_location();
let path = location.path();
cx.props.onchange.call(path.to_string());
}
cx.render(rsx!(
div { &cx.props.children }
))
+101 -17
View File
@@ -1,30 +1,114 @@
use dioxus_core::ScopeState;
use dioxus_core::{ScopeId, ScopeState};
use gloo::history::{HistoryResult, Location};
use serde::de::DeserializeOwned;
use std::{rc::Rc, str::FromStr};
pub struct UseRoute<'a> {
cur_route: String,
cx: &'a ScopeState,
use crate::RouterService;
/// This struct provides is a wrapper around the internal router
/// implementation, with methods for getting information about the current
/// route.
#[derive(Clone)]
pub struct UseRoute {
router: Rc<RouterService>,
}
impl<'a> UseRoute<'a> {
/// Parse the query part of the URL
pub fn param<T>(&self, param: &str) -> Option<&T> {
todo!()
impl UseRoute {
/// This method simply calls the [`Location::query`] method.
pub fn query<T>(&self) -> HistoryResult<T>
where
T: DeserializeOwned,
{
self.current_location().query::<T>()
}
pub fn nth_segment(&self, n: usize) -> Option<&str> {
todo!()
/// Returns the nth segment in the path. Paths that end with a slash have
/// the slash removed before determining the segments. If the path has
/// fewer segments than `n` then this method returns `None`.
pub fn nth_segment(&self, n: usize) -> Option<String> {
let mut segments = self.path_segments();
let len = segments.len();
if len - 1 < n {
return None;
}
Some(segments.remove(n))
}
pub fn last_segment(&self) -> Option<&'a str> {
todo!()
/// Returns the last segment in the path. Paths that end with a slash have
/// the slash removed before determining the segments. The root path, `/`,
/// will return an empty string.
pub fn last_segment(&self) -> String {
let mut segments = self.path_segments();
segments.remove(segments.len() - 1)
}
/// Parse the segments of the URL, using named parameters (defined in your router)
pub fn segment<T>(&self, name: &str) -> Option<&T> {
todo!()
/// Get the named parameter from the path, as defined in your router. The
/// value will be parsed into the type specified by `T` by calling
/// `value.parse::<T>()`. This method returns `None` if the named
/// parameter does not exist in the current path.
pub fn segment<T>(&self, name: &str) -> Option<Result<T, T::Err>>
where
T: FromStr,
{
self.router
.current_path_params()
.get(name)
.and_then(|v| Some(v.parse::<T>()))
}
/// Returns the [Location] for the current route.
pub fn current_location(&self) -> Location {
self.router.current_location()
}
fn path_segments(&self) -> Vec<String> {
let location = self.router.current_location();
let path = location.path();
if path == "/" {
return vec![String::new()];
}
let stripped = &location.path()[1..];
stripped.split('/').map(str::to_string).collect::<Vec<_>>()
}
}
pub fn use_route<'a>(cx: &'a ScopeState) -> UseRoute<'a> {
todo!()
/// This hook provides access to information about the current location in the
/// context of a [`Router`]. If this function is called outside of a `Router`
/// component it will panic.
pub fn use_route(cx: &ScopeState) -> &UseRoute {
&cx.use_hook(|_| {
let router = cx
.consume_context::<RouterService>()
.expect("Cannot call use_route outside the scope of a Router component");
router.subscribe_onchange(cx.scope_id());
UseRouteListener {
router: UseRoute { router },
scope: cx.scope_id(),
}
})
.router
}
// The entire purpose of this struct is to unubscribe this component when it is unmounted.
// The UseRoute can be cloned into async contexts, so we can't rely on its drop to unubscribe.
// Instead, we hide the drop implementation on this private type exclusive to the hook,
// and reveal our cached version of UseRoute to the component.
struct UseRouteListener {
router: UseRoute,
scope: ScopeId,
}
impl Drop for UseRouteListener {
fn drop(&mut self) {
self.router.router.unsubscribe_onchange(self.scope)
}
}
/// This hook provides access to the `RouterService` for the app.
pub fn use_router(cx: &ScopeState) -> &RouterService {
cx.use_hook(|_| {
cx.consume_context::<RouterService>()
.expect("Cannot call use_route outside the scope of a Router component")
})
}
+1 -14
View File
@@ -8,22 +8,9 @@
//!
//! ```rust
//! fn app(cx: Scope) -> Element {
//!
//! }
//!
//!
//!
//!
//!
//! ```
//!
//!
//!
//!
//!
//!
//!
//!
//!
mod hooks {
mod use_route;
+1 -8
View File
@@ -1,11 +1,4 @@
use url::Url;
pub trait RouterProvider {
fn get_current_route(&self) -> String;
fn subscribe_to_route_changes(&self, callback: Box<dyn Fn(String)>);
}
enum RouteChange {
LinkTo(String),
Back(String),
fn listen(&self, callback: Box<dyn Fn()>);
}
+112 -30
View File
@@ -1,22 +1,33 @@
use gloo::history::{BrowserHistory, History, HistoryListener};
use gloo::history::{BrowserHistory, History, HistoryListener, Location};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
cell::{Cell, Ref, RefCell},
collections::{HashMap, HashSet},
rc::Rc,
};
use dioxus_core::ScopeId;
use crate::platform::RouterProvider;
pub struct RouterService {
pub(crate) regen_route: Rc<dyn Fn(ScopeId)>,
history: Rc<RefCell<BrowserHistory>>,
registerd_routes: RefCell<RouteSlot>,
pub(crate) pending_events: Rc<RefCell<Vec<RouteEvent>>>,
slots: Rc<RefCell<Vec<(ScopeId, String)>>>,
root_found: Rc<Cell<bool>>,
cur_root: RefCell<String>,
onchange_listeners: Rc<RefCell<HashSet<ScopeId>>>,
root_found: Rc<Cell<Option<ScopeId>>>,
cur_path_params: Rc<RefCell<HashMap<String, String>>>,
// history: Rc<dyn RouterProvider>,
history: Rc<RefCell<BrowserHistory>>,
listener: HistoryListener,
}
pub enum RouteEvent {
Change,
Pop,
Push,
}
enum RouteSlot {
Routes {
// the partial route
@@ -36,34 +47,44 @@ impl RouterService {
let location = history.location();
let path = location.path();
let onchange_listeners = Rc::new(RefCell::new(HashSet::new()));
let slots: Rc<RefCell<Vec<(ScopeId, String)>>> = Default::default();
let pending_events: Rc<RefCell<Vec<RouteEvent>>> = Default::default();
let root_found = Rc::new(Cell::new(None));
let _slots = slots.clone();
let listener = history.listen({
let pending_events = pending_events.clone();
let regen_route = regen_route.clone();
let root_found = root_found.clone();
let slots = slots.clone();
let onchange_listeners = onchange_listeners.clone();
move || {
root_found.set(None);
// checking if the route is valid is cheap, so we do it
for (slot, root) in slots.borrow_mut().iter().rev() {
regen_route(*slot);
}
let root_found = Rc::new(Cell::new(false));
let regen = regen_route.clone();
let _root_found = root_found.clone();
let listener = history.listen(move || {
_root_found.set(false);
// checking if the route is valid is cheap, so we do it
for (slot, _) in _slots.borrow_mut().iter().rev() {
log::trace!("regenerating slot {:?}", slot);
regen(*slot);
for listener in onchange_listeners.borrow_mut().iter() {
regen_route(*listener);
}
// also regenerate the root
regen_route(root_scope);
pending_events.borrow_mut().push(RouteEvent::Change)
}
});
Self {
registerd_routes: RefCell::new(RouteSlot::Routes {
partial: String::from("/"),
total: String::from("/"),
rest: Vec::new(),
}),
listener,
root_found,
history: Rc::new(RefCell::new(history)),
regen_route,
slots,
cur_root: RefCell::new(path.to_string()),
listener,
pending_events,
onchange_listeners,
cur_path_params: Rc::new(RefCell::new(HashMap::new())),
}
}
@@ -72,11 +93,15 @@ impl RouterService {
}
pub fn register_total_route(&self, route: String, scope: ScopeId, fallback: bool) {
self.slots.borrow_mut().push((scope, route));
let clean = clean_route(route);
self.slots.borrow_mut().push((scope, clean));
}
pub fn should_render(&self, scope: ScopeId) -> bool {
if self.root_found.get() {
if let Some(root_id) = self.root_found.get() {
if root_id == scope {
return true;
}
return false;
}
@@ -89,13 +114,14 @@ impl RouterService {
// fallback logic
match root {
Some((_id, route)) => {
if route == path {
self.root_found.set(true);
Some((id, route)) => {
if let Some(params) = route_matches_path(route, path) {
self.root_found.set(Some(*id));
*self.cur_path_params.borrow_mut() = params;
true
} else {
if route == "" {
self.root_found.set(true);
self.root_found.set(Some(*id));
true
} else {
false
@@ -105,6 +131,62 @@ impl RouterService {
None => false,
}
}
pub fn current_location(&self) -> Location {
self.history.borrow().location().clone()
}
pub fn current_path_params(&self) -> Ref<HashMap<String, String>> {
self.cur_path_params.borrow()
}
pub fn subscribe_onchange(&self, id: ScopeId) {
self.onchange_listeners.borrow_mut().insert(id);
}
pub fn unsubscribe_onchange(&self, id: ScopeId) {
self.onchange_listeners.borrow_mut().remove(&id);
}
}
fn clean_route(route: String) -> String {
if route.as_str() == "/" {
return route;
}
route.trim_end_matches('/').to_string()
}
fn clean_path(path: &str) -> &str {
if path == "/" {
return path;
}
path.trim_end_matches('/')
}
fn route_matches_path(route: &str, path: &str) -> Option<HashMap<String, String>> {
let route_pieces = route.split('/').collect::<Vec<_>>();
let path_pieces = clean_path(path).split('/').collect::<Vec<_>>();
if route_pieces.len() != path_pieces.len() {
return None;
}
let mut matches = HashMap::new();
for (i, r) in route_pieces.iter().enumerate() {
// If this is a parameter then it matches as long as there's
// _any_thing in that spot in the path.
if r.starts_with(':') {
let param = &r[1..];
matches.insert(param.to_string(), path_pieces[i].to_string());
continue;
}
if path_pieces[i] != *r {
return None;
}
}
Some(matches)
}
pub struct RouterCfg {
+63
View File
@@ -0,0 +1,63 @@
#![cfg(target_arch = "wasm32")]
use dioxus_core::prelude::*;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
use dioxus_router::*;
use gloo_utils::document;
use serde::{Deserialize, Serialize};
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn simple_test() {
fn main() {
console_error_panic_hook::set_once();
wasm_logger::init(wasm_logger::Config::new(log::Level::Debug));
dioxus_web::launch(APP);
}
static APP: Component = |cx| {
cx.render(rsx! {
Router {
onchange: move |route| log::info!("route changed to {}", route),
Route { to: "/", Home {} }
Route { to: "blog"
Route { to: "/", BlogList {} }
Route { to: ":id", BlogPost {} }
}
}
})
};
fn Home(cx: Scope) -> Element {
cx.render(rsx! {
div {
h1 { "Home" }
}
})
}
fn BlogList(cx: Scope) -> Element {
cx.render(rsx! {
div {
}
})
}
fn BlogPost(cx: Scope) -> Element {
let id = use_route(&cx).segment::<usize>("id")?;
cx.render(rsx! {
div {
}
})
}
main();
let element = gloo_utils::document();
}
+11
View File
@@ -0,0 +1,11 @@
{
"moz:firefoxOptions": {
"binary": "/usr/bin/firefox",
"prefs": {
"media.navigator.streams.fake": true,
"media.navigator.permission.disabled": true
},
"args": []
}
}
+3
View File
@@ -135,11 +135,14 @@ impl ToTokens for Component {
None => quote! { None },
};
let fn_name = self.name.segments.last().unwrap().ident.to_string();
tokens.append_all(quote! {
__cx.component(
#name,
#builder,
#key_token,
#fn_name
)
})
}
+30 -1
View File
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Bug Fixes
- <csr-id-255f58af63e002339b02bf91c5b85cc5ec917428/> ssr respects bool attrs
### Commit Statistics
<csr-read-only-do-not-edit/>
- 5 commits contributed to the release over the course of 21 calendar days.
- 1 commit where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- Merge pull request #111 from DioxusLabs/jk/props-attrs ([`0369fe7`](https://github.comgit//DioxusLabs/dioxus/commit/0369fe72fb247409da300a54ef11ba9155d0efb3))
- Fix various typos and grammar nits ([`9e4ec43`](https://github.comgit//DioxusLabs/dioxus/commit/9e4ec43b1e78d355c56a38e4c092170b2b01b20d))
- Merge pull request #108 from DioxusLabs/jk/fstring-component-fields ([`f4132d1`](https://github.comgit//DioxusLabs/dioxus/commit/f4132d1874f7495049fac23ba0a022ac137ad74f))
- ssr respects bool attrs ([`255f58a`](https://github.comgit//DioxusLabs/dioxus/commit/255f58af63e002339b02bf91c5b85cc5ec917428))
- Enable clippy ([`b6903bf`](https://github.comgit//DioxusLabs/dioxus/commit/b6903bf558bc7a3d0fe6794a137c44fca0957d11))
</details>
## v0.1.2 (2022-01-08)
### Documentation
@@ -47,7 +75,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 84 commits contributed to the release over the course of 357 calendar days.
- 85 commits contributed to the release over the course of 357 calendar days.
- 75 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
@@ -58,6 +86,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`b804c69`](https://github.comgit//DioxusLabs/dioxus/commit/b804c691d5ade4776390bb3d334cc9cd8efa4a49))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-ssr"
version = "0.1.2"
version = "0.1.3"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Dioxus render-to-string"
@@ -13,7 +13,7 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus-core = { path = "../core", version ="^0.1.7", features = ["serialize"] }
dioxus-core = { path = "../core", version = "^0.1.9", features = ["serialize"] }
[dev-dependencies]
+2 -2
View File
@@ -52,7 +52,7 @@ let content = dioxus::ssr::render_vdom(&dom);
```
## Configuring output
It's possible to configure the output of the generated HTML.
It's possible to configure the output of the generated HTML.
```rust, ignore
let content = dioxus::ssr::render_vdom(&dom, |config| config.pretty(true).prerender(true));
@@ -82,7 +82,7 @@ buf.write_fmt!(format_args!("{}", args));
## Usage in pre-rendering
## Usage in pre-rendering
This crate is particularly useful in pre-generating pages server-side and then selectively loading dioxus client-side to pick up the reactive elements.
+57 -3
View File
@@ -5,6 +5,60 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
### Documentation
- <csr-id-a239d2ba6ac7f1f3d09de16c022ce8ca52cf0f63/> fix web doc example and use &mut for builders everywhere
### New Features
- <csr-id-1406c9020bb3102635737dc2d13e5b3171499a18/> add panic hook by default
- <csr-id-95e93ed0bcf6c69990f4cf3c6448b2bf5da96c36/> remove dioxus id on non-event elements
- <csr-id-05331ddd8033f6997d4916179b62f4d62f832988/> wire up both desktop and web
- <csr-id-8f4aa84f1a4f2443b34d81ee42490564e168de53/> bool attr white list
### Bug Fixes
- <csr-id-ae676d9d816fcbf88d110157124443a5b3aef9eb/> webconfig should take &mut self
- <csr-id-92561612c727e73356d7d36e16af39aacf02a56d/> format code
- <csr-id-c1a5d4e11f5277e6ee644f670dc6fdd68f2202f1/> ssr + hydration event listeners
- <csr-id-21232285d9d84168d9003969ddd254fc22951e4b/> add exclusion list
### Commit Statistics
<csr-read-only-do-not-edit/>
- 17 commits contributed to the release over the course of 21 calendar days.
- 10 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
<csr-read-only-do-not-edit/>
<details><summary>view details</summary>
* **Uncategorized**
- webconfig should take &mut self ([`ae676d9`](https://github.comgit//DioxusLabs/dioxus/commit/ae676d9d816fcbf88d110157124443a5b3aef9eb))
- fix web doc example and use &mut for builders everywhere ([`a239d2b`](https://github.comgit//DioxusLabs/dioxus/commit/a239d2ba6ac7f1f3d09de16c022ce8ca52cf0f63))
- add panic hook by default ([`1406c90`](https://github.comgit//DioxusLabs/dioxus/commit/1406c9020bb3102635737dc2d13e5b3171499a18))
- Merge pull request #111 from DioxusLabs/jk/props-attrs ([`0369fe7`](https://github.comgit//DioxusLabs/dioxus/commit/0369fe72fb247409da300a54ef11ba9155d0efb3))
- Merge pull request #113 from DioxusLabs/jk/desktop-cursor-jump ([`20a2940`](https://github.comgit//DioxusLabs/dioxus/commit/20a29409b22510b001fdbee349724adb7b44d401))
- remove dioxus id on non-event elements ([`95e93ed`](https://github.comgit//DioxusLabs/dioxus/commit/95e93ed0bcf6c69990f4cf3c6448b2bf5da96c36))
- feat(events:focus): add missing `onfocusin` event ([`007d06d`](https://github.comgit//DioxusLabs/dioxus/commit/007d06d602f1adfaa51c87ec89b2afe90d8cdef9))
- feat(example:todomvc): add editing support ([`9849f68`](https://github.comgit//DioxusLabs/dioxus/commit/9849f68f257200fac511c048bfb1a076243b86d3))
- Merge pull request #101 from alexkirsz/ci ([`29bf424`](https://github.comgit//DioxusLabs/dioxus/commit/29bf424b0976b95ff645bb128d0e758cf0186614))
- Merge pull request #139 from DioxusLabs/jk/provide-context-any ([`70f2ef4`](https://github.comgit//DioxusLabs/dioxus/commit/70f2ef43db5b6737bd9bcbfc1aa21c834ce4b395))
- Merge branch 'master' into jk/unify ([`824defa`](https://github.comgit//DioxusLabs/dioxus/commit/824defa2dbcc16d66588b3976699d89b65a8a068))
- wire up both desktop and web ([`05331dd`](https://github.comgit//DioxusLabs/dioxus/commit/05331ddd8033f6997d4916179b62f4d62f832988))
- format code ([`9256161`](https://github.comgit//DioxusLabs/dioxus/commit/92561612c727e73356d7d36e16af39aacf02a56d))
- ssr + hydration event listeners ([`c1a5d4e`](https://github.comgit//DioxusLabs/dioxus/commit/c1a5d4e11f5277e6ee644f670dc6fdd68f2202f1))
- web now links against the js interprter code ([`10db6ad`](https://github.comgit//DioxusLabs/dioxus/commit/10db6ad65bd23dabf60d0afbe6ff82cda8220a8b))
- bool attr white list ([`8f4aa84`](https://github.comgit//DioxusLabs/dioxus/commit/8f4aa84f1a4f2443b34d81ee42490564e168de53))
- add exclusion list ([`2123228`](https://github.comgit//DioxusLabs/dioxus/commit/21232285d9d84168d9003969ddd254fc22951e4b))
</details>
## v0.0.4 (2022-01-08)
### Documentation
@@ -84,7 +138,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<csr-read-only-do-not-edit/>
- 203 commits contributed to the release over the course of 358 calendar days.
- 190 commits where understood as [conventional](https://www.conventionalcommits.org).
- 189 commits where understood as [conventional](https://www.conventionalcommits.org).
- 0 issues like '(#ID)' where seen in commit messages
### Commit Details
@@ -94,10 +148,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<details><summary>view details</summary>
* **Uncategorized**
- Release dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`b804c69`](https://github.comgit//DioxusLabs/dioxus/commit/b804c691d5ade4776390bb3d334cc9cd8efa4a49))
- handle bool attrs properly ([`8d685f4`](https://github.comgit//DioxusLabs/dioxus/commit/8d685f40b7e0ef6521c60310d8687291e9b9c48a))
- Release dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`a36dab7`](https://github.comgit//DioxusLabs/dioxus/commit/a36dab7f45920acd8535a69b4aa3695f3bb92111))
- Release dioxus-core v0.1.7, dioxus-core-macro v0.1.6, dioxus-html v0.1.4, dioxus-desktop v0.1.5, dioxus-hooks v0.1.6, dioxus-mobile v0.0.3, dioxus-router v0.1.0, dioxus-ssr v0.1.2, dioxus-web v0.0.4, dioxus v0.1.7 ([`40d1f85`](https://github.comgit//DioxusLabs/dioxus/commit/40d1f85d0c3e2c9fd23c08840cca9f459d4e4307))
- add exclusion list ([`2123228`](https://github.comgit//DioxusLabs/dioxus/commit/21232285d9d84168d9003969ddd254fc22951e4b))
- handle bool attrs properly ([`8d685f4`](https://github.comgit//DioxusLabs/dioxus/commit/8d685f40b7e0ef6521c60310d8687291e9b9c48a))
- Merge pull request #74 from mrxiaozhuox/master ([`47056fd`](https://github.comgit//DioxusLabs/dioxus/commit/47056fda4577bcbdaa2a6f63d82eec876e5a5aee))
- Merge pull request #80 from DioxusLabs/jk/router2dotoh ([`cdc2d8e`](https://github.comgit//DioxusLabs/dioxus/commit/cdc2d8ec6d123245c2ea5f6d10af02b6a6833994))
- memoize dom in the prescence of identical components ([`cb2782b`](https://github.comgit//DioxusLabs/dioxus/commit/cb2782b4bb34cdaadfff590bfee930ae3ac6536c))
+20 -28
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-web"
version = "0.0.4"
version = "0.0.5"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Dioxus VirtualDOM renderer for the web browser using websys"
@@ -11,26 +11,28 @@ documentation = "https://dioxuslabs.com"
keywords = ["dom", "ui", "gui", "react", "wasm"]
[dependencies]
dioxus-core = { path = "../core", version ="^0.1.7"}
dioxus-html = { path = "../html", version ="^0.1.4"}
js-sys = "0.3"
wasm-bindgen = { version = "0.2.78", features = ["enable-interning"] }
dioxus-core = { path = "../core", version = "^0.1.9" }
dioxus-html = { path = "../html", version = "^0.1.6" }
js-sys = "0.3.56"
wasm-bindgen = { version = "0.2.79", features = ["enable-interning"] }
lazy_static = "1.4.0"
wasm-bindgen-futures = "0.4.20"
wasm-bindgen-futures = "0.4.29"
log = { version = "0.4.14", features = ["release_max_level_off"] }
fxhash = "0.2.1"
wasm-logger = "0.2.0"
console_error_panic_hook = "0.1.6"
wasm-bindgen-test = "0.3.21"
once_cell = "1.8"
console_error_panic_hook = { version = "0.1.7", optional = true }
wasm-bindgen-test = "0.3.29"
once_cell = "1.9.0"
async-channel = "1.6.1"
anyhow = "1.0"
gloo-timers = { version = "0.2.1", features = ["futures"] }
futures-util = "0.3.15"
anyhow = "1.0.53"
gloo-timers = { version = "0.2.3", features = ["futures"] }
futures-util = "0.3.19"
smallstr = "0.2.0"
dioxus-interpreter-js = { path = "../interpreter", version = "^0.0.0", features = ["web"] }
serde-wasm-bindgen = "0.4.2"
[dependencies.web-sys]
version = "0.3.51"
version = "0.3.56"
features = [
"Comment",
"Attr",
@@ -41,6 +43,7 @@ features = [
"HtmlInputElement",
"HtmlSelectElement",
"HtmlTextAreaElement",
"HtmlFormElement",
"EventTarget",
"HtmlCollection",
"Node",
@@ -69,22 +72,11 @@ features = [
"IdleDeadline",
]
# [lib]
# crate-type = ["cdylib", "rlib"]
[features]
default = ["panic_hook"]
panic_hook = ["console_error_panic_hook"]
[dev-dependencies]
dioxus-core-macro = { path = "../core-macro" }
wasm-bindgen-test = "0.3.28"
wasm-bindgen-test = "0.3.29"
dioxus-ssr = { path = "../ssr" }
# im-rc = "15.0.0"
# separator = "0.4.1"
# uuid = { version = "0.8.2", features = ["v4", "wasm-bindgen"] }
# serde = { version = "1.0.126", features = ["derive"] }
# reqwest = { version = "0.11", features = ["json"] }
# dioxus-hooks = { path = "../hooks" }
# rand = { version = "0.8.4", features = ["small_rng"] }
# [dev-dependencies.getrandom]
# version = "0.2"
# features = ["js"]
-2
View File
@@ -1,8 +1,6 @@
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
use wasm_bindgen_test::wasm_bindgen_test;
use web_sys::window;
fn app(cx: Scope) -> Element {
+1 -1
View File
@@ -1,4 +1,4 @@
pub static BUILTIN_INTERNED_STRINGS: &[&'static str] = &[
pub static BUILTIN_INTERNED_STRINGS: &[&str] = &[
// Important tags to dioxus
"dioxus-id",
"dioxus",
+5 -6
View File
@@ -3,10 +3,9 @@
/// This struct helps configure the specifics of hydration and render destination for WebSys.
///
/// # Example
///
/// ```rust, ignore
/// fn main() {
/// dioxus::web::launch(App, |cfg| cfg.hydrate(true).root_name("myroot"))
/// }
/// dioxus::web::launch(App, |cfg| cfg.hydrate(true).root_name("myroot"))
/// ```
pub struct WebConfig {
pub(crate) hydrate: bool,
@@ -31,7 +30,7 @@ impl WebConfig {
/// work and suspended nodes.
///
/// Dioxus will load up all the elements with the `dio_el` data attribute into memory when the page is loaded.
pub fn hydrate(mut self, f: bool) -> Self {
pub fn hydrate(&mut self, f: bool) -> &mut Self {
self.hydrate = f;
self
}
@@ -39,7 +38,7 @@ impl WebConfig {
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akint to calling React.render() on the element with the specified name.
pub fn rootname(mut self, name: impl Into<String>) -> Self {
pub fn rootname(&mut self, name: impl Into<String>) -> &mut Self {
self.rootname = name.into();
self
}
@@ -47,7 +46,7 @@ impl WebConfig {
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akint to calling React.render() on the element with the specified name.
pub fn with_string_cache(mut self, cache: Vec<String>) -> Self {
pub fn with_string_cache(&mut self, cache: Vec<String>) -> &mut Self {
self.cached_strings = cache;
self
}
+153 -483
View File
@@ -7,56 +7,99 @@
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?>
use dioxus_core::{DomEdit, ElementId, SchedulerMsg, ScopeId, UserEvent};
use fxhash::FxHashMap;
use std::{any::Any, fmt::Debug, rc::Rc, sync::Arc};
use dioxus_core::{DomEdit, ElementId, SchedulerMsg, UserEvent};
use dioxus_interpreter_js::Interpreter;
use js_sys::Function;
use std::{any::Any, rc::Rc, sync::Arc};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{
CssStyleDeclaration, Document, Element, Event, HtmlElement, HtmlInputElement,
HtmlOptionElement, HtmlTextAreaElement, Node,
};
use web_sys::{Document, Element, Event, HtmlElement};
use crate::{nodeslab::NodeSlab, WebConfig};
use crate::WebConfig;
pub struct WebsysDom {
stack: Stack,
/// A map from ElementID (index) to Node
pub(crate) nodes: NodeSlab,
document: Document,
pub interpreter: Interpreter,
pub(crate) root: Element,
sender_callback: Rc<dyn Fn(SchedulerMsg)>,
// map of listener types to number of those listeners
// This is roughly a delegater
// TODO: check how infero delegates its events - some are more performant
listeners: FxHashMap<&'static str, ListenerEntry>,
pub handler: Closure<dyn FnMut(&Event)>,
}
type ListenerEntry = (usize, Closure<dyn FnMut(&Event)>);
impl WebsysDom {
pub fn new(cfg: WebConfig, sender_callback: Rc<dyn Fn(SchedulerMsg)>) -> Self {
// eventually, we just want to let the interpreter do all the work of decoding events into our event type
let callback: Box<dyn FnMut(&Event)> = Box::new(move |event: &web_sys::Event| {
let mut target = event
.target()
.expect("missing target")
.dyn_into::<Element>()
.expect("not a valid element");
let typ = event.type_();
let decoded: anyhow::Result<UserEvent> = loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => {
break Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone(), target.clone()),
element: Some(ElementId(id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
});
}
Some(Err(e)) => {
break Err(e.into());
}
None => {
// walk the tree upwards until we actually find an event target
if let Some(parent) = target.parent_element() {
target = parent;
} else {
break Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(
event.clone(),
target.clone(),
),
element: None,
scope_id: None,
priority: dioxus_core::EventPriority::Low,
});
}
}
}
};
if let Ok(synthetic_event) = decoded {
// Try to prevent default if the attribute is set
if let Some(node) = target.dyn_ref::<HtmlElement>() {
if let Some(name) = node.get_attribute("dioxus-prevent-default") {
if name == synthetic_event.name
|| name.trim_start_matches("on") == synthetic_event.name
{
log::trace!("Preventing default");
event.prevent_default();
}
}
}
sender_callback.as_ref()(SchedulerMsg::Event(synthetic_event))
}
});
let document = load_document();
let nodes = NodeSlab::new(2000);
let listeners = FxHashMap::default();
let mut stack = Stack::with_capacity(10);
let root = load_document().get_element_by_id(&cfg.rootname).unwrap();
let root_node = root.clone().dyn_into::<Node>().unwrap();
stack.push(root_node);
let root = match document.get_element_by_id(&cfg.rootname) {
Some(root) => root,
// a match here in order to avoid some error during runtime browser test
None => {
let body = document.create_element("body").ok().unwrap();
body
}
};
Self {
stack,
nodes,
listeners,
document,
sender_callback,
interpreter: Interpreter::new(root.clone()),
handler: Closure::wrap(callback),
root,
}
}
@@ -64,444 +107,68 @@ impl WebsysDom {
pub fn apply_edits(&mut self, mut edits: Vec<DomEdit>) {
for edit in edits.drain(..) {
match edit {
DomEdit::PushRoot { root } => self.push(root),
DomEdit::AppendChildren { many } => self.append_children(many),
DomEdit::ReplaceWith { m, root } => self.replace_with(m, root),
DomEdit::Remove { root } => self.remove(root),
DomEdit::CreateTextNode { text, root: id } => self.create_text_node(text, id),
DomEdit::CreateElement { tag, root: id } => self.create_element(tag, None, id),
DomEdit::CreateElementNs { tag, root: id, ns } => {
self.create_element(tag, Some(ns), id)
DomEdit::PushRoot { root } => self.interpreter.PushRoot(root),
DomEdit::AppendChildren { many } => self.interpreter.AppendChildren(many),
DomEdit::ReplaceWith { root, m } => self.interpreter.ReplaceWith(root, m),
DomEdit::InsertAfter { root, n } => self.interpreter.InsertAfter(root, n),
DomEdit::InsertBefore { root, n } => self.interpreter.InsertBefore(root, n),
DomEdit::Remove { root } => self.interpreter.Remove(root),
DomEdit::CreateElement { tag, root } => self.interpreter.CreateElement(tag, root),
DomEdit::CreateElementNs { tag, root, ns } => {
self.interpreter.CreateElementNs(tag, root, ns)
}
DomEdit::CreatePlaceholder { root: id } => self.create_placeholder(id),
DomEdit::CreatePlaceholder { root } => self.interpreter.CreatePlaceholder(root),
DomEdit::NewEventListener {
event_name,
scope,
root: mounted_node_id,
} => self.new_event_listener(event_name, scope, mounted_node_id),
DomEdit::RemoveEventListener { event, root } => {
self.remove_event_listener(event, root)
event_name, root, ..
} => {
let handler: &Function = self.handler.as_ref().unchecked_ref();
self.interpreter.NewEventListener(event_name, root, handler);
}
DomEdit::SetText { text, root } => self.set_text(text, root),
DomEdit::RemoveEventListener { root, event } => {
self.interpreter.RemoveEventListener(root, event)
}
DomEdit::RemoveAttribute { root, name } => {
self.interpreter.RemoveAttribute(root, name)
}
DomEdit::CreateTextNode { text, root } => {
let text = serde_wasm_bindgen::to_value(text).unwrap();
self.interpreter.CreateTextNode(text, root)
}
DomEdit::SetText { root, text } => {
let text = serde_wasm_bindgen::to_value(text).unwrap();
self.interpreter.SetText(root, text)
}
DomEdit::SetAttribute {
root,
field,
value,
ns,
root,
} => self.set_attribute(field, value, ns, root),
DomEdit::RemoveAttribute { name, root } => self.remove_attribute(name, root),
DomEdit::InsertAfter { n, root } => self.insert_after(n, root),
DomEdit::InsertBefore { n, root } => self.insert_before(n, root),
}
}
}
fn push(&mut self, root: u64) {
let key = root as usize;
let domnode = &self.nodes[key];
let real_node: Node = match domnode {
Some(n) => n.clone(),
None => todo!(),
};
self.stack.push(real_node);
}
fn append_children(&mut self, many: u32) {
let root: Node = self
.stack
.list
.get(self.stack.list.len() - (1 + many as usize))
.unwrap()
.clone();
// We need to make sure to add comments between text nodes
// We ensure that the text siblings are patched by preventing the browser from merging
// neighboring text nodes. Originally inspired by some of React's work from 2016.
// -> https://reactjs.org/blog/2016/04/07/react-v15.html#major-changes
// -> https://github.com/facebook/react/pull/5753
/*
todo: we need to track this for replacing/insert after/etc
*/
let mut last_node_was_text = false;
for child in self
.stack
.list
.drain((self.stack.list.len() - many as usize)..)
{
if child.dyn_ref::<web_sys::Text>().is_some() {
if last_node_was_text {
let comment_node = self
.document
.create_comment("dioxus")
.dyn_into::<Node>()
.unwrap();
root.append_child(&comment_node).unwrap();
}
last_node_was_text = true;
} else {
last_node_was_text = false;
}
root.append_child(&child).unwrap();
}
}
fn replace_with(&mut self, m: u32, root: u64) {
let old = self.nodes[root as usize].as_ref().unwrap();
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - m as usize)..)
.collect();
if let Some(el) = old.dyn_ref::<Element>() {
el.replace_with_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::CharacterData>() {
el.replace_with_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::DocumentType>() {
el.replace_with_with_node(&arr).unwrap();
}
}
fn remove(&mut self, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if let Some(element) = node.dyn_ref::<Element>() {
element.remove();
} else {
if let Some(parent) = node.parent_node() {
parent.remove_child(&node).unwrap();
}
}
}
fn create_placeholder(&mut self, id: u64) {
self.create_element("pre", None, id);
self.set_attribute("hidden", "", None, id);
}
fn create_text_node(&mut self, text: &str, id: u64) {
let textnode = self
.document
.create_text_node(text)
.dyn_into::<Node>()
.unwrap();
self.stack.push(textnode.clone());
self.nodes[(id as usize)] = Some(textnode);
}
fn create_element(&mut self, tag: &str, ns: Option<&'static str>, id: u64) {
let tag = wasm_bindgen::intern(tag);
let el = match ns {
Some(ns) => self
.document
.create_element_ns(Some(ns), tag)
.unwrap()
.dyn_into::<Node>()
.unwrap(),
None => self
.document
.create_element(tag)
.unwrap()
.dyn_into::<Node>()
.unwrap(),
};
use smallstr::SmallString;
use std::fmt::Write;
let mut s: SmallString<[u8; 8]> = smallstr::SmallString::new();
write!(s, "{}", id).unwrap();
let el2 = el.dyn_ref::<Element>().unwrap();
el2.set_attribute("dioxus-id", s.as_str()).unwrap();
self.stack.push(el.clone());
self.nodes[(id as usize)] = Some(el);
}
fn new_event_listener(&mut self, event: &'static str, _scope: ScopeId, _real_id: u64) {
let event = wasm_bindgen::intern(event);
// attach the correct attributes to the element
// these will be used by accessing the event's target
// This ensures we only ever have one handler attached to the root, but decide
// dynamically when we want to call a listener.
let el = self.stack.top();
let el = el.dyn_ref::<Element>().unwrap();
el.set_attribute("dioxus-event", event).unwrap();
// Register the callback to decode
if let Some(entry) = self.listeners.get_mut(event) {
entry.0 += 1;
} else {
let trigger = self.sender_callback.clone();
let c: Box<dyn FnMut(&Event)> = Box::new(move |event: &web_sys::Event| {
// "Result" cannot be received from JS
// Instead, we just build and immediately execute a closure that returns result
match decode_trigger(event) {
Ok(synthetic_event) => {
let target = event.target().unwrap();
if let Some(node) = target.dyn_ref::<HtmlElement>() {
if let Some(name) = node.get_attribute("dioxus-prevent-default") {
if name == synthetic_event.name
|| name.trim_start_matches("on") == synthetic_event.name
{
log::trace!("Preventing default");
event.prevent_default();
}
}
}
trigger.as_ref()(SchedulerMsg::Event(synthetic_event))
}
Err(e) => log::error!("Error decoding Dioxus event attribute. {:#?}", e),
};
});
let handler = Closure::wrap(c);
self.root
.add_event_listener_with_callback(event, (&handler).as_ref().unchecked_ref())
.unwrap();
// Increment the listeners
self.listeners.insert(event.into(), (1, handler));
}
}
fn remove_event_listener(&mut self, _event: &str, _root: u64) {
todo!()
}
fn set_text(&mut self, text: &str, root: u64) {
let el = self.nodes[root as usize].as_ref().unwrap();
el.set_text_content(Some(text))
}
fn set_attribute(&mut self, name: &str, value: &str, ns: Option<&str>, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if ns == Some("style") {
if let Some(el) = node.dyn_ref::<Element>() {
let el = el.dyn_ref::<HtmlElement>().unwrap();
let style_dc: CssStyleDeclaration = el.style();
style_dc.set_property(name, value).unwrap();
}
} else {
let fallback = || {
let el = node.dyn_ref::<Element>().unwrap();
el.set_attribute(name, value).unwrap()
};
match name {
"dangerous_inner_html" => {
if let Some(el) = node.dyn_ref::<Element>() {
el.set_inner_html(value);
}
}
"value" => {
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
/*
if the attribute being set is the same as the value of the input, then don't bother setting it.
This is used in controlled components to keep the cursor in the right spot.
this logic should be moved into the virtualdom since we have the notion of "volatile"
*/
if input.value() != value {
input.set_value(value);
}
} else if let Some(node) = node.dyn_ref::<HtmlTextAreaElement>() {
if name == "value" {
node.set_value(value);
}
} else {
fallback();
}
}
"checked" => {
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
match value {
"true" => input.set_checked(true),
"false" => input.set_checked(false),
_ => fallback(),
}
} else {
fallback();
}
}
"selected" => {
if let Some(node) = node.dyn_ref::<HtmlOptionElement>() {
node.set_selected(true);
} else {
fallback();
}
}
_ => {
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if value == "false" {
if let Some(el) = node.dyn_ref::<Element>() {
match name {
"allowfullscreen"
| "allowpaymentrequest"
| "async"
| "autofocus"
| "autoplay"
| "checked"
| "controls"
| "default"
| "defer"
| "disabled"
| "formnovalidate"
| "hidden"
| "ismap"
| "itemscope"
| "loop"
| "multiple"
| "muted"
| "nomodule"
| "novalidate"
| "open"
| "playsinline"
| "readonly"
| "required"
| "reversed"
| "selected"
| "truespeed" => {
let _ = el.remove_attribute(name);
}
_ => {
let _ = el.set_attribute(name, value);
}
};
}
} else {
fallback();
}
} => {
let value = serde_wasm_bindgen::to_value(value).unwrap();
self.interpreter.SetAttribute(root, field, value, ns)
}
}
}
}
fn remove_attribute(&mut self, name: &str, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if let Some(node) = node.dyn_ref::<web_sys::Element>() {
node.remove_attribute(name).unwrap();
}
if let Some(node) = node.dyn_ref::<HtmlInputElement>() {
// Some attributes are "volatile" and don't work through `removeAttribute`.
if name == "value" {
node.set_value("");
}
if name == "checked" {
node.set_checked(false);
}
}
if let Some(node) = node.dyn_ref::<HtmlOptionElement>() {
if name == "selected" {
node.set_selected(true);
}
}
}
fn insert_after(&mut self, n: u32, root: u64) {
let old = self.nodes[root as usize].as_ref().unwrap();
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - n as usize)..)
.collect();
if let Some(el) = old.dyn_ref::<Element>() {
el.after_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::CharacterData>() {
el.after_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::DocumentType>() {
el.after_with_node(&arr).unwrap();
}
}
fn insert_before(&mut self, n: u32, root: u64) {
let anchor = self.nodes[root as usize].as_ref().unwrap();
if n == 1 {
let before = self.stack.pop();
anchor
.parent_node()
.unwrap()
.insert_before(&before, Some(&anchor))
.unwrap();
} else {
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - n as usize)..)
.collect();
if let Some(el) = anchor.dyn_ref::<Element>() {
el.before_with_node(&arr).unwrap();
} else if let Some(el) = anchor.dyn_ref::<web_sys::CharacterData>() {
el.before_with_node(&arr).unwrap();
} else if let Some(el) = anchor.dyn_ref::<web_sys::DocumentType>() {
el.before_with_node(&arr).unwrap();
}
}
}
}
#[derive(Debug, Default)]
struct Stack {
list: Vec<Node>,
}
impl Stack {
#[inline]
fn with_capacity(cap: usize) -> Self {
Stack {
list: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, node: Node) {
self.list.push(node);
}
#[inline]
fn pop(&mut self) -> Node {
self.list.pop().unwrap()
}
fn top(&self) -> &Node {
match self.list.last() {
Some(a) => a,
None => panic!("Called 'top' of an empty stack, make sure to push the root first"),
}
}
}
pub struct DioxusWebsysEvent(web_sys::Event);
// safety: currently the web is not multithreaded and our VirtualDom exists on the same thread
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for DioxusWebsysEvent {}
unsafe impl Sync for DioxusWebsysEvent {}
// todo: some of these events are being casted to the wrong event type.
// We need tests that simulate clicks/etc and make sure every event type works.
fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send + Sync> {
fn virtual_event_from_websys_event(
event: web_sys::Event,
target: Element,
) -> Arc<dyn Any + Send + Sync> {
use dioxus_html::on::*;
use dioxus_html::KeyCode;
@@ -534,9 +201,6 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send
// todo: these handlers might get really slow if the input box gets large and allocation pressure is heavy
// don't have a good solution with the serialized event problem
"change" | "input" | "invalid" | "reset" | "submit" => {
let evt: &web_sys::Event = event.dyn_ref().unwrap();
let target: web_sys::EventTarget = evt.target().unwrap();
let value: String = (&target)
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
@@ -572,7 +236,38 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send
})
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
Arc::new(FormData { value })
let mut values = std::collections::HashMap::new();
// try to fill in form values
if let Some(form) = target.dyn_ref::<web_sys::HtmlFormElement>() {
let elements = form.elements();
for x in 0..elements.length() {
let element = elements.item(x).unwrap();
if let Some(name) = element.get_attribute("name") {
let value: String = (&element)
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => "true".to_string(),
false => "false".to_string(),
}
},
_ => input.value()
}
})
.or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlTextAreaElement| input.value()))
.or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlSelectElement| input.value()))
.or_else(|| target.dyn_ref::<web_sys::HtmlElement>().unwrap().text_content())
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
values.insert(name, value);
}
}
}
Arc::new(FormData { value, values })
}
"click" | "contextmenu" | "doubleclick" | "drag" | "dragend" | "dragenter" | "dragexit"
| "dragleave" | "dragover" | "dragstart" | "drop" | "mousedown" | "mouseenter"
@@ -632,6 +327,7 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send
shift_key: evt.shift_key(),
})
}
"scroll" => Arc::new(()),
"wheel" => {
let evt: &web_sys::WheelEvent = event.dyn_ref().unwrap();
@@ -663,37 +359,11 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send
| "playing" | "progress" | "ratechange" | "seeked" | "seeking" | "stalled" | "suspend"
| "timeupdate" | "volumechange" | "waiting" => Arc::new(MediaData {}),
"toggle" => Arc::new(ToggleData {}),
_ => Arc::new(()),
}
}
/// This function decodes a websys event and produces an EventTrigger
/// With the websys implementation, we attach a unique key to the nodes
fn decode_trigger(event: &web_sys::Event) -> anyhow::Result<UserEvent> {
use anyhow::Context;
let target = event
.target()
.expect("missing target")
.dyn_into::<Element>()
.expect("not a valid element");
let typ = event.type_();
let element_id = target
.get_attribute("dioxus-id")
.context("Could not find element id on event target")?
.parse()?;
Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone()),
element: Some(ElementId(element_id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
})
}
pub(crate) fn load_document() -> Document {
web_sys::window()
.expect("should have access to the Window")
+36 -6
View File
@@ -64,7 +64,6 @@ use futures_util::FutureExt;
mod cache;
mod cfg;
mod dom;
mod nodeslab;
mod rehydrate;
mod ric_raf;
@@ -92,6 +91,29 @@ pub fn launch(root_component: Component) {
launch_with_props(root_component, (), |c| c);
}
/// Launch your app and run the event loop, with configuration.
///
/// This function will start your web app on the main web thread.
///
/// You can configure the WebView window with a configuration closure
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn main() {
/// dioxus_web::launch_with_props(App, |config| config.pre_render(true));
/// }
///
/// fn app(cx: Scope) -> Element {
/// cx.render(rsx!{
/// h1 {"hello world!"}
/// })
/// }
/// ```
pub fn launch_cfg(root: Component, config_builder: impl FnOnce(&mut WebConfig) -> &mut WebConfig) {
launch_with_props(root, (), config_builder)
}
/// Launches the VirtualDOM from the specified component function and props.
///
/// This method will block the thread with `spawn_local`
@@ -100,7 +122,11 @@ pub fn launch(root_component: Component) {
///
/// ```rust, ignore
/// fn main() {
/// dioxus_web::launch_with_props(App, RootProps { name: String::from("joe") });
/// dioxus_web::launch_with_props(
/// App,
/// RootProps { name: String::from("joe") },
/// |config| config
/// );
/// }
///
/// #[derive(ParitalEq, Props)]
@@ -112,15 +138,19 @@ pub fn launch(root_component: Component) {
/// rsx!(cx, div {"hello {cx.props.name}"})
/// }
/// ```
pub fn launch_with_props<T, F>(
pub fn launch_with_props<T>(
root_component: Component<T>,
root_properties: T,
configuration_builder: F,
configuration_builder: impl FnOnce(&mut WebConfig) -> &mut WebConfig,
) where
T: Send + 'static,
F: FnOnce(WebConfig) -> WebConfig,
{
let config = configuration_builder(WebConfig::default());
if cfg!(feature = "panic_hook") {
console_error_panic_hook::set_once();
}
let mut config = WebConfig::default();
configuration_builder(&mut config);
wasm_bindgen_futures::spawn_local(run_with_props(root_component, root_properties, config));
}
-34
View File
@@ -1,34 +0,0 @@
//! This module provides a mirror of the VirtualDOM Element Slab using a Vector.
use std::ops::{Index, IndexMut};
use web_sys::Node;
pub(crate) struct NodeSlab {
nodes: Vec<Option<Node>>,
}
impl NodeSlab {
pub fn new(capacity: usize) -> NodeSlab {
let nodes = Vec::with_capacity(capacity);
NodeSlab { nodes }
}
}
impl Index<usize> for NodeSlab {
type Output = Option<Node>;
fn index(&self, index: usize) -> &Self::Output {
&self.nodes[index]
}
}
impl IndexMut<usize> for NodeSlab {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
if index >= self.nodes.capacity() * 3 {
panic!("Trying to mutate an element way too far out of bounds");
}
if index + 1 > self.nodes.len() {
self.nodes.resize_with(index + 1, || None);
}
&mut self.nodes[index]
}
}
+857
View File
@@ -0,0 +1,857 @@
//! Implementation of a renderer for Dioxus on the web.
//!
//! Oustanding todos:
//! - Removing event listeners (delegation)
//! - Passive event listeners
//! - no-op event listener patch for safari
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?>
use dioxus_core::{DomEdit, ElementId, SchedulerMsg, ScopeId, UserEvent};
use fxhash::FxHashMap;
use std::{any::Any, fmt::Debug, rc::Rc, sync::Arc};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{
CssStyleDeclaration, Document, Element, Event, HtmlElement, HtmlInputElement,
HtmlOptionElement, HtmlTextAreaElement, Node,
};
use crate::{nodeslab::NodeSlab, WebConfig};
pub struct WebsysDom {
stack: Stack,
/// A map from ElementID (index) to Node
pub(crate) nodes: NodeSlab,
document: Document,
pub(crate) root: Element,
sender_callback: Rc<dyn Fn(SchedulerMsg)>,
// map of listener types to number of those listeners
// This is roughly a delegater
// TODO: check how infero delegates its events - some are more performant
listeners: FxHashMap<&'static str, ListenerEntry>,
}
type ListenerEntry = (usize, Closure<dyn FnMut(&Event)>);
impl WebsysDom {
pub fn new(cfg: WebConfig, sender_callback: Rc<dyn Fn(SchedulerMsg)>) -> Self {
let document = load_document();
let nodes = NodeSlab::new(2000);
let listeners = FxHashMap::default();
let mut stack = Stack::with_capacity(10);
let root = load_document().get_element_by_id(&cfg.rootname).unwrap();
let root_node = root.clone().dyn_into::<Node>().unwrap();
stack.push(root_node);
Self {
stack,
nodes,
listeners,
document,
sender_callback,
root,
}
}
pub fn apply_edits(&mut self, mut edits: Vec<DomEdit>) {
for edit in edits.drain(..) {
match edit {
DomEdit::PushRoot { root } => self.push(root),
DomEdit::AppendChildren { many } => self.append_children(many),
DomEdit::ReplaceWith { m, root } => self.replace_with(m, root),
DomEdit::Remove { root } => self.remove(root),
DomEdit::CreateTextNode { text, root: id } => self.create_text_node(text, id),
DomEdit::CreateElement { tag, root: id } => self.create_element(tag, None, id),
DomEdit::CreateElementNs { tag, root: id, ns } => {
self.create_element(tag, Some(ns), id)
}
DomEdit::CreatePlaceholder { root: id } => self.create_placeholder(id),
DomEdit::NewEventListener {
event_name,
scope,
root: mounted_node_id,
} => self.new_event_listener(event_name, scope, mounted_node_id),
DomEdit::RemoveEventListener { event, root } => {
self.remove_event_listener(event, root)
}
DomEdit::SetText { text, root } => self.set_text(text, root),
DomEdit::SetAttribute {
field,
value,
ns,
root,
} => self.set_attribute(field, value, ns, root),
DomEdit::RemoveAttribute { name, root } => self.remove_attribute(name, root),
DomEdit::InsertAfter { n, root } => self.insert_after(n, root),
DomEdit::InsertBefore { n, root } => self.insert_before(n, root),
}
}
}
fn push(&mut self, root: u64) {
let key = root as usize;
let domnode = &self.nodes[key];
let real_node: Node = match domnode {
Some(n) => n.clone(),
None => todo!(),
};
self.stack.push(real_node);
}
fn append_children(&mut self, many: u32) {
let root: Node = self
.stack
.list
.get(self.stack.list.len() - (1 + many as usize))
.unwrap()
.clone();
// We need to make sure to add comments between text nodes
// We ensure that the text siblings are patched by preventing the browser from merging
// neighboring text nodes. Originally inspired by some of React's work from 2016.
// -> https://reactjs.org/blog/2016/04/07/react-v15.html#major-changes
// -> https://github.com/facebook/react/pull/5753
/*
todo: we need to track this for replacing/insert after/etc
*/
let mut last_node_was_text = false;
for child in self
.stack
.list
.drain((self.stack.list.len() - many as usize)..)
{
if child.dyn_ref::<web_sys::Text>().is_some() {
if last_node_was_text {
let comment_node = self
.document
.create_comment("dioxus")
.dyn_into::<Node>()
.unwrap();
root.append_child(&comment_node).unwrap();
}
last_node_was_text = true;
} else {
last_node_was_text = false;
}
root.append_child(&child).unwrap();
}
}
fn replace_with(&mut self, m: u32, root: u64) {
let old = self.nodes[root as usize].as_ref().unwrap();
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - m as usize)..)
.collect();
if let Some(el) = old.dyn_ref::<Element>() {
el.replace_with_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::CharacterData>() {
el.replace_with_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::DocumentType>() {
el.replace_with_with_node(&arr).unwrap();
}
}
fn remove(&mut self, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if let Some(element) = node.dyn_ref::<Element>() {
element.remove();
} else {
if let Some(parent) = node.parent_node() {
parent.remove_child(&node).unwrap();
}
}
}
fn create_placeholder(&mut self, id: u64) {
self.create_element("pre", None, id);
self.set_attribute("hidden", "", None, id);
}
fn create_text_node(&mut self, text: &str, id: u64) {
let textnode = self
.document
.create_text_node(text)
.dyn_into::<Node>()
.unwrap();
self.stack.push(textnode.clone());
self.nodes[(id as usize)] = Some(textnode);
}
fn create_element(&mut self, tag: &str, ns: Option<&'static str>, id: u64) {
let tag = wasm_bindgen::intern(tag);
let el = match ns {
Some(ns) => self
.document
.create_element_ns(Some(ns), tag)
.unwrap()
.dyn_into::<Node>()
.unwrap(),
None => self
.document
.create_element(tag)
.unwrap()
.dyn_into::<Node>()
.unwrap(),
};
use smallstr::SmallString;
use std::fmt::Write;
let mut s: SmallString<[u8; 8]> = smallstr::SmallString::new();
write!(s, "{}", id).unwrap();
let el2 = el.dyn_ref::<Element>().unwrap();
el2.set_attribute("dioxus-id", s.as_str()).unwrap();
self.stack.push(el.clone());
self.nodes[(id as usize)] = Some(el);
}
fn new_event_listener(&mut self, event: &'static str, _scope: ScopeId, _real_id: u64) {
let event = wasm_bindgen::intern(event);
// attach the correct attributes to the element
// these will be used by accessing the event's target
// This ensures we only ever have one handler attached to the root, but decide
// dynamically when we want to call a listener.
let el = self.stack.top();
let el = el.dyn_ref::<Element>().unwrap();
el.set_attribute("dioxus-event", event).unwrap();
// Register the callback to decode
if let Some(entry) = self.listeners.get_mut(event) {
entry.0 += 1;
} else {
let trigger = self.sender_callback.clone();
let c: Box<dyn FnMut(&Event)> = Box::new(move |event: &web_sys::Event| {
// "Result" cannot be received from JS
// Instead, we just build and immediately execute a closure that returns result
match decode_trigger(event) {
Ok(synthetic_event) => {
let target = event.target().unwrap();
if let Some(node) = target.dyn_ref::<HtmlElement>() {
if let Some(name) = node.get_attribute("dioxus-prevent-default") {
if name == synthetic_event.name
|| name.trim_start_matches("on") == synthetic_event.name
{
log::trace!("Preventing default");
event.prevent_default();
}
}
}
trigger.as_ref()(SchedulerMsg::Event(synthetic_event))
}
Err(e) => log::error!("Error decoding Dioxus event attribute. {:#?}", e),
};
});
let handler = Closure::wrap(c);
self.root
.add_event_listener_with_callback(event, (&handler).as_ref().unchecked_ref())
.unwrap();
// Increment the listeners
self.listeners.insert(event.into(), (1, handler));
}
}
fn remove_event_listener(&mut self, _event: &str, _root: u64) {
todo!()
}
fn set_text(&mut self, text: &str, root: u64) {
let el = self.nodes[root as usize].as_ref().unwrap();
el.set_text_content(Some(text))
}
fn set_attribute(&mut self, name: &str, value: &str, ns: Option<&str>, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if ns == Some("style") {
if let Some(el) = node.dyn_ref::<Element>() {
let el = el.dyn_ref::<HtmlElement>().unwrap();
let style_dc: CssStyleDeclaration = el.style();
style_dc.set_property(name, value).unwrap();
}
} else {
let fallback = || {
let el = node.dyn_ref::<Element>().unwrap();
el.set_attribute(name, value).unwrap()
};
match name {
"dangerous_inner_html" => {
if let Some(el) = node.dyn_ref::<Element>() {
el.set_inner_html(value);
}
}
"value" => {
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
/*
if the attribute being set is the same as the value of the input, then don't bother setting it.
This is used in controlled components to keep the cursor in the right spot.
this logic should be moved into the virtualdom since we have the notion of "volatile"
*/
if input.value() != value {
input.set_value(value);
}
} else if let Some(node) = node.dyn_ref::<HtmlTextAreaElement>() {
if name == "value" {
node.set_value(value);
}
} else {
fallback();
}
}
"checked" => {
if let Some(input) = node.dyn_ref::<HtmlInputElement>() {
match value {
"true" => input.set_checked(true),
"false" => input.set_checked(false),
_ => fallback(),
}
} else {
fallback();
}
}
"selected" => {
if let Some(node) = node.dyn_ref::<HtmlOptionElement>() {
node.set_selected(true);
} else {
fallback();
}
}
_ => {
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
if value == "false" {
if let Some(el) = node.dyn_ref::<Element>() {
match name {
"allowfullscreen"
| "allowpaymentrequest"
| "async"
| "autofocus"
| "autoplay"
| "checked"
| "controls"
| "default"
| "defer"
| "disabled"
| "formnovalidate"
| "hidden"
| "ismap"
| "itemscope"
| "loop"
| "multiple"
| "muted"
| "nomodule"
| "novalidate"
| "open"
| "playsinline"
| "readonly"
| "required"
| "reversed"
| "selected"
| "truespeed" => {
let _ = el.remove_attribute(name);
}
_ => {
let _ = el.set_attribute(name, value);
}
};
}
} else {
fallback();
}
}
}
}
}
fn remove_attribute(&mut self, name: &str, root: u64) {
let node = self.nodes[root as usize].as_ref().unwrap();
if let Some(node) = node.dyn_ref::<web_sys::Element>() {
node.remove_attribute(name).unwrap();
}
if let Some(node) = node.dyn_ref::<HtmlInputElement>() {
// Some attributes are "volatile" and don't work through `removeAttribute`.
if name == "value" {
node.set_value("");
}
if name == "checked" {
node.set_checked(false);
}
}
if let Some(node) = node.dyn_ref::<HtmlOptionElement>() {
if name == "selected" {
node.set_selected(true);
}
}
}
fn insert_after(&mut self, n: u32, root: u64) {
let old = self.nodes[root as usize].as_ref().unwrap();
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - n as usize)..)
.collect();
if let Some(el) = old.dyn_ref::<Element>() {
el.after_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::CharacterData>() {
el.after_with_node(&arr).unwrap();
} else if let Some(el) = old.dyn_ref::<web_sys::DocumentType>() {
el.after_with_node(&arr).unwrap();
}
}
fn insert_before(&mut self, n: u32, root: u64) {
let anchor = self.nodes[root as usize].as_ref().unwrap();
if n == 1 {
let before = self.stack.pop();
anchor
.parent_node()
.unwrap()
.insert_before(&before, Some(&anchor))
.unwrap();
} else {
let arr: js_sys::Array = self
.stack
.list
.drain((self.stack.list.len() - n as usize)..)
.collect();
if let Some(el) = anchor.dyn_ref::<Element>() {
el.before_with_node(&arr).unwrap();
} else if let Some(el) = anchor.dyn_ref::<web_sys::CharacterData>() {
el.before_with_node(&arr).unwrap();
} else if let Some(el) = anchor.dyn_ref::<web_sys::DocumentType>() {
el.before_with_node(&arr).unwrap();
}
}
}
}
#[derive(Debug, Default)]
struct Stack {
list: Vec<Node>,
}
impl Stack {
#[inline]
fn with_capacity(cap: usize) -> Self {
Stack {
list: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, node: Node) {
self.list.push(node);
}
#[inline]
fn pop(&mut self) -> Node {
self.list.pop().unwrap()
}
fn top(&self) -> &Node {
match self.list.last() {
Some(a) => a,
None => panic!("Called 'top' of an empty stack, make sure to push the root first"),
}
}
}
pub struct DioxusWebsysEvent(web_sys::Event);
// safety: currently the web is not multithreaded and our VirtualDom exists on the same thread
unsafe impl Send for DioxusWebsysEvent {}
unsafe impl Sync for DioxusWebsysEvent {}
// todo: some of these events are being casted to the wrong event type.
// We need tests that simulate clicks/etc and make sure every event type works.
fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc<dyn Any + Send + Sync> {
use dioxus_html::on::*;
use dioxus_html::KeyCode;
match event.type_().as_str() {
"copy" | "cut" | "paste" => Arc::new(ClipboardData {}),
"compositionend" | "compositionstart" | "compositionupdate" => {
let evt: &web_sys::CompositionEvent = event.dyn_ref().unwrap();
Arc::new(CompositionData {
data: evt.data().unwrap_or_default(),
})
}
"keydown" | "keypress" | "keyup" => {
let evt: &web_sys::KeyboardEvent = event.dyn_ref().unwrap();
Arc::new(KeyboardData {
alt_key: evt.alt_key(),
char_code: evt.char_code(),
key: evt.key(),
key_code: KeyCode::from_raw_code(evt.key_code() as u8),
ctrl_key: evt.ctrl_key(),
locale: "not implemented".to_string(),
location: evt.location() as usize,
meta_key: evt.meta_key(),
repeat: evt.repeat(),
shift_key: evt.shift_key(),
which: evt.which() as usize,
})
}
"focus" | "blur" => Arc::new(FocusData {}),
// todo: these handlers might get really slow if the input box gets large and allocation pressure is heavy
// don't have a good solution with the serialized event problem
"change" | "input" | "invalid" | "reset" | "submit" => {
let evt: &web_sys::Event = event.dyn_ref().unwrap();
let target: web_sys::EventTarget = evt.target().unwrap();
let value: String = (&target)
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
// todo: special case more input types
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => "true".to_string(),
false => "false".to_string(),
}
},
_ => {
input.value()
}
}
})
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlTextAreaElement| input.value())
})
// select elements are NOT input events - because - why woudn't they be??
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlSelectElement| input.value())
})
.or_else(|| {
target
.dyn_ref::<web_sys::HtmlElement>()
.unwrap()
.text_content()
})
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
Arc::new(FormData { value })
}
"click" | "contextmenu" | "doubleclick" | "drag" | "dragend" | "dragenter" | "dragexit"
| "dragleave" | "dragover" | "dragstart" | "drop" | "mousedown" | "mouseenter"
| "mouseleave" | "mousemove" | "mouseout" | "mouseover" | "mouseup" => {
let evt: &web_sys::MouseEvent = event.dyn_ref().unwrap();
Arc::new(MouseData {
alt_key: evt.alt_key(),
button: evt.button(),
buttons: evt.buttons(),
client_x: evt.client_x(),
client_y: evt.client_y(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
screen_x: evt.screen_x(),
screen_y: evt.screen_y(),
shift_key: evt.shift_key(),
page_x: evt.page_x(),
page_y: evt.page_y(),
})
}
"pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "gotpointercapture"
| "lostpointercapture" | "pointerenter" | "pointerleave" | "pointerover" | "pointerout" => {
let evt: &web_sys::PointerEvent = event.dyn_ref().unwrap();
Arc::new(PointerData {
alt_key: evt.alt_key(),
button: evt.button(),
buttons: evt.buttons(),
client_x: evt.client_x(),
client_y: evt.client_y(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
page_x: evt.page_x(),
page_y: evt.page_y(),
screen_x: evt.screen_x(),
screen_y: evt.screen_y(),
shift_key: evt.shift_key(),
pointer_id: evt.pointer_id(),
width: evt.width(),
height: evt.height(),
pressure: evt.pressure(),
tangential_pressure: evt.tangential_pressure(),
tilt_x: evt.tilt_x(),
tilt_y: evt.tilt_y(),
twist: evt.twist(),
pointer_type: evt.pointer_type(),
is_primary: evt.is_primary(),
// get_modifier_state: evt.get_modifier_state(),
})
}
"select" => Arc::new(SelectionData {}),
"touchcancel" | "touchend" | "touchmove" | "touchstart" => {
let evt: &web_sys::TouchEvent = event.dyn_ref().unwrap();
Arc::new(TouchData {
alt_key: evt.alt_key(),
ctrl_key: evt.ctrl_key(),
meta_key: evt.meta_key(),
shift_key: evt.shift_key(),
})
}
"scroll" => Arc::new(()),
"wheel" => {
let evt: &web_sys::WheelEvent = event.dyn_ref().unwrap();
Arc::new(WheelData {
delta_x: evt.delta_x(),
delta_y: evt.delta_y(),
delta_z: evt.delta_z(),
delta_mode: evt.delta_mode(),
})
}
"animationstart" | "animationend" | "animationiteration" => {
let evt: &web_sys::AnimationEvent = event.dyn_ref().unwrap();
Arc::new(AnimationData {
elapsed_time: evt.elapsed_time(),
animation_name: evt.animation_name(),
pseudo_element: evt.pseudo_element(),
})
}
"transitionend" => {
let evt: &web_sys::TransitionEvent = event.dyn_ref().unwrap();
Arc::new(TransitionData {
elapsed_time: evt.elapsed_time(),
property_name: evt.property_name(),
pseudo_element: evt.pseudo_element(),
})
}
"abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied" | "encrypted"
| "ended" | "error" | "loadeddata" | "loadedmetadata" | "loadstart" | "pause" | "play"
| "playing" | "progress" | "ratechange" | "seeked" | "seeking" | "stalled" | "suspend"
| "timeupdate" | "volumechange" | "waiting" => Arc::new(MediaData {}),
"toggle" => Arc::new(ToggleData {}),
_ => Arc::new(()),
}
}
/// This function decodes a websys event and produces an EventTrigger
/// With the websys implementation, we attach a unique key to the nodes
fn decode_trigger(event: &web_sys::Event) -> anyhow::Result<UserEvent> {
use anyhow::Context;
let target = event
.target()
.expect("missing target")
.dyn_into::<Element>()
.expect("not a valid element");
let typ = event.type_();
let element_id = target
.get_attribute("dioxus-id")
.context("Could not find element id on event target")?
.parse()?;
Ok(UserEvent {
name: event_name_from_typ(&typ),
data: virtual_event_from_websys_event(event.clone()),
element: Some(ElementId(element_id)),
scope_id: None,
priority: dioxus_core::EventPriority::Medium,
})
}
pub(crate) fn load_document() -> Document {
web_sys::window()
.expect("should have access to the Window")
.document()
.expect("should have access to the Document")
}
fn event_name_from_typ(typ: &str) -> &'static str {
match typ {
"copy" => "copy",
"cut" => "cut",
"paste" => "paste",
"compositionend" => "compositionend",
"compositionstart" => "compositionstart",
"compositionupdate" => "compositionupdate",
"keydown" => "keydown",
"keypress" => "keypress",
"keyup" => "keyup",
"focus" => "focus",
"blur" => "blur",
"change" => "change",
"input" => "input",
"invalid" => "invalid",
"reset" => "reset",
"submit" => "submit",
"click" => "click",
"contextmenu" => "contextmenu",
"doubleclick" => "doubleclick",
"drag" => "drag",
"dragend" => "dragend",
"dragenter" => "dragenter",
"dragexit" => "dragexit",
"dragleave" => "dragleave",
"dragover" => "dragover",
"dragstart" => "dragstart",
"drop" => "drop",
"mousedown" => "mousedown",
"mouseenter" => "mouseenter",
"mouseleave" => "mouseleave",
"mousemove" => "mousemove",
"mouseout" => "mouseout",
"mouseover" => "mouseover",
"mouseup" => "mouseup",
"pointerdown" => "pointerdown",
"pointermove" => "pointermove",
"pointerup" => "pointerup",
"pointercancel" => "pointercancel",
"gotpointercapture" => "gotpointercapture",
"lostpointercapture" => "lostpointercapture",
"pointerenter" => "pointerenter",
"pointerleave" => "pointerleave",
"pointerover" => "pointerover",
"pointerout" => "pointerout",
"select" => "select",
"touchcancel" => "touchcancel",
"touchend" => "touchend",
"touchmove" => "touchmove",
"touchstart" => "touchstart",
"scroll" => "scroll",
"wheel" => "wheel",
"animationstart" => "animationstart",
"animationend" => "animationend",
"animationiteration" => "animationiteration",
"transitionend" => "transitionend",
"abort" => "abort",
"canplay" => "canplay",
"canplaythrough" => "canplaythrough",
"durationchange" => "durationchange",
"emptied" => "emptied",
"encrypted" => "encrypted",
"ended" => "ended",
"error" => "error",
"loadeddata" => "loadeddata",
"loadedmetadata" => "loadedmetadata",
"loadstart" => "loadstart",
"pause" => "pause",
"play" => "play",
"playing" => "playing",
"progress" => "progress",
"ratechange" => "ratechange",
"seeked" => "seeked",
"seeking" => "seeking",
"stalled" => "stalled",
"suspend" => "suspend",
"timeupdate" => "timeupdate",
"volumechange" => "volumechange",
"waiting" => "waiting",
"toggle" => "toggle",
_ => {
panic!("unsupported event type")
}
}
}
//! This module provides a mirror of the VirtualDOM Element Slab using a Vector.
use std::ops::{Index, IndexMut};
use web_sys::Node;
pub(crate) struct NodeSlab {
nodes: Vec<Option<Node>>,
}
impl NodeSlab {
pub fn new(capacity: usize) -> NodeSlab {
let nodes = Vec::with_capacity(capacity);
NodeSlab { nodes }
}
}
impl Index<usize> for NodeSlab {
type Output = Option<Node>;
fn index(&self, index: usize) -> &Self::Output {
&self.nodes[index]
}
}
impl IndexMut<usize> for NodeSlab {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
if index >= self.nodes.capacity() * 3 {
panic!("Trying to mutate an element way too far out of bounds");
}
if index + 1 > self.nodes.len() {
self.nodes.resize_with(index + 1, || None);
}
&mut self.nodes[index]
}
}
#[derive(Debug, Default)]
struct Stack {
list: Vec<Node>,
}
impl Stack {
#[inline]
fn with_capacity(cap: usize) -> Self {
Stack {
list: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, node: Node) {
self.list.push(node);
}
#[inline]
fn pop(&mut self) -> Node {
self.list.pop().unwrap()
}
fn top(&self) -> &Node {
match self.list.last() {
Some(a) => a,
None => panic!("Called 'top' of an empty stack, make sure to push the root first"),
}
}
}
+17 -5
View File
@@ -80,7 +80,8 @@ impl WebsysDom {
*last_node_was_text = true;
self.nodes[node_id.0] = Some(node);
self.interpreter.set_node(node_id.0, node);
// self.nodes[node_id.0] = Some(node);
*cur_place += 1;
}
@@ -105,7 +106,8 @@ impl WebsysDom {
.set_attribute("dioxus-id", s.as_str())
.unwrap();
self.nodes[node_id.0] = Some(node.clone());
self.interpreter.set_node(node_id.0, node.clone());
// self.nodes[node_id.0] = Some(node.clone());
*cur_place += 1;
@@ -116,7 +118,15 @@ impl WebsysDom {
// we cant have the last node be text
let mut last_node_was_text = false;
for child in vel.children {
self.rehydrate_single(nodes, place, dom, &child, &mut last_node_was_text)?;
self.rehydrate_single(nodes, place, dom, child, &mut last_node_was_text)?;
}
for listener in vel.listeners {
self.interpreter.NewEventListener(
listener.event,
listener.mounted_node.get().unwrap().as_u64(),
self.handler.as_ref().unchecked_ref(),
);
}
place.pop();
@@ -135,14 +145,16 @@ impl WebsysDom {
let cur_place = place.last_mut().unwrap();
let node = nodes.last().unwrap().child_nodes().get(*cur_place).unwrap();
self.nodes[node_id.0] = Some(node);
self.interpreter.set_node(node_id.0, node);
// self.nodes[node_id.0] = Some(node);
*cur_place += 1;
}
VNode::Fragment(el) => {
for el in el.children {
self.rehydrate_single(nodes, place, dom, &el, last_node_was_text)?;
self.rehydrate_single(nodes, place, dom, el, last_node_was_text)?;
}
}
+1 -2
View File
@@ -68,8 +68,7 @@ impl RafLoop {
let ric_fn = self.ric_closure.as_ref().dyn_ref::<Function>().unwrap();
let _cb_id: u32 = self.window.request_idle_callback(ric_fn).unwrap();
let deadline = self.ric_receiver.recv().await.unwrap();
let deadline = TimeoutFuture::new(deadline);
deadline
TimeoutFuture::new(deadline)
}
pub async fn wait_for_raf(&self) {
-1
View File
@@ -1,4 +1,3 @@
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;