Merge branch 'master' into feature/use-shared-state-better-diagnostics
This commit is contained in:
324 files changed
+13509
-6646
No files matched your search
@@ -4,7 +4,7 @@ version = "0.3.0"
|
||||
edition = "2021"
|
||||
authors = ["Jonathan Kelley"]
|
||||
description = "Autofomatter for Dioxus RSX"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com"
|
||||
keywords = ["dom", "ui", "gui", "react"]
|
||||
@@ -14,9 +14,9 @@ keywords = ["dom", "ui", "gui", "react"]
|
||||
dioxus-rsx = { workspace = true }
|
||||
proc-macro2 = { version = "1.0.6", features = ["span-locations"] }
|
||||
quote = "1.0"
|
||||
syn = { version = "1.0.11", features = ["full", "extra-traits"] }
|
||||
syn = { version = "2.0", features = ["full", "extra-traits", "visit"] }
|
||||
serde = { version = "1.0.136", features = ["derive"] }
|
||||
prettyplease = { package = "prettier-please", version = "0.1.16", features = [
|
||||
prettyplease = { package = "prettier-please", version = "0.2", features = [
|
||||
"verbatim",
|
||||
] }
|
||||
|
||||
|
||||
@@ -3,178 +3,24 @@
|
||||
//! Returns all macros that match a pattern. You can use this information to autoformat them later
|
||||
|
||||
use proc_macro2::LineColumn;
|
||||
use syn::{Block, Expr, File, Item, Macro, Stmt};
|
||||
use syn::{visit::Visit, File, Macro};
|
||||
|
||||
type CollectedMacro<'a> = &'a Macro;
|
||||
|
||||
pub fn collect_from_file<'a>(file: &'a File, macros: &mut Vec<CollectedMacro<'a>>) {
|
||||
for item in file.items.iter() {
|
||||
collect_from_item(item, macros);
|
||||
}
|
||||
MacroCollector::visit_file(&mut MacroCollector { macros }, file);
|
||||
}
|
||||
|
||||
pub fn collect_from_item<'a>(item: &'a Item, macros: &mut Vec<CollectedMacro<'a>>) {
|
||||
match item {
|
||||
Item::Fn(f) => collect_from_block(&f.block, macros),
|
||||
|
||||
// Ignore macros if they're not rsx or render
|
||||
Item::Macro(macro_) => {
|
||||
if macro_.mac.path.segments[0].ident == "rsx"
|
||||
|| macro_.mac.path.segments[0].ident == "render"
|
||||
{
|
||||
macros.push(¯o_.mac);
|
||||
}
|
||||
}
|
||||
|
||||
// Currently disabled since we're not focused on autoformatting these
|
||||
Item::Impl(_imp) => {}
|
||||
Item::Trait(_) => {}
|
||||
|
||||
// Global-ish things
|
||||
Item::Static(f) => collect_from_expr(&f.expr, macros),
|
||||
Item::Const(f) => collect_from_expr(&f.expr, macros),
|
||||
Item::Mod(s) => {
|
||||
if let Some((_, block)) = &s.content {
|
||||
for item in block {
|
||||
collect_from_item(item, macros);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// None of these we can really do anything with at the item level
|
||||
Item::Macro2(_)
|
||||
| Item::Enum(_)
|
||||
| Item::ExternCrate(_)
|
||||
| Item::ForeignMod(_)
|
||||
| Item::TraitAlias(_)
|
||||
| Item::Type(_)
|
||||
| Item::Struct(_)
|
||||
| Item::Union(_)
|
||||
| Item::Use(_)
|
||||
| Item::Verbatim(_) => {}
|
||||
_ => {}
|
||||
}
|
||||
struct MacroCollector<'a, 'b> {
|
||||
macros: &'a mut Vec<CollectedMacro<'b>>,
|
||||
}
|
||||
|
||||
pub fn collect_from_block<'a>(block: &'a Block, macros: &mut Vec<CollectedMacro<'a>>) {
|
||||
for stmt in &block.stmts {
|
||||
match stmt {
|
||||
Stmt::Item(item) => collect_from_item(item, macros),
|
||||
Stmt::Local(local) => {
|
||||
if let Some((_eq, init)) = &local.init {
|
||||
collect_from_expr(init, macros);
|
||||
}
|
||||
}
|
||||
Stmt::Expr(exp) | Stmt::Semi(exp, _) => collect_from_expr(exp, macros),
|
||||
}
|
||||
impl<'a, 'b> Visit<'b> for MacroCollector<'a, 'b> {
|
||||
fn visit_macro(&mut self, i: &'b Macro) {
|
||||
self.macros.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_from_expr<'a>(expr: &'a Expr, macros: &mut Vec<CollectedMacro<'a>>) {
|
||||
// collect an expr from the exprs, descending into blocks
|
||||
match expr {
|
||||
Expr::Macro(macro_) => {
|
||||
if macro_.mac.path.segments[0].ident == "rsx"
|
||||
|| macro_.mac.path.segments[0].ident == "render"
|
||||
{
|
||||
macros.push(¯o_.mac);
|
||||
}
|
||||
}
|
||||
|
||||
Expr::MethodCall(e) => {
|
||||
collect_from_expr(&e.receiver, macros);
|
||||
for expr in e.args.iter() {
|
||||
collect_from_expr(expr, macros);
|
||||
}
|
||||
}
|
||||
Expr::Assign(exp) => {
|
||||
collect_from_expr(&exp.left, macros);
|
||||
collect_from_expr(&exp.right, macros);
|
||||
}
|
||||
|
||||
Expr::Async(b) => collect_from_block(&b.block, macros),
|
||||
Expr::Block(b) => collect_from_block(&b.block, macros),
|
||||
Expr::Closure(c) => collect_from_expr(&c.body, macros),
|
||||
Expr::Let(l) => collect_from_expr(&l.expr, macros),
|
||||
Expr::Unsafe(u) => collect_from_block(&u.block, macros),
|
||||
Expr::Loop(l) => collect_from_block(&l.body, macros),
|
||||
|
||||
Expr::Call(c) => {
|
||||
collect_from_expr(&c.func, macros);
|
||||
for expr in c.args.iter() {
|
||||
collect_from_expr(expr, macros);
|
||||
}
|
||||
}
|
||||
|
||||
Expr::ForLoop(b) => {
|
||||
collect_from_expr(&b.expr, macros);
|
||||
collect_from_block(&b.body, macros);
|
||||
}
|
||||
Expr::If(f) => {
|
||||
collect_from_expr(&f.cond, macros);
|
||||
collect_from_block(&f.then_branch, macros);
|
||||
if let Some((_, else_branch)) = &f.else_branch {
|
||||
collect_from_expr(else_branch, macros);
|
||||
}
|
||||
}
|
||||
Expr::Yield(y) => {
|
||||
if let Some(expr) = &y.expr {
|
||||
collect_from_expr(expr, macros);
|
||||
}
|
||||
}
|
||||
|
||||
Expr::Return(r) => {
|
||||
if let Some(expr) = &r.expr {
|
||||
collect_from_expr(expr, macros);
|
||||
}
|
||||
}
|
||||
|
||||
Expr::Match(l) => {
|
||||
collect_from_expr(&l.expr, macros);
|
||||
for arm in l.arms.iter() {
|
||||
if let Some((_, expr)) = &arm.guard {
|
||||
collect_from_expr(expr, macros);
|
||||
}
|
||||
|
||||
collect_from_expr(&arm.body, macros);
|
||||
}
|
||||
}
|
||||
|
||||
Expr::While(w) => {
|
||||
collect_from_expr(&w.cond, macros);
|
||||
collect_from_block(&w.body, macros);
|
||||
}
|
||||
|
||||
// don't both formatting these for now
|
||||
Expr::Array(_)
|
||||
| Expr::AssignOp(_)
|
||||
| Expr::Await(_)
|
||||
| Expr::Binary(_)
|
||||
| Expr::Box(_)
|
||||
| Expr::Break(_)
|
||||
| Expr::Cast(_)
|
||||
| Expr::Continue(_)
|
||||
| Expr::Field(_)
|
||||
| Expr::Group(_)
|
||||
| Expr::Index(_)
|
||||
| Expr::Lit(_)
|
||||
| Expr::Paren(_)
|
||||
| Expr::Path(_)
|
||||
| Expr::Range(_)
|
||||
| Expr::Reference(_)
|
||||
| Expr::Repeat(_)
|
||||
| Expr::Struct(_)
|
||||
| Expr::Try(_)
|
||||
| Expr::TryBlock(_)
|
||||
| Expr::Tuple(_)
|
||||
| Expr::Type(_)
|
||||
| Expr::Unary(_)
|
||||
| Expr::Verbatim(_) => {}
|
||||
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn byte_offset(input: &str, location: LineColumn) -> usize {
|
||||
let mut offset = 0;
|
||||
for _ in 1..location.line {
|
||||
|
||||
@@ -165,7 +165,14 @@ impl Writer<'_> {
|
||||
match &field.content {
|
||||
ContentField::ManExpr(exp) => {
|
||||
let out = prettyplease::unparse_expr(exp);
|
||||
write!(self.out, "{name}: {out}")?;
|
||||
let mut lines = out.split('\n').peekable();
|
||||
let first = lines.next().unwrap();
|
||||
write!(self.out, "{name}: {first}")?;
|
||||
for line in lines {
|
||||
self.out.new_line()?;
|
||||
self.out.indented_tab()?;
|
||||
write!(self.out, "{line}")?;
|
||||
}
|
||||
}
|
||||
ContentField::Formatted(s) => {
|
||||
write!(
|
||||
|
||||
@@ -48,7 +48,6 @@ impl Writer<'_> {
|
||||
key,
|
||||
attributes,
|
||||
children,
|
||||
_is_static,
|
||||
brace,
|
||||
} = el;
|
||||
|
||||
@@ -217,7 +216,26 @@ impl Writer<'_> {
|
||||
}
|
||||
ElementAttr::AttrExpression { name, value } => {
|
||||
let out = prettyplease::unparse_expr(value);
|
||||
write!(self.out, "{name}: {out}")?;
|
||||
let mut lines = out.split('\n').peekable();
|
||||
let first = lines.next().unwrap();
|
||||
|
||||
// a one-liner for whatever reason
|
||||
// Does not need a new line
|
||||
if lines.peek().is_none() {
|
||||
write!(self.out, "{name}: {first}")?;
|
||||
} else {
|
||||
writeln!(self.out, "{name}: {first}")?;
|
||||
|
||||
while let Some(line) = lines.next() {
|
||||
self.out.indented_tab()?;
|
||||
write!(self.out, "{line}")?;
|
||||
if lines.peek().is_none() {
|
||||
write!(self.out, "")?;
|
||||
} else {
|
||||
writeln!(self.out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ElementAttr::CustomAttrText { name, value } => {
|
||||
|
||||
@@ -27,41 +27,29 @@ impl Writer<'_> {
|
||||
// If the expr is multiline, we want to collect all of its lines together and write them out properly
|
||||
// This involves unshifting the first line if it's aligned
|
||||
let first_line = &self.src[start.line - 1];
|
||||
write!(
|
||||
self.out,
|
||||
"{}",
|
||||
&first_line[start.column - 1..first_line.len()].trim()
|
||||
)?;
|
||||
write!(self.out, "{}", &first_line[start.column - 1..].trim_start())?;
|
||||
|
||||
let first_prefix = &self.src[start.line - 1][..start.column];
|
||||
let offset = match first_prefix.trim() {
|
||||
"" => 0,
|
||||
_ => first_prefix
|
||||
.chars()
|
||||
.rev()
|
||||
.take_while(|c| c.is_whitespace())
|
||||
.count() as isize,
|
||||
};
|
||||
let prev_block_indent_level = crate::leading_whitespaces(first_line) / 4;
|
||||
|
||||
for (id, line) in self.src[start.line..end.line].iter().enumerate() {
|
||||
writeln!(self.out)?;
|
||||
// trim the leading whitespace
|
||||
let line = match id {
|
||||
x if x == (end.line - start.line) - 1 => &line[..end.column],
|
||||
_ => line,
|
||||
// check if this is the last line
|
||||
let line = {
|
||||
if id == (end.line - start.line) - 1 {
|
||||
&line[..end.column]
|
||||
} else {
|
||||
line
|
||||
}
|
||||
};
|
||||
|
||||
if offset < 0 {
|
||||
for _ in 0..-offset {
|
||||
write!(self.out, " ")?;
|
||||
}
|
||||
// trim the leading whitespace
|
||||
let previous_indent = crate::leading_whitespaces(line) / 4;
|
||||
let offset = previous_indent.saturating_sub(prev_block_indent_level);
|
||||
let required_indent = self.out.indent + offset;
|
||||
self.out.write_tabs(required_indent)?;
|
||||
|
||||
write!(self.out, "{line}")?;
|
||||
} else {
|
||||
let offset = offset as usize;
|
||||
let right = &line[offset..];
|
||||
write!(self.out, "{right}")?;
|
||||
}
|
||||
let line = line.trim_start();
|
||||
write!(self.out, "{line}")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -58,7 +58,7 @@ pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
|
||||
|
||||
let mut writer = Writer::new(contents);
|
||||
|
||||
// Dont parse nested macros
|
||||
// Don't parse nested macros
|
||||
let mut end_span = LineColumn { column: 0, line: 0 };
|
||||
for item in macros {
|
||||
let macro_path = &item.path.segments[0].ident;
|
||||
@@ -68,16 +68,11 @@ pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
|
||||
continue;
|
||||
}
|
||||
|
||||
// item.parse_body::<CallBody>();
|
||||
let body = item.parse_body::<CallBody>().unwrap();
|
||||
|
||||
let rsx_start = macro_path.span().start();
|
||||
|
||||
writer.out.indent = &writer.src[rsx_start.line - 1]
|
||||
.chars()
|
||||
.take_while(|c| *c == ' ')
|
||||
.count()
|
||||
/ 4;
|
||||
writer.out.indent = leading_whitespaces(writer.src[rsx_start.line - 1]) / 4;
|
||||
|
||||
write_body(&mut writer, &body);
|
||||
|
||||
@@ -91,7 +86,8 @@ pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
|
||||
MacroDelimiter::Paren(b) => b.span,
|
||||
MacroDelimiter::Brace(b) => b.span,
|
||||
MacroDelimiter::Bracket(b) => b.span,
|
||||
};
|
||||
}
|
||||
.join();
|
||||
|
||||
let mut formatted = String::new();
|
||||
|
||||
@@ -230,3 +226,14 @@ pub(crate) fn write_ifmt(input: &IfmtInput, writable: &mut impl Write) -> std::f
|
||||
let display = DisplayIfmt(input);
|
||||
write!(writable, "{}", display)
|
||||
}
|
||||
|
||||
pub fn leading_whitespaces(input: &str) -> usize {
|
||||
input
|
||||
.chars()
|
||||
.map_while(|c| match c {
|
||||
' ' => Some(1),
|
||||
'\t' => Some(4),
|
||||
_ => None,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
@@ -5,7 +5,7 @@ authors = ["Jonathan Kelley"]
|
||||
edition = "2021"
|
||||
description = "CLI tool for developing, testing, and publishing Dioxus apps"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
# cli core
|
||||
@@ -57,7 +57,7 @@ flate2 = "1.0.22"
|
||||
tar = "0.4.38"
|
||||
zip = "0.6.2"
|
||||
tower = "0.4.12"
|
||||
syn = { version = "1.0", features = ["full", "extra-traits"] }
|
||||
syn = { version = "2.0", features = ["full", "extra-traits"] }
|
||||
proc-macro2 = { version = "1.0", features = ["span-locations"] }
|
||||
lazy_static = "1.4.0"
|
||||
|
||||
@@ -81,18 +81,13 @@ rsx-rosetta = { workspace = true }
|
||||
dioxus-rsx = { workspace = true }
|
||||
dioxus-html = { workspace = true, features = ["hot-reload-context"] }
|
||||
dioxus-core = { workspace = true, features = ["serialize"] }
|
||||
dioxus-hot-reload = { workspace = true }
|
||||
interprocess-docfix = { version = "1.2.2" }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
plugin = ["mlua"]
|
||||
|
||||
# install path dx and dioxus as the same command
|
||||
# so, they're not really aliases
|
||||
# eventually dx will defer to the right version of dioxus
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "dioxus"
|
||||
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "dx"
|
||||
@@ -4,7 +4,7 @@
|
||||
name = "dioxus-cli"
|
||||
|
||||
# default platfrom
|
||||
# you can also use `dioxus serve/build --platform XXX` to use other platform
|
||||
# you can also use `dx serve/build --platform XXX` to use other platform
|
||||
# value: web | desktop
|
||||
default_platform = "desktop"
|
||||
|
||||
@@ -42,4 +42,4 @@ script = []
|
||||
|
||||
# use binaryen.wasm-opt for output Wasm file
|
||||
# binaryen just will trigger in `web` platform
|
||||
binaryen = { wasm_opt = true }
|
||||
binaryen = { wasm_opt = true }
|
||||
@@ -24,7 +24,7 @@ cargo install --path . --debug
|
||||
|
||||
## Get Started
|
||||
|
||||
Use `dioxus create project-name` to initialize a new Dioxus project. <br>
|
||||
Use `dx create project-name` to initialize a new Dioxus project. <br>
|
||||
|
||||
It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxus-template) repository.
|
||||
|
||||
@@ -33,7 +33,7 @@ It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxu
|
||||
Alternatively, you can specify the template path:
|
||||
|
||||
```
|
||||
dioxus create hello --template gh:dioxuslabs/dioxus-template
|
||||
dx create hello --template gh:dioxuslabs/dioxus-template
|
||||
```
|
||||
|
||||
## Dioxus Config File
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
In this chapter we will introduce all `dioxus-cli` commands.
|
||||
|
||||
> You can also use `dioxus --help` to get cli help info.
|
||||
> You can also use `dx --help` to get cli help info.
|
||||
|
||||
```
|
||||
dioxus
|
||||
dx
|
||||
Build, bundle, & ship your Dioxus app
|
||||
|
||||
USAGE:
|
||||
dioxus [OPTIONS] <SUBCOMMAND>
|
||||
dx [OPTIONS] <SUBCOMMAND>
|
||||
|
||||
OPTIONS:
|
||||
-h, --help Print help information
|
||||
@@ -23,4 +23,4 @@ SUBCOMMANDS:
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
serve Build, watch & serve the Rust WASM app and all of its assets
|
||||
translate Translate some html file into a Dioxus component
|
||||
```
|
||||
```
|
||||
@@ -1,24 +1,25 @@
|
||||
# Build
|
||||
|
||||
The `dioxus build` command can help you `pack & build` a dioxus project.
|
||||
The `dx build` command can help you `pack & build` a dioxus project.
|
||||
|
||||
```
|
||||
dioxus-build
|
||||
dioxus-build
|
||||
Build the Rust WASM app and all of its assets
|
||||
|
||||
USAGE:
|
||||
dioxus build [OPTIONS]
|
||||
dx build [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--example <EXAMPLE> [default: ""]
|
||||
--platform <PLATFORM> [default: "default_platform"]
|
||||
--release [default: false]
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
You can use this command to build a project:
|
||||
|
||||
```
|
||||
dioxus build --release
|
||||
dx build --release
|
||||
```
|
||||
|
||||
## Target platform
|
||||
@@ -27,14 +28,22 @@ Use the `platform` option to choose your target platform:
|
||||
|
||||
```
|
||||
# for desktop project
|
||||
dioxus build --platform desktop
|
||||
dx build --platform desktop
|
||||
```
|
||||
|
||||
`platform` currently only supports `desktop` & `web`.
|
||||
|
||||
```
|
||||
# for web project
|
||||
dioxus build --platform web
|
||||
dx build --platform web
|
||||
```
|
||||
|
||||
## Specify workspace bin
|
||||
|
||||
You can add the `--bin` option to select which crate you want Dioxus to build:
|
||||
|
||||
```
|
||||
dx build --bin app
|
||||
```
|
||||
|
||||
## Build Example
|
||||
@@ -43,5 +52,5 @@ You can use the `example` option to select a example to build:
|
||||
|
||||
```
|
||||
# build the `test` example
|
||||
dioxus build --exmaple test
|
||||
```
|
||||
dx build --exmaple test
|
||||
```
|
||||
@@ -1,18 +1,27 @@
|
||||
# Clean
|
||||
|
||||
`dioxus clean` will clear the build artifacts (the out_dir and the cargo cache)
|
||||
`dx clean` will clear the build artifacts (the out_dir and the cargo cache)
|
||||
|
||||
```
|
||||
dioxus-clean
|
||||
dioxus-clean
|
||||
Clean build artifacts
|
||||
|
||||
USAGE:
|
||||
dioxus clean
|
||||
dx clean [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
```
|
||||
dioxus clean
|
||||
dx clean
|
||||
```
|
||||
|
||||
# Specify workspace bin
|
||||
You can add the `--bin` option to select which crate you want Dioxus to clean artifacts from:
|
||||
|
||||
```
|
||||
dx clean --bin app
|
||||
```
|
||||
@@ -1,25 +1,26 @@
|
||||
# Serve
|
||||
|
||||
The `dioxus serve` can start a dev server with hot-reloading
|
||||
The `dx serve` can start a dev server with hot-reloading
|
||||
|
||||
```
|
||||
dioxus-serve
|
||||
dioxus-serve
|
||||
Build, watch & serve the Rust WASM app and all of its assets
|
||||
|
||||
USAGE:
|
||||
dioxus serve [OPTIONS]
|
||||
dx serve [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--example <EXAMPLE> [default: ""]
|
||||
--platform <PLATFORM> [default: "default_platform"]
|
||||
--release [default: false]
|
||||
--hot-reload [default: false]ß
|
||||
--hot-reload [default: false]
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
You can use this command to build project and start a dev server:
|
||||
|
||||
```
|
||||
dioxus serve
|
||||
dx serve
|
||||
```
|
||||
|
||||
## Serve Example
|
||||
@@ -28,7 +29,15 @@ You can use the `example` option to serve a example:
|
||||
|
||||
```
|
||||
# serve the `test` example
|
||||
dioxus serve --exmaple test
|
||||
dx serve --exmaple test
|
||||
```
|
||||
|
||||
## Specify workspace bin
|
||||
|
||||
You can add the `--bin` option to select which crate you want Dioxus to build and serve:
|
||||
|
||||
```
|
||||
dx serve --bin app
|
||||
```
|
||||
|
||||
## Open Browser
|
||||
@@ -36,7 +45,7 @@ dioxus serve --exmaple test
|
||||
You can add the `--open` option to open system default browser when server startup:
|
||||
|
||||
```
|
||||
dioxus serve --open
|
||||
dx serve --open
|
||||
```
|
||||
|
||||
## RSX Hot Reloading
|
||||
@@ -44,7 +53,7 @@ dioxus serve --open
|
||||
You can add the `--hot-reload` flag to enable [rsx hot reloading](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/hot_reload.html). This will allow you to reload some rsx changes without a full recompile:
|
||||
|
||||
```
|
||||
dioxus serve --open
|
||||
dx serve --open
|
||||
```
|
||||
|
||||
## Cross Origin Policy
|
||||
@@ -57,5 +66,5 @@ You can add the `cross-origin-policy` option to change cross-origin header to:
|
||||
```
|
||||
|
||||
```
|
||||
dioxus serve --corss-origin-policy
|
||||
```
|
||||
dx serve --corss-origin-policy
|
||||
```
|
||||
@@ -1,13 +1,13 @@
|
||||
# Translate
|
||||
|
||||
`dioxus translate` can translate some `html` file into a Dioxus compoent
|
||||
`dx translate` can translate some `html` file into a Dioxus compoent
|
||||
|
||||
```
|
||||
dioxus-translate
|
||||
dioxus-translate
|
||||
Translate some source file into a Dioxus component
|
||||
|
||||
USAGE:
|
||||
dioxus translate [OPTIONS] [OUTPUT]
|
||||
dx translate [OPTIONS] [OUTPUT]
|
||||
|
||||
ARGS:
|
||||
<OUTPUT> Output file, defaults to stdout if not present
|
||||
@@ -22,7 +22,7 @@ OPTIONS:
|
||||
You can use the `file` option to set path to the `html` file to translate:
|
||||
|
||||
```
|
||||
dioxus transtale --file ./index.html
|
||||
dx transtale --file ./index.html
|
||||
```
|
||||
|
||||
## Output rsx to a file
|
||||
@@ -30,7 +30,7 @@ dioxus transtale --file ./index.html
|
||||
You can pass a file to the traslate command to set the path to write the output of the command to:
|
||||
|
||||
```
|
||||
dioxus translate --file ./index.html component.rsx
|
||||
dx translate --file ./index.html component.rsx
|
||||
```
|
||||
|
||||
## Output rsx to a file
|
||||
@@ -38,7 +38,7 @@ dioxus translate --file ./index.html component.rsx
|
||||
Setting the `component` option will create a compoent from the HTML:
|
||||
|
||||
```
|
||||
dioxus translate --file ./index.html --component
|
||||
dx translate --file ./index.html --component
|
||||
```
|
||||
|
||||
## Example
|
||||
@@ -65,4 +65,4 @@ fn component(cx: Scope) -> Element {
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
```
|
||||
@@ -29,8 +29,8 @@ General application confiration:
|
||||
# default: web
|
||||
default_platform = "web"
|
||||
```
|
||||
if you change this to `desktop`, the `dioxus build` will default building a desktop app
|
||||
3. ***out_dir*** - The directory to place the build artifacts from `dioxus build` or `dioxus service` into. This is also where the `assets` directory will be copied to
|
||||
if you change this to `desktop`, the `dx build` will default building a desktop app
|
||||
3. ***out_dir*** - The directory to place the build artifacts from `dx build` or `dx service` into. This is also where the `assets` directory will be copied to
|
||||
```
|
||||
out_dir = "dist"
|
||||
```
|
||||
|
||||
@@ -4,10 +4,10 @@ Once you have the Dioxus CLI tool installed, you can use it to create dioxus pro
|
||||
|
||||
## Initializing a default project
|
||||
|
||||
First, run the `dioxus create` command to create a new project ready to be used with Dioxus and the Dioxus CLI:
|
||||
First, run the `dx create` command to create a new project ready to be used with Dioxus and the Dioxus CLI:
|
||||
|
||||
```
|
||||
dioxus create hello-dioxus
|
||||
dx create hello-dioxus
|
||||
```
|
||||
|
||||
> It will clone a default template from github template: [DioxusLabs/dioxus-template](https://github.com/DioxusLabs/dioxus-template)
|
||||
@@ -15,7 +15,7 @@ dioxus create hello-dioxus
|
||||
>
|
||||
> You can choose to create your project from a different template by passing the `template` argument:
|
||||
> ```
|
||||
> dioxus init hello-dioxus --template=gh:dioxuslabs/dioxus-template
|
||||
> dx init hello-dioxus --template=gh:dioxuslabs/dioxus-template
|
||||
> ```
|
||||
|
||||
Next, move the current directory into your new project:
|
||||
@@ -33,7 +33,7 @@ cd hello-dioxus
|
||||
Finally, create serve your project with the Dioxus CLI:
|
||||
|
||||
```
|
||||
dioxus serve
|
||||
dx serve
|
||||
```
|
||||
|
||||
By default, the CLI serve your site at: [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> For Cli 0.2.0 we will add `plugin-develop` support.
|
||||
|
||||
Before the 0.2.0 we use `dioxus tool` to use & install some plugin, but we think that is not good for extend cli program, some people want tailwind support, some people want sass support, we can't add all this thing in to the cli source code and we don't have time to maintain a lot of tools that user request, so maybe user make plugin by themself is a good choice.
|
||||
Before the 0.2.0 we use `dx tool` to use & install some plugin, but we think that is not good for extend cli program, some people want tailwind support, some people want sass support, we can't add all this thing in to the cli source code and we don't have time to maintain a lot of tools that user request, so maybe user make plugin by themself is a good choice.
|
||||
|
||||
### Why Lua ?
|
||||
|
||||
@@ -76,4 +76,4 @@ end
|
||||
manager.serve.interval = 1000
|
||||
|
||||
return manager
|
||||
```
|
||||
```
|
||||
@@ -4,7 +4,7 @@
|
||||
name = "{{project-name}}"
|
||||
|
||||
# default platfrom
|
||||
# you can also use `dioxus serve/build --platform XXX` to use other platform
|
||||
# you can also use `dx serve/build --platform XXX` to use other platform
|
||||
# value: web | desktop
|
||||
default_platform = "{{default-platform}}"
|
||||
|
||||
|
||||
+85
-89
@@ -12,7 +12,6 @@ use std::{
|
||||
io::Read,
|
||||
panic,
|
||||
path::PathBuf,
|
||||
process::Command,
|
||||
time::Duration,
|
||||
};
|
||||
use wasm_bindgen_cli_support::Bindgen;
|
||||
@@ -161,7 +160,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
}
|
||||
} else {
|
||||
log::warn!(
|
||||
"Binaryen tool not found, you can use `dioxus tool add binaryen` to install it."
|
||||
"Binaryen tool not found, you can use `dx tool add binaryen` to install it."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -200,7 +199,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
}
|
||||
} else {
|
||||
log::warn!(
|
||||
"Tailwind tool not found, you can use `dioxus tool add tailwindcss` to install it."
|
||||
"Tailwind tool not found, you can use `dx tool add tailwindcss` to install it."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -244,128 +243,125 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<()> {
|
||||
pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResult> {
|
||||
log::info!("🚅 Running build [Desktop] command...");
|
||||
|
||||
let t_start = std::time::Instant::now();
|
||||
let ignore_files = build_assets(config)?;
|
||||
|
||||
let mut cmd = Command::new("cargo");
|
||||
cmd.current_dir(&config.crate_dir)
|
||||
let mut cmd = subprocess::Exec::cmd("cargo")
|
||||
.cwd(&config.crate_dir)
|
||||
.arg("build")
|
||||
.stdout(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit());
|
||||
.arg("--message-format=json");
|
||||
|
||||
if config.release {
|
||||
cmd.arg("--release");
|
||||
cmd = cmd.arg("--release");
|
||||
}
|
||||
if config.verbose {
|
||||
cmd.arg("--verbose");
|
||||
cmd = cmd.arg("--verbose");
|
||||
}
|
||||
|
||||
if config.custom_profile.is_some() {
|
||||
let custom_profile = config.custom_profile.as_ref().unwrap();
|
||||
cmd.arg("--profile");
|
||||
cmd.arg(custom_profile);
|
||||
cmd = cmd.arg("--profile").arg(custom_profile);
|
||||
}
|
||||
|
||||
if config.features.is_some() {
|
||||
let features_str = config.features.as_ref().unwrap().join(" ");
|
||||
cmd.arg("--features");
|
||||
cmd.arg(features_str);
|
||||
cmd = cmd.arg("--features").arg(features_str);
|
||||
}
|
||||
|
||||
match &config.executable {
|
||||
let cmd = match &config.executable {
|
||||
crate::ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
|
||||
crate::ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
|
||||
crate::ExecutableType::Example(name) => cmd.arg("--example").arg(name),
|
||||
};
|
||||
|
||||
let output = cmd.output()?;
|
||||
let warning_messages = prettier_build(cmd)?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(Error::BuildFailed("Program build failed.".into()));
|
||||
}
|
||||
let release_type = match config.release {
|
||||
true => "release",
|
||||
false => "debug",
|
||||
};
|
||||
|
||||
if output.status.success() {
|
||||
let release_type = match config.release {
|
||||
true => "release",
|
||||
false => "debug",
|
||||
};
|
||||
|
||||
let file_name: String;
|
||||
let mut res_path = match &config.executable {
|
||||
crate::ExecutableType::Binary(name) | crate::ExecutableType::Lib(name) => {
|
||||
file_name = name.clone();
|
||||
config.target_dir.join(release_type).join(name)
|
||||
}
|
||||
crate::ExecutableType::Example(name) => {
|
||||
file_name = name.clone();
|
||||
config
|
||||
.target_dir
|
||||
.join(release_type)
|
||||
.join("examples")
|
||||
.join(name)
|
||||
}
|
||||
};
|
||||
|
||||
let target_file = if cfg!(windows) {
|
||||
res_path.set_extension("exe");
|
||||
format!("{}.exe", &file_name)
|
||||
} else {
|
||||
file_name
|
||||
};
|
||||
|
||||
if !config.out_dir.is_dir() {
|
||||
create_dir_all(&config.out_dir)?;
|
||||
let file_name: String;
|
||||
let mut res_path = match &config.executable {
|
||||
crate::ExecutableType::Binary(name) | crate::ExecutableType::Lib(name) => {
|
||||
file_name = name.clone();
|
||||
config.target_dir.join(release_type).join(name)
|
||||
}
|
||||
copy(res_path, &config.out_dir.join(target_file))?;
|
||||
crate::ExecutableType::Example(name) => {
|
||||
file_name = name.clone();
|
||||
config
|
||||
.target_dir
|
||||
.join(release_type)
|
||||
.join("examples")
|
||||
.join(name)
|
||||
}
|
||||
};
|
||||
|
||||
// this code will copy all public file to the output dir
|
||||
if config.asset_dir.is_dir() {
|
||||
let copy_options = fs_extra::dir::CopyOptions {
|
||||
overwrite: true,
|
||||
skip_exist: false,
|
||||
buffer_size: 64000,
|
||||
copy_inside: false,
|
||||
content_only: false,
|
||||
depth: 0,
|
||||
};
|
||||
let target_file = if cfg!(windows) {
|
||||
res_path.set_extension("exe");
|
||||
format!("{}.exe", &file_name)
|
||||
} else {
|
||||
file_name
|
||||
};
|
||||
|
||||
for entry in std::fs::read_dir(&config.asset_dir)? {
|
||||
let path = entry?.path();
|
||||
if path.is_file() {
|
||||
std::fs::copy(&path, &config.out_dir.join(path.file_name().unwrap()))?;
|
||||
} else {
|
||||
match fs_extra::dir::copy(&path, &config.out_dir, ©_options) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("Error copying dir: {}", e);
|
||||
}
|
||||
if !config.out_dir.is_dir() {
|
||||
create_dir_all(&config.out_dir)?;
|
||||
}
|
||||
copy(res_path, &config.out_dir.join(target_file))?;
|
||||
|
||||
// this code will copy all public file to the output dir
|
||||
if config.asset_dir.is_dir() {
|
||||
let copy_options = fs_extra::dir::CopyOptions {
|
||||
overwrite: true,
|
||||
skip_exist: false,
|
||||
buffer_size: 64000,
|
||||
copy_inside: false,
|
||||
content_only: false,
|
||||
depth: 0,
|
||||
};
|
||||
|
||||
for entry in std::fs::read_dir(&config.asset_dir)? {
|
||||
let path = entry?.path();
|
||||
if path.is_file() {
|
||||
std::fs::copy(&path, &config.out_dir.join(path.file_name().unwrap()))?;
|
||||
} else {
|
||||
match fs_extra::dir::copy(&path, &config.out_dir, ©_options) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("Error copying dir: {}", e);
|
||||
}
|
||||
for ignore in &ignore_files {
|
||||
let ignore = ignore.strip_prefix(&config.asset_dir).unwrap();
|
||||
let ignore = config.out_dir.join(ignore);
|
||||
if ignore.is_file() {
|
||||
std::fs::remove_file(ignore)?;
|
||||
}
|
||||
}
|
||||
for ignore in &ignore_files {
|
||||
let ignore = ignore.strip_prefix(&config.asset_dir).unwrap();
|
||||
let ignore = config.out_dir.join(ignore);
|
||||
if ignore.is_file() {
|
||||
std::fs::remove_file(ignore)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"🚩 Build completed: [./{}]",
|
||||
config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("dist"))
|
||||
.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
log::info!(
|
||||
"🚩 Build completed: [./{}]",
|
||||
config
|
||||
.dioxus_config
|
||||
.application
|
||||
.out_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("dist"))
|
||||
.display()
|
||||
);
|
||||
|
||||
println!("build desktop done");
|
||||
|
||||
Ok(BuildResult {
|
||||
warnings: warning_messages,
|
||||
elapsed_time: (t_start - std::time::Instant::now()).as_millis(),
|
||||
})
|
||||
}
|
||||
|
||||
fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
|
||||
@@ -78,7 +78,7 @@ impl Autoformat {
|
||||
///
|
||||
/// Doesn't do mod-descending, so it will still try to format unreachable files. TODO.
|
||||
async fn autoformat_project(check: bool) -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new()?;
|
||||
let crate_config = crate::CrateConfig::new(None)?;
|
||||
|
||||
let mut files_to_format = vec![];
|
||||
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
|
||||
@@ -109,11 +109,17 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
})
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
eprintln!("error formatting file: {}", _path.display());
|
||||
match res {
|
||||
Err(err) => {
|
||||
eprintln!("error formatting file: {}\n{err}", _path.display());
|
||||
None
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
eprintln!("error formatting file: {}\n{err}", _path.display());
|
||||
None
|
||||
}
|
||||
Ok(Ok(res)) => Some(res),
|
||||
}
|
||||
|
||||
res
|
||||
})
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.collect::<Vec<_>>()
|
||||
@@ -122,7 +128,7 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
let files_formatted: usize = counts
|
||||
.into_iter()
|
||||
.map(|f| match f {
|
||||
Ok(Ok(res)) => res,
|
||||
Some(res) => res,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
@@ -136,12 +142,16 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
}
|
||||
|
||||
fn collect_rs_files(folder: &Path, files: &mut Vec<PathBuf>) {
|
||||
let Ok(folder) = folder.read_dir() else { return };
|
||||
let Ok(folder) = folder.read_dir() else {
|
||||
return;
|
||||
};
|
||||
|
||||
// load the gitignore
|
||||
|
||||
for entry in folder {
|
||||
let Ok(entry) = entry else { continue; };
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::cfg::Platform;
|
||||
#[cfg(feature = "plugin")]
|
||||
use crate::plugin::PluginManager;
|
||||
|
||||
@@ -12,8 +13,8 @@ pub struct Build {
|
||||
}
|
||||
|
||||
impl Build {
|
||||
pub fn build(self) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new()?;
|
||||
pub fn build(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new(bin)?;
|
||||
|
||||
// change the release state.
|
||||
crate_config.with_release(self.build.release);
|
||||
@@ -31,27 +32,21 @@ impl Build {
|
||||
crate_config.set_features(self.build.features.unwrap());
|
||||
}
|
||||
|
||||
let platform = self.build.platform.unwrap_or_else(|| {
|
||||
crate_config
|
||||
.dioxus_config
|
||||
.application
|
||||
.default_platform
|
||||
.clone()
|
||||
});
|
||||
let platform = self
|
||||
.build
|
||||
.platform
|
||||
.unwrap_or(crate_config.dioxus_config.application.default_platform);
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_build_start(&crate_config, &platform);
|
||||
|
||||
match platform.as_str() {
|
||||
"web" => {
|
||||
match platform {
|
||||
Platform::Web => {
|
||||
crate::builder::build(&crate_config, false)?;
|
||||
}
|
||||
"desktop" => {
|
||||
Platform::Desktop => {
|
||||
crate::builder::build_desktop(&crate_config, false)?;
|
||||
}
|
||||
_ => {
|
||||
return custom_error!("Unsupported platform target.");
|
||||
}
|
||||
}
|
||||
|
||||
let temp = gen_page(&crate_config.dioxus_config, false);
|
||||
@@ -1,3 +1,6 @@
|
||||
use clap::ValueEnum;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Config options for the build system.
|
||||
@@ -26,8 +29,8 @@ pub struct ConfigOptsBuild {
|
||||
pub profile: Option<String>,
|
||||
|
||||
/// Build platform: support Web & Desktop [default: "default_platform"]
|
||||
#[clap(long)]
|
||||
pub platform: Option<String>,
|
||||
#[clap(long, value_enum)]
|
||||
pub platform: Option<Platform>,
|
||||
|
||||
/// Space separated list of features to activate
|
||||
#[clap(long)]
|
||||
@@ -69,8 +72,8 @@ pub struct ConfigOptsServe {
|
||||
pub profile: Option<String>,
|
||||
|
||||
/// Build platform: support Web & Desktop [default: "default_platform"]
|
||||
#[clap(long)]
|
||||
pub platform: Option<String>,
|
||||
#[clap(long, value_enum)]
|
||||
pub platform: Option<Platform>,
|
||||
|
||||
/// Build with hot reloading rsx [default: false]
|
||||
#[clap(long)]
|
||||
@@ -88,6 +91,16 @@ pub struct ConfigOptsServe {
|
||||
pub features: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Debug)]
|
||||
pub enum Platform {
|
||||
#[clap(name = "web")]
|
||||
#[serde(rename = "web")]
|
||||
Web,
|
||||
#[clap(name = "desktop")]
|
||||
#[serde(rename = "desktop")]
|
||||
Desktop,
|
||||
}
|
||||
|
||||
/// Ensure the given value for `--public-url` is formatted correctly.
|
||||
pub fn parse_public_url(val: &str) -> String {
|
||||
let prefix = if !val.starts_with('/') { "/" } else { "" };
|
||||
|
||||
@@ -6,8 +6,8 @@ use super::*;
|
||||
pub struct Clean {}
|
||||
|
||||
impl Clean {
|
||||
pub fn clean(self) -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new()?;
|
||||
pub fn clean(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let crate_config = crate::CrateConfig::new(bin)?;
|
||||
|
||||
let output = Command::new("cargo")
|
||||
.arg("clean")
|
||||
@@ -41,19 +41,19 @@ impl Config {
|
||||
return Ok(());
|
||||
}
|
||||
let mut file = File::create(conf_path)?;
|
||||
let content = String::from(include_str!("../../assets/dioxus.toml"))
|
||||
let content = String::from(include_str!("../assets/dioxus.toml"))
|
||||
.replace("{{project-name}}", &name)
|
||||
.replace("{{default-platform}}", &platform);
|
||||
file.write_all(content.as_bytes())?;
|
||||
log::info!("🚩 Init config file completed.");
|
||||
}
|
||||
Config::FormatPrint {} => {
|
||||
println!("{:#?}", crate::CrateConfig::new()?.dioxus_config);
|
||||
println!("{:#?}", crate::CrateConfig::new(None)?.dioxus_config);
|
||||
}
|
||||
Config::CustomHtml {} => {
|
||||
let html_path = crate_root.join("index.html");
|
||||
let mut file = File::create(html_path)?;
|
||||
let content = include_str!("../../assets/index.html");
|
||||
let content = include_str!("../assets/index.html");
|
||||
file.write_all(content.as_bytes())?;
|
||||
log::info!("🚩 Create custom html file done.");
|
||||
}
|
||||
File renamed without changes.
@@ -36,6 +36,10 @@ pub struct Cli {
|
||||
/// Enable verbose logging.
|
||||
#[clap(short)]
|
||||
pub v: bool,
|
||||
|
||||
/// Specify bin target
|
||||
#[clap(global = true, long)]
|
||||
pub bin: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
|
||||
@@ -31,7 +31,7 @@ impl Plugin {
|
||||
}
|
||||
}
|
||||
Plugin::Add { name: _ } => {
|
||||
log::info!("You can use `dioxus plugin app-path` to get Installation position");
|
||||
log::info!("You can use `dx plugin app-path` to get Installation position");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -1,10 +1,5 @@
|
||||
use super::*;
|
||||
use std::{
|
||||
fs::create_dir_all,
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
use std::{fs::create_dir_all, io::Write, path::PathBuf};
|
||||
|
||||
/// Run the WASM project on dev-server
|
||||
#[derive(Clone, Debug, Parser)]
|
||||
@@ -15,8 +10,8 @@ pub struct Serve {
|
||||
}
|
||||
|
||||
impl Serve {
|
||||
pub async fn serve(self) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new()?;
|
||||
pub async fn serve(self, bin: Option<PathBuf>) -> Result<()> {
|
||||
let mut crate_config = crate::CrateConfig::new(bin)?;
|
||||
|
||||
// change the relase state.
|
||||
crate_config.with_hot_reload(self.serve.hot_reload);
|
||||
@@ -39,41 +34,24 @@ impl Serve {
|
||||
// Subdirectories don't work with the server
|
||||
crate_config.dioxus_config.web.app.base_path = None;
|
||||
|
||||
let platform = self.serve.platform.unwrap_or_else(|| {
|
||||
crate_config
|
||||
.dioxus_config
|
||||
.application
|
||||
.default_platform
|
||||
.clone()
|
||||
});
|
||||
let platform = self
|
||||
.serve
|
||||
.platform
|
||||
.unwrap_or(crate_config.dioxus_config.application.default_platform);
|
||||
|
||||
if platform.as_str() == "desktop" {
|
||||
crate::builder::build_desktop(&crate_config, true)?;
|
||||
match platform {
|
||||
cfg::Platform::Web => {
|
||||
// generate dev-index page
|
||||
Serve::regen_dev_page(&crate_config)?;
|
||||
|
||||
match &crate_config.executable {
|
||||
crate::ExecutableType::Binary(name)
|
||||
| crate::ExecutableType::Lib(name)
|
||||
| crate::ExecutableType::Example(name) => {
|
||||
let mut file = crate_config.out_dir.join(name);
|
||||
if cfg!(windows) {
|
||||
file.set_extension("exe");
|
||||
}
|
||||
Command::new(file.to_str().unwrap())
|
||||
.stdout(Stdio::inherit())
|
||||
.output()?;
|
||||
}
|
||||
// start the develop server
|
||||
server::web::startup(self.serve.port, crate_config.clone(), self.serve.open)
|
||||
.await?;
|
||||
}
|
||||
cfg::Platform::Desktop => {
|
||||
server::desktop::startup(crate_config.clone()).await?;
|
||||
}
|
||||
return Ok(());
|
||||
} else if platform != "web" {
|
||||
return custom_error!("Unsupported platform target.");
|
||||
}
|
||||
|
||||
// generate dev-index page
|
||||
Serve::regen_dev_page(&crate_config)?;
|
||||
|
||||
// start the develop server
|
||||
server::startup(self.serve.port, crate_config.clone(), self.serve.open).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -130,7 +130,7 @@ fn determine_input(file: Option<String>, raw: Option<String>) -> Result<String>
|
||||
|
||||
#[test]
|
||||
fn generates_svgs() {
|
||||
let st = include_str!("../../../tests/svg.html");
|
||||
let st = include_str!("../../tests/svg.html");
|
||||
|
||||
let out = convert_html_to_formatted_rsx(&html_parser::Dom::parse(st).unwrap(), true);
|
||||
|
||||
+52
-22
@@ -1,6 +1,9 @@
|
||||
use crate::error::Result;
|
||||
use crate::{cfg::Platform, error::Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DioxusConfig {
|
||||
@@ -17,29 +20,49 @@ fn default_plugin() -> toml::Value {
|
||||
}
|
||||
|
||||
impl DioxusConfig {
|
||||
pub fn load() -> crate::error::Result<Option<DioxusConfig>> {
|
||||
let Ok(crate_dir) = crate::cargo::crate_root() else { return Ok(None); };
|
||||
pub fn load(bin: Option<PathBuf>) -> crate::error::Result<Option<DioxusConfig>> {
|
||||
let crate_dir = crate::cargo::crate_root();
|
||||
|
||||
let crate_dir = match crate_dir {
|
||||
Ok(dir) => {
|
||||
if let Some(bin) = bin {
|
||||
dir.join(bin)
|
||||
} else {
|
||||
dir
|
||||
}
|
||||
}
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let crate_dir = crate_dir.as_path();
|
||||
|
||||
// we support either `Dioxus.toml` or `Cargo.toml`
|
||||
let Some(dioxus_conf_file) = acquire_dioxus_toml(crate_dir) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let dioxus_conf_file = dioxus_conf_file.as_path();
|
||||
toml::from_str::<DioxusConfig>(&std::fs::read_to_string(dioxus_conf_file)?)
|
||||
.map_err(|_| crate::Error::Unique("Dioxus.toml parse failed".into()))
|
||||
.map_err(|err| {
|
||||
let error_location = dioxus_conf_file
|
||||
.strip_prefix(crate_dir)
|
||||
.unwrap_or(dioxus_conf_file)
|
||||
.display();
|
||||
crate::Error::Unique(format!("{error_location} {err}"))
|
||||
})
|
||||
.map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_dioxus_toml(dir: PathBuf) -> Option<PathBuf> {
|
||||
fn acquire_dioxus_toml(dir: &Path) -> Option<PathBuf> {
|
||||
// prefer uppercase
|
||||
if dir.join("Dioxus.toml").is_file() {
|
||||
return Some(dir.join("Dioxus.toml"));
|
||||
let uppercase_conf = dir.join("Dioxus.toml");
|
||||
if uppercase_conf.is_file() {
|
||||
return Some(uppercase_conf);
|
||||
}
|
||||
|
||||
// lowercase is fine too
|
||||
if dir.join("dioxus.toml").is_file() {
|
||||
return Some(dir.join("Dioxus.toml"));
|
||||
let lowercase_conf = dir.join("dioxus.toml");
|
||||
if lowercase_conf.is_file() {
|
||||
return Some(lowercase_conf);
|
||||
}
|
||||
|
||||
None
|
||||
@@ -50,7 +73,7 @@ impl Default for DioxusConfig {
|
||||
Self {
|
||||
application: ApplicationConfig {
|
||||
name: "dioxus".into(),
|
||||
default_platform: "web".to_string(),
|
||||
default_platform: Platform::Web,
|
||||
out_dir: Some(PathBuf::from("dist")),
|
||||
asset_dir: Some(PathBuf::from("public")),
|
||||
|
||||
@@ -92,7 +115,7 @@ impl Default for DioxusConfig {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApplicationConfig {
|
||||
pub name: String,
|
||||
pub default_platform: String,
|
||||
pub default_platform: Platform,
|
||||
pub out_dir: Option<PathBuf>,
|
||||
pub asset_dir: Option<PathBuf>,
|
||||
|
||||
@@ -176,14 +199,19 @@ pub enum ExecutableType {
|
||||
}
|
||||
|
||||
impl CrateConfig {
|
||||
pub fn new() -> Result<Self> {
|
||||
let dioxus_config = DioxusConfig::load()?.unwrap_or_default();
|
||||
pub fn new(bin: Option<PathBuf>) -> Result<Self> {
|
||||
let dioxus_config = DioxusConfig::load(bin.clone())?.unwrap_or_default();
|
||||
|
||||
let crate_root = crate::cargo::crate_root()?;
|
||||
|
||||
let crate_dir = if let Some(package) = &dioxus_config.application.sub_package {
|
||||
crate::cargo::crate_root()?.join(package)
|
||||
crate_root.join(package)
|
||||
} else if let Some(bin) = bin {
|
||||
crate_root.join(bin)
|
||||
} else {
|
||||
crate::cargo::crate_root()?
|
||||
crate_root
|
||||
};
|
||||
|
||||
let meta = crate::cargo::Metadata::get()?;
|
||||
let workspace_dir = meta.workspace_root;
|
||||
let target_dir = meta.target_directory;
|
||||
@@ -202,8 +230,9 @@ impl CrateConfig {
|
||||
|
||||
let manifest = cargo_toml::Manifest::from_path(cargo_def).unwrap();
|
||||
|
||||
let output_filename = {
|
||||
match &manifest.package.as_ref().unwrap().default_run {
|
||||
let mut output_filename = String::from("dioxus_app");
|
||||
if let Some(package) = &manifest.package.as_ref() {
|
||||
output_filename = match &package.default_run {
|
||||
Some(default_run_target) => default_run_target.to_owned(),
|
||||
None => manifest
|
||||
.bin
|
||||
@@ -216,9 +245,10 @@ impl CrateConfig {
|
||||
.or(manifest.bin.first())
|
||||
.or(manifest.lib.as_ref())
|
||||
.and_then(|prod| prod.name.clone())
|
||||
.expect("No executable or library found from cargo metadata."),
|
||||
}
|
||||
};
|
||||
.unwrap_or(String::from("dioxus_app")),
|
||||
};
|
||||
}
|
||||
|
||||
let executable = ExecutableType::Binary(output_filename);
|
||||
|
||||
let release = false;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use clap::Parser;
|
||||
use dioxus_cli::*;
|
||||
@@ -7,14 +9,54 @@ use dioxus_cli::plugin::PluginManager;
|
||||
|
||||
use Commands::*;
|
||||
|
||||
fn get_bin(bin: Option<String>) -> Result<Option<PathBuf>> {
|
||||
const ERR_MESSAGE: &str = "The `--bin` flag has to be ran in a Cargo workspace.";
|
||||
|
||||
if let Some(ref bin) = bin {
|
||||
let manifest = cargo_toml::Manifest::from_path("./Cargo.toml")
|
||||
.map_err(|_| Error::CargoError(ERR_MESSAGE.to_string()))?;
|
||||
|
||||
if let Some(workspace) = manifest.workspace {
|
||||
for item in workspace.members.iter() {
|
||||
let path = PathBuf::from(item);
|
||||
|
||||
if !path.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if path.ends_with(bin.clone()) {
|
||||
return Ok(Some(path));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(Error::CargoError(ERR_MESSAGE.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// If the bin exists but we couldn't find it
|
||||
if bin.is_some() {
|
||||
return Err(Error::CargoError(
|
||||
"The specified bin does not exist.".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = Cli::parse();
|
||||
|
||||
set_up_logging();
|
||||
|
||||
let _dioxus_config = DioxusConfig::load()
|
||||
.map_err(|e| anyhow!("Failed to load `Dioxus.toml` because: {e}"))?
|
||||
let bin = get_bin(args.bin)?;
|
||||
|
||||
let _dioxus_config = DioxusConfig::load(bin.clone())
|
||||
.map_err(|e| anyhow!("Failed to load Dioxus config because: {e}"))?
|
||||
.unwrap_or_else(|| {
|
||||
log::warn!("You appear to be creating a Dioxus project from scratch; we will use the default config");
|
||||
DioxusConfig::default()
|
||||
@@ -30,15 +72,15 @@ async fn main() -> anyhow::Result<()> {
|
||||
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
|
||||
|
||||
Build(opts) => opts
|
||||
.build()
|
||||
.build(bin.clone())
|
||||
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
|
||||
|
||||
Clean(opts) => opts
|
||||
.clean()
|
||||
.clean(bin.clone())
|
||||
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
|
||||
|
||||
Serve(opts) => opts
|
||||
.serve()
|
||||
.serve(bin.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
use crate::{
|
||||
server::{
|
||||
output::{print_console_info, PrettierOptions},
|
||||
setup_file_watcher, setup_file_watcher_hot_reload,
|
||||
},
|
||||
BuildResult, CrateConfig, Result,
|
||||
};
|
||||
|
||||
use dioxus_hot_reload::HotReloadMsg;
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::*;
|
||||
use interprocess_docfix::local_socket::LocalSocketListener;
|
||||
use std::{
|
||||
process::{Child, Command},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
};
|
||||
use tokio::sync::broadcast::{self};
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
use plugin::PluginManager;
|
||||
|
||||
pub async fn startup(config: CrateConfig) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
let _ = ctrlc::set_handler(move || {
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_serve_shutdown(&_crate_config);
|
||||
std::process::exit(0);
|
||||
});
|
||||
|
||||
match config.hot_reload {
|
||||
true => serve_hot_reload(config).await?,
|
||||
false => serve_default(config).await?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve_default(config: CrateConfig) -> Result<()> {
|
||||
let (child, first_build_result) = start_desktop(&config)?;
|
||||
let currently_running_child: RwLock<Child> = RwLock::new(child);
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise full reload won't work.
|
||||
let _watcher = setup_file_watcher(
|
||||
{
|
||||
let config = config.clone();
|
||||
|
||||
move || {
|
||||
let mut current_child = currently_running_child.write().unwrap();
|
||||
current_child.kill()?;
|
||||
let (child, result) = start_desktop(&config)?;
|
||||
*current_child = child;
|
||||
Ok(result)
|
||||
}
|
||||
},
|
||||
&config,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
std::future::pending::<()>().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
|
||||
/// Start dx serve with hot reload
|
||||
pub async fn serve_hot_reload(config: CrateConfig) -> Result<()> {
|
||||
let (_, first_build_result) = start_desktop(&config)?;
|
||||
|
||||
println!("🚀 Starting development server...");
|
||||
|
||||
// Setup hot reload
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
println!("🚀 Starting development server...");
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let (hot_reload_tx, mut hot_reload_rx) = broadcast::channel(100);
|
||||
|
||||
// States
|
||||
// The open interprocess sockets
|
||||
let channels = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
// Setup file watcher
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise hot reload won't work.
|
||||
let _watcher = setup_file_watcher_hot_reload(
|
||||
&config,
|
||||
hot_reload_tx,
|
||||
file_map.clone(),
|
||||
{
|
||||
let config = config.clone();
|
||||
|
||||
let channels = channels.clone();
|
||||
move || {
|
||||
for channel in &mut *channels.lock().unwrap() {
|
||||
send_msg(HotReloadMsg::Shutdown, channel);
|
||||
}
|
||||
Ok(start_desktop(&config)?.1)
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
clear_paths();
|
||||
|
||||
match LocalSocketListener::bind("@dioxusin") {
|
||||
Ok(local_socket_stream) => {
|
||||
let aborted = Arc::new(Mutex::new(false));
|
||||
|
||||
// listen for connections
|
||||
std::thread::spawn({
|
||||
let file_map = file_map.clone();
|
||||
let channels = channels.clone();
|
||||
let aborted = aborted.clone();
|
||||
let _ = local_socket_stream.set_nonblocking(true);
|
||||
move || {
|
||||
loop {
|
||||
if let Ok(mut connection) = local_socket_stream.accept() {
|
||||
// send any templates than have changed before the socket connected
|
||||
let templates: Vec<_> = {
|
||||
file_map
|
||||
.lock()
|
||||
.unwrap()
|
||||
.map
|
||||
.values()
|
||||
.filter_map(|(_, template_slot)| *template_slot)
|
||||
.collect()
|
||||
};
|
||||
for template in templates {
|
||||
if !send_msg(
|
||||
HotReloadMsg::UpdateTemplate(template),
|
||||
&mut connection,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
channels.lock().unwrap().push(connection);
|
||||
println!("Connected to hot reloading 🚀");
|
||||
}
|
||||
if *aborted.lock().unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
while let Ok(template) = hot_reload_rx.recv().await {
|
||||
let channels = &mut *channels.lock().unwrap();
|
||||
let mut i = 0;
|
||||
while i < channels.len() {
|
||||
let channel = &mut channels[i];
|
||||
if send_msg(HotReloadMsg::UpdateTemplate(template), channel) {
|
||||
i += 1;
|
||||
} else {
|
||||
channels.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => println!("failed to connect to hot reloading\n{error}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_paths() {
|
||||
if cfg!(target_os = "macos") {
|
||||
// On unix, if you force quit the application, it can leave the file socket open
|
||||
// This will cause the local socket listener to fail to open
|
||||
// We check if the file socket is already open from an old session and then delete it
|
||||
let paths = ["./dioxusin", "./@dioxusin"];
|
||||
for path in paths {
|
||||
let path = std::path::PathBuf::from(path);
|
||||
if path.exists() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
|
||||
if let Ok(msg) = serde_json::to_string(&msg) {
|
||||
if channel.write_all(msg.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
if channel.write_all(&[b'\n']).is_err() {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
|
||||
// Run the desktop application
|
||||
let result = crate::builder::build_desktop(config, true)?;
|
||||
|
||||
match &config.executable {
|
||||
crate::ExecutableType::Binary(name)
|
||||
| crate::ExecutableType::Lib(name)
|
||||
| crate::ExecutableType::Example(name) => {
|
||||
let mut file = config.out_dir.join(name);
|
||||
if cfg!(windows) {
|
||||
file.set_extension("exe");
|
||||
}
|
||||
let child = Command::new(file.to_str().unwrap()).spawn()?;
|
||||
|
||||
Ok((child, result))
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-490
@@ -1,449 +1,27 @@
|
||||
use crate::{builder, serve::Serve, BuildResult, CrateConfig, Result};
|
||||
use axum::{
|
||||
body::{Full, HttpBody},
|
||||
extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade},
|
||||
http::{
|
||||
header::{HeaderName, HeaderValue},
|
||||
Method, Response, StatusCode,
|
||||
},
|
||||
response::IntoResponse,
|
||||
routing::{get, get_service},
|
||||
Router,
|
||||
};
|
||||
use axum_server::tls_rustls::RustlsConfig;
|
||||
use crate::{BuildResult, CrateConfig, Result};
|
||||
|
||||
use cargo_metadata::diagnostic::Diagnostic;
|
||||
use dioxus_core::Template;
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::*;
|
||||
use notify::{RecommendedWatcher, Watcher};
|
||||
use std::{
|
||||
net::UdpSocket,
|
||||
path::PathBuf,
|
||||
process::Command,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::sync::broadcast::{self, Sender};
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::services::fs::{ServeDir, ServeFileSystemResponseBody};
|
||||
use tower_http::{
|
||||
cors::{Any, CorsLayer},
|
||||
ServiceBuilderExt,
|
||||
};
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
use plugin::PluginManager;
|
||||
|
||||
mod proxy;
|
||||
|
||||
mod hot_reload;
|
||||
use hot_reload::*;
|
||||
use tokio::sync::broadcast::Sender;
|
||||
|
||||
mod output;
|
||||
use output::*;
|
||||
|
||||
pub struct BuildManager {
|
||||
config: CrateConfig,
|
||||
reload_tx: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
impl BuildManager {
|
||||
fn rebuild(&self) -> Result<BuildResult> {
|
||||
log::info!("🪁 Rebuild project");
|
||||
let result = builder::build(&self.config, true)?;
|
||||
// change the websocket reload state to true;
|
||||
// the page will auto-reload.
|
||||
if self
|
||||
.config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.reload_html
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let _ = Serve::regen_dev_page(&self.config);
|
||||
}
|
||||
let _ = self.reload_tx.send(());
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
struct WsReloadState {
|
||||
update: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
let _ = ctrlc::set_handler(move || {
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_serve_shutdown(&_crate_config);
|
||||
std::process::exit(0);
|
||||
});
|
||||
|
||||
let ip = get_ip().unwrap_or(String::from("0.0.0.0"));
|
||||
|
||||
match config.hot_reload {
|
||||
true => serve_hot_reload(ip, port, config, start_browser).await?,
|
||||
false => serve_default(ip, port, config, start_browser).await?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve_default(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// WS Reload Watching
|
||||
let (reload_tx, _) = broadcast::channel(100);
|
||||
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise full reload won't work.
|
||||
let _watcher = setup_file_watcher(&config, port, ip.clone(), reload_tx.clone()).await?;
|
||||
|
||||
let ws_reload_state = Arc::new(WsReloadState {
|
||||
update: reload_tx.clone(),
|
||||
});
|
||||
|
||||
// HTTPS
|
||||
// Before console info so it can stop if mkcert isn't installed or fails
|
||||
let rustls_config = get_rustls(&config).await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&ip,
|
||||
port,
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, None).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start dx serve with hot reload
|
||||
pub async fn serve_hot_reload(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// Setup hot reload
|
||||
let (reload_tx, _) = broadcast::channel(100);
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
let build_manager = Arc::new(BuildManager {
|
||||
config: config.clone(),
|
||||
reload_tx: reload_tx.clone(),
|
||||
});
|
||||
|
||||
let hot_reload_tx = broadcast::channel(100).0;
|
||||
|
||||
// States
|
||||
let hot_reload_state = Arc::new(HotReloadState {
|
||||
messages: hot_reload_tx.clone(),
|
||||
build_manager: build_manager.clone(),
|
||||
file_map: file_map.clone(),
|
||||
watcher_config: config.clone(),
|
||||
});
|
||||
|
||||
let ws_reload_state = Arc::new(WsReloadState {
|
||||
update: reload_tx.clone(),
|
||||
});
|
||||
|
||||
// Setup file watcher
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise hot reload won't work.
|
||||
let _watcher = setup_file_watcher_hot_reload(
|
||||
&config,
|
||||
port,
|
||||
ip.clone(),
|
||||
hot_reload_tx,
|
||||
file_map,
|
||||
build_manager,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// HTTPS
|
||||
// Before console info so it can stop if mkcert isn't installed or fails
|
||||
let rustls_config = get_rustls(&config).await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&ip,
|
||||
port,
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEFAULT_KEY_PATH: &str = "ssl/key.pem";
|
||||
const DEFAULT_CERT_PATH: &str = "ssl/cert.pem";
|
||||
|
||||
/// Returns an enum of rustls config and a bool if mkcert isn't installed
|
||||
async fn get_rustls(config: &CrateConfig) -> Result<Option<RustlsConfig>> {
|
||||
let web_config = &config.dioxus_config.web.https;
|
||||
if web_config.enabled != Some(true) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let (cert_path, key_path) = match web_config.mkcert {
|
||||
// mkcert, use it
|
||||
Some(true) => {
|
||||
// Get paths to store certs, otherwise use ssl/item.pem
|
||||
let key_path = web_config
|
||||
.key_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_KEY_PATH.to_string());
|
||||
|
||||
let cert_path = web_config
|
||||
.cert_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_CERT_PATH.to_string());
|
||||
|
||||
// Create ssl directory if using defaults
|
||||
if key_path == DEFAULT_KEY_PATH && cert_path == DEFAULT_CERT_PATH {
|
||||
_ = fs::create_dir("ssl");
|
||||
}
|
||||
|
||||
let cmd = Command::new("mkcert")
|
||||
.args([
|
||||
"-install",
|
||||
"-key-file",
|
||||
&key_path,
|
||||
"-cert-file",
|
||||
&cert_path,
|
||||
"localhost",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
])
|
||||
.spawn();
|
||||
|
||||
match cmd {
|
||||
Err(e) => {
|
||||
match e.kind() {
|
||||
io::ErrorKind::NotFound => log::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
|
||||
e => log::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
|
||||
};
|
||||
return Err("failed to generate mkcert certificates".into());
|
||||
}
|
||||
Ok(mut cmd) => {
|
||||
cmd.wait()?;
|
||||
}
|
||||
}
|
||||
|
||||
(cert_path, key_path)
|
||||
}
|
||||
// not mkcert
|
||||
Some(false) => {
|
||||
// get paths to cert & key
|
||||
if let (Some(key), Some(cert)) =
|
||||
(web_config.key_path.clone(), web_config.cert_path.clone())
|
||||
{
|
||||
(cert, key)
|
||||
} else {
|
||||
// missing cert or key
|
||||
return Err("https is enabled but cert or key path is missing".into());
|
||||
}
|
||||
}
|
||||
// other
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
Ok(Some(
|
||||
RustlsConfig::from_pem_file(cert_path, key_path).await?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Sets up and returns a router
|
||||
async fn setup_router(
|
||||
config: CrateConfig,
|
||||
ws_reload: Arc<WsReloadState>,
|
||||
hot_reload: Option<Arc<HotReloadState>>,
|
||||
) -> Result<Router> {
|
||||
// Setup cors
|
||||
let cors = CorsLayer::new()
|
||||
// allow `GET` and `POST` when accessing the resource
|
||||
.allow_methods([Method::GET, Method::POST])
|
||||
// allow requests from any origin
|
||||
.allow_origin(Any)
|
||||
.allow_headers(Any);
|
||||
|
||||
let (coep, coop) = if config.cross_origin_policy {
|
||||
(
|
||||
HeaderValue::from_static("require-corp"),
|
||||
HeaderValue::from_static("same-origin"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
HeaderValue::from_static("unsafe-none"),
|
||||
HeaderValue::from_static("unsafe-none"),
|
||||
)
|
||||
};
|
||||
|
||||
// Create file service
|
||||
let file_service_config = config.clone();
|
||||
let file_service = ServiceBuilder::new()
|
||||
.override_response_header(
|
||||
HeaderName::from_static("cross-origin-embedder-policy"),
|
||||
coep,
|
||||
)
|
||||
.override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop)
|
||||
.and_then(
|
||||
move |response: Response<ServeFileSystemResponseBody>| async move {
|
||||
let response = if file_service_config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.index_on_404
|
||||
.unwrap_or(false)
|
||||
&& response.status() == StatusCode::NOT_FOUND
|
||||
{
|
||||
let body = Full::from(
|
||||
// TODO: Cache/memoize this.
|
||||
std::fs::read_to_string(
|
||||
file_service_config
|
||||
.crate_dir
|
||||
.join(file_service_config.out_dir)
|
||||
.join("index.html"),
|
||||
)
|
||||
.ok()
|
||||
.unwrap(),
|
||||
)
|
||||
.map_err(|err| match err {})
|
||||
.boxed();
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.body(body)
|
||||
.unwrap()
|
||||
} else {
|
||||
response.map(|body| body.boxed())
|
||||
};
|
||||
Ok(response)
|
||||
},
|
||||
)
|
||||
.service(ServeDir::new(config.crate_dir.join(&config.out_dir)));
|
||||
|
||||
// Setup websocket
|
||||
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
|
||||
|
||||
// Setup proxy
|
||||
for proxy_config in config.dioxus_config.web.proxy.unwrap_or_default() {
|
||||
router = proxy::add_proxy(router, &proxy_config)?;
|
||||
}
|
||||
|
||||
// Route file service
|
||||
router = router.fallback(get_service(file_service).handle_error(
|
||||
|error: std::io::Error| async move {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
)
|
||||
},
|
||||
));
|
||||
|
||||
// Setup routes
|
||||
router = router
|
||||
.route("/_dioxus/hot_reload", get(hot_reload_handler))
|
||||
.layer(cors)
|
||||
.layer(Extension(ws_reload));
|
||||
|
||||
if let Some(hot_reload) = hot_reload {
|
||||
router = router.layer(Extension(hot_reload))
|
||||
}
|
||||
|
||||
Ok(router)
|
||||
}
|
||||
|
||||
/// Starts dx serve with no hot reload
|
||||
async fn start_server(
|
||||
port: u16,
|
||||
router: Router,
|
||||
start_browser: bool,
|
||||
rustls: Option<RustlsConfig>,
|
||||
) -> Result<()> {
|
||||
// If plugins, call on_serve_start event
|
||||
#[cfg(feature = "plugin")]
|
||||
PluginManager::on_serve_start(&config)?;
|
||||
|
||||
// Parse address
|
||||
let addr = format!("0.0.0.0:{}", port).parse().unwrap();
|
||||
|
||||
// Open the browser
|
||||
if start_browser {
|
||||
match rustls {
|
||||
Some(_) => _ = open::that(format!("https://{}", addr)),
|
||||
None => _ = open::that(format!("http://{}", addr)),
|
||||
}
|
||||
}
|
||||
|
||||
// Start the server with or without rustls
|
||||
match rustls {
|
||||
Some(rustls) => {
|
||||
axum_server::bind_rustls(addr, rustls)
|
||||
.serve(router.into_make_service())
|
||||
.await?
|
||||
}
|
||||
None => {
|
||||
axum::Server::bind(&addr)
|
||||
.serve(router.into_make_service())
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub mod desktop;
|
||||
pub mod web;
|
||||
|
||||
/// Sets up a file watcher
|
||||
async fn setup_file_watcher(
|
||||
async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
build_with: F,
|
||||
config: &CrateConfig,
|
||||
port: u16,
|
||||
watcher_ip: String,
|
||||
reload_tx: Sender<()>,
|
||||
web_info: Option<WebServerInfo>,
|
||||
) -> Result<RecommendedWatcher> {
|
||||
let build_manager = BuildManager {
|
||||
config: config.clone(),
|
||||
reload_tx,
|
||||
};
|
||||
|
||||
let mut last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
// file watcher: check file change
|
||||
@@ -460,20 +38,19 @@ async fn setup_file_watcher(
|
||||
let config = watcher_config.clone();
|
||||
if let Ok(e) = info {
|
||||
if chrono::Local::now().timestamp() > last_update_time {
|
||||
match build_manager.rebuild() {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
#[allow(clippy::redundant_clone)]
|
||||
print_console_info(
|
||||
&watcher_ip,
|
||||
port,
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: e.paths.clone(),
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
@@ -502,13 +79,12 @@ async fn setup_file_watcher(
|
||||
|
||||
// Todo: reduce duplication and merge with setup_file_watcher()
|
||||
/// Sets up a file watcher with hot reload
|
||||
async fn setup_file_watcher_hot_reload(
|
||||
async fn setup_file_watcher_hot_reload<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
config: &CrateConfig,
|
||||
port: u16,
|
||||
watcher_ip: String,
|
||||
hot_reload_tx: Sender<Template<'static>>,
|
||||
file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
|
||||
build_manager: Arc<BuildManager>,
|
||||
build_with: F,
|
||||
web_info: Option<WebServerInfo>,
|
||||
) -> Result<RecommendedWatcher> {
|
||||
// file watcher: check file change
|
||||
let allow_watch_path = config
|
||||
@@ -533,17 +109,16 @@ async fn setup_file_watcher_hot_reload(
|
||||
for path in evt.paths.clone() {
|
||||
// if this is not a rust file, rebuild the whole project
|
||||
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
|
||||
match build_manager.rebuild() {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
print_console_info(
|
||||
&watcher_ip,
|
||||
port,
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: evt.paths,
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -560,17 +135,16 @@ async fn setup_file_watcher_hot_reload(
|
||||
messages.extend(msgs);
|
||||
}
|
||||
Ok(UpdateResult::NeedsRebuild) => {
|
||||
match build_manager.rebuild() {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
print_console_info(
|
||||
&watcher_ip,
|
||||
port,
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: evt.paths,
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -606,50 +180,3 @@ async fn setup_file_watcher_hot_reload(
|
||||
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
/// Get the network ip
|
||||
fn get_ip() -> Option<String> {
|
||||
let socket = match UdpSocket::bind("0.0.0.0:0") {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
match socket.connect("8.8.8.8:80") {
|
||||
Ok(()) => (),
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
match socket.local_addr() {
|
||||
Ok(addr) => Some(addr.ip().to_string()),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle websockets
|
||||
async fn ws_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
_: Option<TypedHeader<headers::UserAgent>>,
|
||||
Extension(state): Extension<Arc<WsReloadState>>,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(|mut socket| async move {
|
||||
let mut rx = state.update.subscribe();
|
||||
let reload_watcher = tokio::spawn(async move {
|
||||
loop {
|
||||
rx.recv().await.unwrap();
|
||||
// ignore the error
|
||||
if socket
|
||||
.send(Message::Text(String::from("reload")))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// flush the errors after recompling
|
||||
rx = rx.resubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
reload_watcher.await.unwrap();
|
||||
})
|
||||
}
|
||||
@@ -11,7 +11,17 @@ pub struct PrettierOptions {
|
||||
pub elapsed_time: u128,
|
||||
}
|
||||
|
||||
pub fn print_console_info(ip: &String, port: u16, config: &CrateConfig, options: PrettierOptions) {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WebServerInfo {
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
pub fn print_console_info(
|
||||
config: &CrateConfig,
|
||||
options: PrettierOptions,
|
||||
web_info: Option<WebServerInfo>,
|
||||
) {
|
||||
if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") {
|
||||
"cls"
|
||||
} else {
|
||||
@@ -70,26 +80,28 @@ pub fn print_console_info(ip: &String, port: u16, config: &CrateConfig, options:
|
||||
);
|
||||
}
|
||||
|
||||
if config.dioxus_config.web.https.enabled == Some(true) {
|
||||
println!(
|
||||
"\t> Local : {}",
|
||||
format!("https://localhost:{}/", port).blue()
|
||||
);
|
||||
println!(
|
||||
"\t> Network : {}",
|
||||
format!("https://{}:{}/", ip, port).blue()
|
||||
);
|
||||
println!("\t> HTTPS : {}", "Enabled".to_string().green());
|
||||
} else {
|
||||
println!(
|
||||
"\t> Local : {}",
|
||||
format!("http://localhost:{}/", port).blue()
|
||||
);
|
||||
println!(
|
||||
"\t> Network : {}",
|
||||
format!("http://{}:{}/", ip, port).blue()
|
||||
);
|
||||
println!("\t> HTTPS : {}", "Disabled".to_string().red());
|
||||
if let Some(WebServerInfo { ip, port }) = web_info {
|
||||
if config.dioxus_config.web.https.enabled == Some(true) {
|
||||
println!(
|
||||
"\t> Local : {}",
|
||||
format!("https://localhost:{}/", port).blue()
|
||||
);
|
||||
println!(
|
||||
"\t> Network : {}",
|
||||
format!("https://{}:{}/", ip, port).blue()
|
||||
);
|
||||
println!("\t> HTTPS : {}", "Enabled".to_string().green());
|
||||
} else {
|
||||
println!(
|
||||
"\t> Local : {}",
|
||||
format!("http://localhost:{}/", port).blue()
|
||||
);
|
||||
println!(
|
||||
"\t> Network : {}",
|
||||
format!("http://{}:{}/", ip, port).blue()
|
||||
);
|
||||
println!("\t> HTTPS : {}", "Disabled".to_string().red());
|
||||
}
|
||||
}
|
||||
println!();
|
||||
println!("\t> Profile : {}", profile.green());
|
||||
|
||||
@@ -10,12 +10,10 @@ use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::FileMap;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use super::BuildManager;
|
||||
use crate::CrateConfig;
|
||||
|
||||
pub struct HotReloadState {
|
||||
pub messages: broadcast::Sender<Template<'static>>,
|
||||
pub build_manager: Arc<BuildManager>,
|
||||
pub file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
|
||||
pub watcher_config: CrateConfig,
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
use crate::{
|
||||
builder,
|
||||
serve::Serve,
|
||||
server::{
|
||||
output::{print_console_info, PrettierOptions, WebServerInfo},
|
||||
setup_file_watcher, setup_file_watcher_hot_reload,
|
||||
},
|
||||
BuildResult, CrateConfig, Result,
|
||||
};
|
||||
use axum::{
|
||||
body::{Full, HttpBody},
|
||||
extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade},
|
||||
http::{
|
||||
header::{HeaderName, HeaderValue},
|
||||
Method, Response, StatusCode,
|
||||
},
|
||||
response::IntoResponse,
|
||||
routing::{get, get_service},
|
||||
Router,
|
||||
};
|
||||
use axum_server::tls_rustls::RustlsConfig;
|
||||
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::*;
|
||||
use std::{
|
||||
net::UdpSocket,
|
||||
process::Command,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::sync::broadcast::{self, Sender};
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::services::fs::{ServeDir, ServeFileSystemResponseBody};
|
||||
use tower_http::{
|
||||
cors::{Any, CorsLayer},
|
||||
ServiceBuilderExt,
|
||||
};
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
use plugin::PluginManager;
|
||||
|
||||
mod proxy;
|
||||
|
||||
mod hot_reload;
|
||||
use hot_reload::*;
|
||||
|
||||
struct WsReloadState {
|
||||
update: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
let _ = ctrlc::set_handler(move || {
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_serve_shutdown(&_crate_config);
|
||||
std::process::exit(0);
|
||||
});
|
||||
|
||||
let ip = get_ip().unwrap_or(String::from("0.0.0.0"));
|
||||
|
||||
match config.hot_reload {
|
||||
true => serve_hot_reload(ip, port, config, start_browser).await?,
|
||||
false => serve_default(ip, port, config, start_browser).await?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve_default(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// WS Reload Watching
|
||||
let (reload_tx, _) = broadcast::channel(100);
|
||||
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise full reload won't work.
|
||||
let _watcher = setup_file_watcher(
|
||||
{
|
||||
let config = config.clone();
|
||||
let reload_tx = reload_tx.clone();
|
||||
move || build(&config, &reload_tx)
|
||||
},
|
||||
&config,
|
||||
Some(WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let ws_reload_state = Arc::new(WsReloadState {
|
||||
update: reload_tx.clone(),
|
||||
});
|
||||
|
||||
// HTTPS
|
||||
// Before console info so it can stop if mkcert isn't installed or fails
|
||||
let rustls_config = get_rustls(&config).await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
Some(crate::server::output::WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, None).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start dx serve with hot reload
|
||||
pub async fn serve_hot_reload(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// Setup hot reload
|
||||
let (reload_tx, _) = broadcast::channel(100);
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let hot_reload_tx = broadcast::channel(100).0;
|
||||
|
||||
// States
|
||||
let hot_reload_state = Arc::new(HotReloadState {
|
||||
messages: hot_reload_tx.clone(),
|
||||
file_map: file_map.clone(),
|
||||
watcher_config: config.clone(),
|
||||
});
|
||||
|
||||
let ws_reload_state = Arc::new(WsReloadState {
|
||||
update: reload_tx.clone(),
|
||||
});
|
||||
|
||||
// Setup file watcher
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise hot reload won't work.
|
||||
let _watcher = setup_file_watcher_hot_reload(
|
||||
&config,
|
||||
hot_reload_tx,
|
||||
file_map,
|
||||
{
|
||||
let config = config.clone();
|
||||
let reload_tx = reload_tx.clone();
|
||||
move || build(&config, &reload_tx)
|
||||
},
|
||||
Some(WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// HTTPS
|
||||
// Before console info so it can stop if mkcert isn't installed or fails
|
||||
let rustls_config = get_rustls(&config).await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
Some(WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEFAULT_KEY_PATH: &str = "ssl/key.pem";
|
||||
const DEFAULT_CERT_PATH: &str = "ssl/cert.pem";
|
||||
|
||||
/// Returns an enum of rustls config and a bool if mkcert isn't installed
|
||||
async fn get_rustls(config: &CrateConfig) -> Result<Option<RustlsConfig>> {
|
||||
let web_config = &config.dioxus_config.web.https;
|
||||
if web_config.enabled != Some(true) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let (cert_path, key_path) = match web_config.mkcert {
|
||||
// mkcert, use it
|
||||
Some(true) => {
|
||||
// Get paths to store certs, otherwise use ssl/item.pem
|
||||
let key_path = web_config
|
||||
.key_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_KEY_PATH.to_string());
|
||||
|
||||
let cert_path = web_config
|
||||
.cert_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_CERT_PATH.to_string());
|
||||
|
||||
// Create ssl directory if using defaults
|
||||
if key_path == DEFAULT_KEY_PATH && cert_path == DEFAULT_CERT_PATH {
|
||||
_ = fs::create_dir("ssl");
|
||||
}
|
||||
|
||||
let cmd = Command::new("mkcert")
|
||||
.args([
|
||||
"-install",
|
||||
"-key-file",
|
||||
&key_path,
|
||||
"-cert-file",
|
||||
&cert_path,
|
||||
"localhost",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
])
|
||||
.spawn();
|
||||
|
||||
match cmd {
|
||||
Err(e) => {
|
||||
match e.kind() {
|
||||
io::ErrorKind::NotFound => log::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
|
||||
e => log::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
|
||||
};
|
||||
return Err("failed to generate mkcert certificates".into());
|
||||
}
|
||||
Ok(mut cmd) => {
|
||||
cmd.wait()?;
|
||||
}
|
||||
}
|
||||
|
||||
(cert_path, key_path)
|
||||
}
|
||||
// not mkcert
|
||||
Some(false) => {
|
||||
// get paths to cert & key
|
||||
if let (Some(key), Some(cert)) =
|
||||
(web_config.key_path.clone(), web_config.cert_path.clone())
|
||||
{
|
||||
(cert, key)
|
||||
} else {
|
||||
// missing cert or key
|
||||
return Err("https is enabled but cert or key path is missing".into());
|
||||
}
|
||||
}
|
||||
// other
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
Ok(Some(
|
||||
RustlsConfig::from_pem_file(cert_path, key_path).await?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Sets up and returns a router
|
||||
async fn setup_router(
|
||||
config: CrateConfig,
|
||||
ws_reload: Arc<WsReloadState>,
|
||||
hot_reload: Option<Arc<HotReloadState>>,
|
||||
) -> Result<Router> {
|
||||
// Setup cors
|
||||
let cors = CorsLayer::new()
|
||||
// allow `GET` and `POST` when accessing the resource
|
||||
.allow_methods([Method::GET, Method::POST])
|
||||
// allow requests from any origin
|
||||
.allow_origin(Any)
|
||||
.allow_headers(Any);
|
||||
|
||||
let (coep, coop) = if config.cross_origin_policy {
|
||||
(
|
||||
HeaderValue::from_static("require-corp"),
|
||||
HeaderValue::from_static("same-origin"),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
HeaderValue::from_static("unsafe-none"),
|
||||
HeaderValue::from_static("unsafe-none"),
|
||||
)
|
||||
};
|
||||
|
||||
// Create file service
|
||||
let file_service_config = config.clone();
|
||||
let file_service = ServiceBuilder::new()
|
||||
.override_response_header(
|
||||
HeaderName::from_static("cross-origin-embedder-policy"),
|
||||
coep,
|
||||
)
|
||||
.override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop)
|
||||
.and_then(
|
||||
move |response: Response<ServeFileSystemResponseBody>| async move {
|
||||
let response = if file_service_config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.index_on_404
|
||||
.unwrap_or(false)
|
||||
&& response.status() == StatusCode::NOT_FOUND
|
||||
{
|
||||
let body = Full::from(
|
||||
// TODO: Cache/memoize this.
|
||||
std::fs::read_to_string(
|
||||
file_service_config
|
||||
.crate_dir
|
||||
.join(file_service_config.out_dir)
|
||||
.join("index.html"),
|
||||
)
|
||||
.ok()
|
||||
.unwrap(),
|
||||
)
|
||||
.map_err(|err| match err {})
|
||||
.boxed();
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.body(body)
|
||||
.unwrap()
|
||||
} else {
|
||||
response.map(|body| body.boxed())
|
||||
};
|
||||
Ok(response)
|
||||
},
|
||||
)
|
||||
.service(ServeDir::new(config.crate_dir.join(&config.out_dir)));
|
||||
|
||||
// Setup websocket
|
||||
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
|
||||
|
||||
// Setup proxy
|
||||
for proxy_config in config.dioxus_config.web.proxy.unwrap_or_default() {
|
||||
router = proxy::add_proxy(router, &proxy_config)?;
|
||||
}
|
||||
|
||||
// Route file service
|
||||
router = router.fallback(get_service(file_service).handle_error(
|
||||
|error: std::io::Error| async move {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
)
|
||||
},
|
||||
));
|
||||
|
||||
// Setup routes
|
||||
router = router
|
||||
.route("/_dioxus/hot_reload", get(hot_reload_handler))
|
||||
.layer(cors)
|
||||
.layer(Extension(ws_reload));
|
||||
|
||||
if let Some(hot_reload) = hot_reload {
|
||||
router = router.layer(Extension(hot_reload))
|
||||
}
|
||||
|
||||
Ok(router)
|
||||
}
|
||||
|
||||
/// Starts dx serve with no hot reload
|
||||
async fn start_server(
|
||||
port: u16,
|
||||
router: Router,
|
||||
start_browser: bool,
|
||||
rustls: Option<RustlsConfig>,
|
||||
) -> Result<()> {
|
||||
// If plugins, call on_serve_start event
|
||||
#[cfg(feature = "plugin")]
|
||||
PluginManager::on_serve_start(&config)?;
|
||||
|
||||
// Parse address
|
||||
let addr = format!("0.0.0.0:{}", port).parse().unwrap();
|
||||
|
||||
// Open the browser
|
||||
if start_browser {
|
||||
match rustls {
|
||||
Some(_) => _ = open::that(format!("https://{}", addr)),
|
||||
None => _ = open::that(format!("http://{}", addr)),
|
||||
}
|
||||
}
|
||||
|
||||
// Start the server with or without rustls
|
||||
match rustls {
|
||||
Some(rustls) => {
|
||||
axum_server::bind_rustls(addr, rustls)
|
||||
.serve(router.into_make_service())
|
||||
.await?
|
||||
}
|
||||
None => {
|
||||
axum::Server::bind(&addr)
|
||||
.serve(router.into_make_service())
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the network ip
|
||||
fn get_ip() -> Option<String> {
|
||||
let socket = match UdpSocket::bind("0.0.0.0:0") {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
match socket.connect("8.8.8.8:80") {
|
||||
Ok(()) => (),
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
match socket.local_addr() {
|
||||
Ok(addr) => Some(addr.ip().to_string()),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle websockets
|
||||
async fn ws_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
_: Option<TypedHeader<headers::UserAgent>>,
|
||||
Extension(state): Extension<Arc<WsReloadState>>,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(|mut socket| async move {
|
||||
let mut rx = state.update.subscribe();
|
||||
let reload_watcher = tokio::spawn(async move {
|
||||
loop {
|
||||
rx.recv().await.unwrap();
|
||||
// ignore the error
|
||||
if socket
|
||||
.send(Message::Text(String::from("reload")))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// flush the errors after recompling
|
||||
rx = rx.resubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
reload_watcher.await.unwrap();
|
||||
})
|
||||
}
|
||||
|
||||
fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
|
||||
let result = builder::build(config, true)?;
|
||||
// change the websocket reload state to true;
|
||||
// the page will auto-reload.
|
||||
if config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.reload_html
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let _ = Serve::regen_dev_page(config);
|
||||
}
|
||||
let _ = reload_tx.send(());
|
||||
Ok(result)
|
||||
}
|
||||
File renamed without changes.
@@ -4,7 +4,7 @@ version = "0.3.0"
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2021"
|
||||
description = "Core macro for Dioxus Virtual DOM"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com"
|
||||
keywords = ["dom", "ui", "gui", "react"]
|
||||
@@ -15,7 +15,7 @@ proc-macro = true
|
||||
[dependencies]
|
||||
proc-macro2 = { version = "1.0" }
|
||||
quote = "1.0"
|
||||
syn = { version = "1.0", features = ["full", "extra-traits"] }
|
||||
syn = { version = "2.0", features = ["full", "extra-traits"] }
|
||||
dioxus-rsx = { workspace = true }
|
||||
|
||||
# testing
|
||||
|
||||
@@ -135,7 +135,7 @@ impl ToTokens for InlinePropsBody {
|
||||
quote! { <#struct_generics> },
|
||||
)
|
||||
} else {
|
||||
let lifetime: LifetimeDef = parse_quote! { 'a };
|
||||
let lifetime: LifetimeParam = parse_quote! { 'a };
|
||||
|
||||
let mut fn_generics = generics.clone();
|
||||
fn_generics
|
||||
|
||||
@@ -166,8 +166,9 @@ mod field_info {
|
||||
use crate::props::type_from_inside_option;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::parse::Error;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::Expr;
|
||||
use syn::{parse::Error, punctuated::Punctuated};
|
||||
|
||||
use super::util::{
|
||||
expr_to_single_string, ident_to_type, path_to_single_string, strip_raw_ident_prefix,
|
||||
@@ -260,31 +261,32 @@ mod field_info {
|
||||
pub fn with(mut self, attrs: &[syn::Attribute]) -> Result<Self, Error> {
|
||||
let mut skip_tokens = None;
|
||||
for attr in attrs {
|
||||
if path_to_single_string(&attr.path).as_deref() != Some("props") {
|
||||
if path_to_single_string(attr.path()).as_deref() != Some("props") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if attr.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let as_expr: syn::Expr = syn::parse2(attr.tokens.clone())?;
|
||||
match as_expr {
|
||||
syn::Expr::Paren(body) => {
|
||||
self.apply_meta(*body.expr)?;
|
||||
}
|
||||
syn::Expr::Tuple(body) => {
|
||||
for expr in body.elems.into_iter() {
|
||||
self.apply_meta(expr)?;
|
||||
match &attr.meta {
|
||||
syn::Meta::List(list) => {
|
||||
if list.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::new_spanned(attr.tokens.clone(), "Expected (<...>)"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let as_expr = attr.parse_args_with(
|
||||
Punctuated::<Expr, syn::Token![,]>::parse_separated_nonempty,
|
||||
)?;
|
||||
|
||||
for expr in as_expr.into_iter() {
|
||||
self.apply_meta(expr)?;
|
||||
}
|
||||
|
||||
// Stash its span for later (we don’t yet know if it’ll be an error)
|
||||
if self.skip && skip_tokens.is_none() {
|
||||
skip_tokens = Some(attr.tokens.clone());
|
||||
skip_tokens = Some(attr.meta.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -461,6 +463,8 @@ mod struct_info {
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::parse::Error;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::Expr;
|
||||
|
||||
use super::field_info::{FieldBuilderAttr, FieldInfo};
|
||||
use super::util::{
|
||||
@@ -1082,28 +1086,28 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
pub fn new(attrs: &[syn::Attribute]) -> Result<TypeBuilderAttr, Error> {
|
||||
let mut result = TypeBuilderAttr::default();
|
||||
for attr in attrs {
|
||||
if path_to_single_string(&attr.path).as_deref() != Some("builder") {
|
||||
if path_to_single_string(attr.path()).as_deref() != Some("builder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if attr.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let as_expr: syn::Expr = syn::parse2(attr.tokens.clone())?;
|
||||
|
||||
match as_expr {
|
||||
syn::Expr::Paren(body) => {
|
||||
result.apply_meta(*body.expr)?;
|
||||
}
|
||||
syn::Expr::Tuple(body) => {
|
||||
for expr in body.elems.into_iter() {
|
||||
result.apply_meta(expr)?;
|
||||
match &attr.meta {
|
||||
syn::Meta::List(list) => {
|
||||
if list.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::new_spanned(attr.tokens.clone(), "Expected (<...>)"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let as_expr = attr.parse_args_with(
|
||||
Punctuated::<Expr, syn::Token![,]>::parse_separated_nonempty,
|
||||
)?;
|
||||
|
||||
for expr in as_expr.into_iter() {
|
||||
result.apply_meta(expr)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.3.3"
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2018"
|
||||
description = "Core functionality for Dioxus - a concurrent renderer-agnostic Virtual DOM for interactive user experiences"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com"
|
||||
keywords = ["dom", "ui", "gui", "react"]
|
||||
@@ -33,13 +33,12 @@ log = { workspace = true }
|
||||
# Serialize the Edits for use in Webview/Liveview instances
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
|
||||
bumpslab = { version = "0.2.0" }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
dioxus = { workspace = true }
|
||||
pretty_assertions = "1.3.0"
|
||||
rand = "0.8.5"
|
||||
dioxus-ssr = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use std::{marker::PhantomData, panic::AssertUnwindSafe};
|
||||
|
||||
use crate::{
|
||||
innerlude::Scoped,
|
||||
nodes::{ComponentReturn, RenderReturn},
|
||||
nodes::RenderReturn,
|
||||
scopes::{Scope, ScopeState},
|
||||
Element,
|
||||
};
|
||||
use std::panic::AssertUnwindSafe;
|
||||
|
||||
/// A trait that essentially allows VComponentProps to be used generically
|
||||
///
|
||||
@@ -18,19 +17,15 @@ pub(crate) unsafe trait AnyProps<'a> {
|
||||
unsafe fn memoize(&self, other: &dyn AnyProps) -> bool;
|
||||
}
|
||||
|
||||
pub(crate) struct VProps<'a, P, A, F: ComponentReturn<'a, A> = Element<'a>> {
|
||||
pub render_fn: fn(Scope<'a, P>) -> F,
|
||||
pub(crate) struct VProps<'a, P> {
|
||||
pub render_fn: fn(Scope<'a, P>) -> Element<'a>,
|
||||
pub memo: unsafe fn(&P, &P) -> bool,
|
||||
pub props: P,
|
||||
_marker: PhantomData<A>,
|
||||
}
|
||||
|
||||
impl<'a, P, A, F> VProps<'a, P, A, F>
|
||||
where
|
||||
F: ComponentReturn<'a, A>,
|
||||
{
|
||||
impl<'a, P> VProps<'a, P> {
|
||||
pub(crate) fn new(
|
||||
render_fn: fn(Scope<'a, P>) -> F,
|
||||
render_fn: fn(Scope<'a, P>) -> Element<'a>,
|
||||
memo: unsafe fn(&P, &P) -> bool,
|
||||
props: P,
|
||||
) -> Self {
|
||||
@@ -38,15 +33,11 @@ where
|
||||
render_fn,
|
||||
memo,
|
||||
props,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<'a, P, A, F> AnyProps<'a> for VProps<'a, P, A, F>
|
||||
where
|
||||
F: ComponentReturn<'a, A>,
|
||||
{
|
||||
unsafe impl<'a, P> AnyProps<'a> for VProps<'a, P> {
|
||||
fn props_ptr(&self) -> *const () {
|
||||
&self.props as *const _ as *const ()
|
||||
}
|
||||
@@ -69,12 +60,12 @@ where
|
||||
scope: cx,
|
||||
});
|
||||
|
||||
(self.render_fn)(scope).into_return(cx)
|
||||
(self.render_fn)(scope)
|
||||
}));
|
||||
|
||||
match res {
|
||||
Ok(e) => e,
|
||||
Err(_) => RenderReturn::default(),
|
||||
Ok(Some(e)) => RenderReturn::Ready(e),
|
||||
_ => RenderReturn::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,21 +91,21 @@ impl VirtualDom {
|
||||
// Note: This will not remove any ids from the arena
|
||||
pub(crate) fn drop_scope(&mut self, id: ScopeId, recursive: bool) {
|
||||
self.dirty_scopes.remove(&DirtyScope {
|
||||
height: self.scopes[id].height,
|
||||
height: self.scopes[id.0].height,
|
||||
id,
|
||||
});
|
||||
|
||||
self.ensure_drop_safety(id);
|
||||
|
||||
if recursive {
|
||||
if let Some(root) = self.scopes[id].try_root_node() {
|
||||
if let Some(root) = self.scopes[id.0].try_root_node() {
|
||||
if let RenderReturn::Ready(node) = unsafe { root.extend_lifetime_ref() } {
|
||||
self.drop_scope_inner(node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let scope = &mut self.scopes[id];
|
||||
let scope = &mut self.scopes[id.0];
|
||||
|
||||
// Drop all the hooks once the children are dropped
|
||||
// this means we'll drop hooks bottom-up
|
||||
@@ -116,7 +116,7 @@ impl VirtualDom {
|
||||
scope.tasks.remove(task_id);
|
||||
}
|
||||
|
||||
self.scopes.remove(id);
|
||||
self.scopes.remove(id.0);
|
||||
}
|
||||
|
||||
fn drop_scope_inner(&mut self, node: &VNode) {
|
||||
@@ -137,7 +137,7 @@ impl VirtualDom {
|
||||
|
||||
/// Descend through the tree, removing any borrowed props and listeners
|
||||
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
|
||||
let scope = &self.scopes[scope_id];
|
||||
let scope = &self.scopes[scope_id.0];
|
||||
|
||||
// make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
|
||||
// run the hooks (which hold an &mut Reference)
|
||||
|
||||
@@ -5,10 +5,9 @@ use crate::mutations::Mutation::*;
|
||||
use crate::nodes::VNode;
|
||||
use crate::nodes::{DynamicNode, TemplateNode};
|
||||
use crate::virtual_dom::VirtualDom;
|
||||
use crate::{AttributeValue, ElementId, RenderReturn, ScopeId, SuspenseContext, Template};
|
||||
use crate::{AttributeValue, ElementId, RenderReturn, ScopeId, Template};
|
||||
use std::cell::Cell;
|
||||
use std::iter::Peekable;
|
||||
use std::rc::Rc;
|
||||
use TemplateNode::*;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -89,8 +88,7 @@ impl<'b> VirtualDom {
|
||||
}
|
||||
|
||||
// Intialize the root nodes slice
|
||||
node.root_ids
|
||||
.intialize(vec![ElementId(0); node.template.get().roots.len()].into_boxed_slice());
|
||||
*node.root_ids.borrow_mut() = vec![ElementId(0); node.template.get().roots.len()];
|
||||
|
||||
// The best renderers will have templates prehydrated and registered
|
||||
// Just in case, let's create the template using instructions anyways
|
||||
@@ -329,7 +327,7 @@ impl<'b> VirtualDom {
|
||||
fn load_template_root(&mut self, template: &VNode, root_idx: usize) -> ElementId {
|
||||
// Get an ID for this root since it's a real root
|
||||
let this_id = self.next_root(template, root_idx);
|
||||
template.root_ids.set(root_idx, this_id);
|
||||
template.root_ids.borrow_mut()[root_idx] = this_id;
|
||||
|
||||
self.mutations.push(LoadTemplate {
|
||||
name: template.template.get().name,
|
||||
@@ -445,7 +443,7 @@ impl<'b> VirtualDom {
|
||||
match node {
|
||||
Text(text) => self.create_dynamic_text(template, text, idx),
|
||||
Placeholder(place) => self.create_placeholder(place, template, idx),
|
||||
Component(component) => self.create_component_node(template, component, idx),
|
||||
Component(component) => self.create_component_node(template, component),
|
||||
Fragment(frag) => frag.iter().map(|child| self.create(child)).sum(),
|
||||
}
|
||||
}
|
||||
@@ -502,7 +500,6 @@ impl<'b> VirtualDom {
|
||||
&mut self,
|
||||
template: &'b VNode<'b>,
|
||||
component: &'b VComponent<'b>,
|
||||
idx: usize,
|
||||
) -> usize {
|
||||
use RenderReturn::*;
|
||||
|
||||
@@ -512,9 +509,9 @@ impl<'b> VirtualDom {
|
||||
component.scope.set(Some(scope));
|
||||
|
||||
match unsafe { self.run_scope(scope).extend_lifetime_ref() } {
|
||||
Ready(t) => self.mount_component(scope, template, t, idx),
|
||||
// Create the component's root element
|
||||
Ready(t) => self.create_scope(scope, t),
|
||||
Aborted(t) => self.mount_aborted(template, t),
|
||||
Pending(_) => self.mount_async(template, idx, scope),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,60 +527,6 @@ impl<'b> VirtualDom {
|
||||
.unwrap_or_else(|| component.scope.get().unwrap())
|
||||
}
|
||||
|
||||
fn mount_component(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
parent: &'b VNode<'b>,
|
||||
new: &'b VNode<'b>,
|
||||
idx: usize,
|
||||
) -> usize {
|
||||
// Keep track of how many mutations are in the buffer in case we need to split them out if a suspense boundary
|
||||
// is encountered
|
||||
let mutations_to_this_point = self.mutations.edits.len();
|
||||
|
||||
// Create the component's root element
|
||||
let created = self.create_scope(scope, new);
|
||||
|
||||
// If there are no suspense leaves below us, then just don't bother checking anything suspense related
|
||||
if self.collected_leaves.is_empty() {
|
||||
return created;
|
||||
}
|
||||
|
||||
// If running the scope has collected some leaves and *this* component is a boundary, then handle the suspense
|
||||
let boundary = match self.scopes[scope].has_context::<Rc<SuspenseContext>>() {
|
||||
Some(boundary) => boundary,
|
||||
_ => return created,
|
||||
};
|
||||
|
||||
// Since this is a boundary, use its placeholder within the template as the placeholder for the suspense tree
|
||||
let new_id = self.next_element(new, parent.template.get().node_paths[idx]);
|
||||
|
||||
// Now connect everything to the boundary
|
||||
self.scopes[scope].placeholder.set(Some(new_id));
|
||||
|
||||
// This involves breaking off the mutations to this point, and then creating a new placeholder for the boundary
|
||||
// Note that we break off dynamic mutations only - since static mutations aren't rendered immediately
|
||||
let split_off = unsafe {
|
||||
std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
|
||||
self.mutations.edits.split_off(mutations_to_this_point),
|
||||
)
|
||||
};
|
||||
boundary.mutations.borrow_mut().edits.extend(split_off);
|
||||
boundary.created_on_stack.set(created);
|
||||
boundary
|
||||
.waiting_on
|
||||
.borrow_mut()
|
||||
.extend(self.collected_leaves.drain(..));
|
||||
|
||||
// Now assign the placeholder in the DOM
|
||||
self.mutations.push(AssignId {
|
||||
id: new_id,
|
||||
path: &parent.template.get().node_paths[idx][1..],
|
||||
});
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
fn mount_aborted(&mut self, parent: &'b VNode<'b>, placeholder: &VPlaceholder) -> usize {
|
||||
let id = self.next_element(parent, &[]);
|
||||
self.mutations.push(Mutation::CreatePlaceholder { id });
|
||||
@@ -591,24 +534,6 @@ impl<'b> VirtualDom {
|
||||
1
|
||||
}
|
||||
|
||||
/// Take the rendered nodes from a component and handle them if they were async
|
||||
///
|
||||
/// IE simply assign an ID to the placeholder
|
||||
fn mount_async(&mut self, template: &VNode, idx: usize, scope: ScopeId) -> usize {
|
||||
let new_id = self.next_element(template, template.template.get().node_paths[idx]);
|
||||
|
||||
// Set the placeholder of the scope
|
||||
self.scopes[scope].placeholder.set(Some(new_id));
|
||||
|
||||
// Since the placeholder is already in the DOM, we don't create any new nodes
|
||||
self.mutations.push(AssignId {
|
||||
id: new_id,
|
||||
path: &template.template.get().node_paths[idx][1..],
|
||||
});
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
fn set_slot(
|
||||
&mut self,
|
||||
template: &'b VNode<'b>,
|
||||
|
||||
+26
-46
@@ -15,7 +15,7 @@ use DynamicNode::*;
|
||||
|
||||
impl<'b> VirtualDom {
|
||||
pub(super) fn diff_scope(&mut self, scope: ScopeId) {
|
||||
let scope_state = &mut self.scopes[scope];
|
||||
let scope_state = &mut self.scopes[scope.0];
|
||||
|
||||
self.scope_stack.push(scope);
|
||||
unsafe {
|
||||
@@ -30,7 +30,7 @@ impl<'b> VirtualDom {
|
||||
.try_load_node()
|
||||
.expect("Call rebuild before diffing");
|
||||
|
||||
use RenderReturn::{Aborted, Pending, Ready};
|
||||
use RenderReturn::{Aborted, Ready};
|
||||
|
||||
match (old, new) {
|
||||
// Normal pathway
|
||||
@@ -42,29 +42,14 @@ impl<'b> VirtualDom {
|
||||
// Just move over the placeholder
|
||||
(Aborted(l), Aborted(r)) => r.id.set(l.id.get()),
|
||||
|
||||
// Becomes async, do nothing while we wait
|
||||
(Ready(_nodes), Pending(_fut)) => self.diff_ok_to_async(_nodes, scope),
|
||||
|
||||
// Placeholder becomes something
|
||||
// We should also clear the error now
|
||||
(Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
|
||||
|
||||
(Aborted(_), Pending(_)) => todo!("async should not resolve here"),
|
||||
(Pending(_), Ready(_)) => todo!("async should not resolve here"),
|
||||
(Pending(_), Aborted(_)) => todo!("async should not resolve here"),
|
||||
(Pending(_), Pending(_)) => {
|
||||
// All suspense should resolve before we diff it again
|
||||
panic!("Should not roll from suspense to suspense.");
|
||||
}
|
||||
};
|
||||
}
|
||||
self.scope_stack.pop();
|
||||
}
|
||||
|
||||
fn diff_ok_to_async(&mut self, _new: &'b VNode<'b>, _scope: ScopeId) {
|
||||
//
|
||||
}
|
||||
|
||||
fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
|
||||
let id = self.next_null();
|
||||
p.id.set(Some(id));
|
||||
@@ -139,18 +124,19 @@ impl<'b> VirtualDom {
|
||||
.dynamic_nodes
|
||||
.iter()
|
||||
.zip(right_template.dynamic_nodes.iter())
|
||||
.enumerate()
|
||||
.for_each(|(idx, (left_node, right_node))| {
|
||||
self.diff_dynamic_node(left_node, right_node, right_template, idx);
|
||||
.for_each(|(left_node, right_node)| {
|
||||
self.diff_dynamic_node(left_node, right_node, right_template);
|
||||
});
|
||||
|
||||
// Make sure the roots get transferred over while we're here
|
||||
right_template.root_ids.transfer(&left_template.root_ids);
|
||||
*right_template.root_ids.borrow_mut() = left_template.root_ids.borrow().clone();
|
||||
|
||||
let root_ids = right_template.root_ids.borrow();
|
||||
|
||||
// Update the node refs
|
||||
for i in 0..right_template.root_ids.len() {
|
||||
if let Some(root_id) = right_template.root_ids.get(i) {
|
||||
self.update_template(root_id, right_template);
|
||||
for i in 0..root_ids.len() {
|
||||
if let Some(root_id) = root_ids.get(i) {
|
||||
self.update_template(*root_id, right_template);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,13 +146,12 @@ impl<'b> VirtualDom {
|
||||
left_node: &'b DynamicNode<'b>,
|
||||
right_node: &'b DynamicNode<'b>,
|
||||
node: &'b VNode<'b>,
|
||||
idx: usize,
|
||||
) {
|
||||
match (left_node, right_node) {
|
||||
(Text(left), Text(right)) => self.diff_vtext(left, right, node),
|
||||
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
|
||||
(Placeholder(left), Placeholder(right)) => right.id.set(left.id.get()),
|
||||
(Component(left), Component(right)) => self.diff_vcomponent(left, right, node, idx),
|
||||
(Component(left), Component(right)) => self.diff_vcomponent(left, right, node),
|
||||
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right),
|
||||
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right),
|
||||
_ => todo!("This is an usual custom case for dynamic nodes. We don't know how to handle it yet."),
|
||||
@@ -190,7 +175,6 @@ impl<'b> VirtualDom {
|
||||
left: &'b VComponent<'b>,
|
||||
right: &'b VComponent<'b>,
|
||||
right_template: &'b VNode<'b>,
|
||||
idx: usize,
|
||||
) {
|
||||
if std::ptr::eq(left, right) {
|
||||
return;
|
||||
@@ -198,7 +182,7 @@ impl<'b> VirtualDom {
|
||||
|
||||
// Replace components that have different render fns
|
||||
if left.render_fn != right.render_fn {
|
||||
return self.replace_vcomponent(right_template, right, idx, left);
|
||||
return self.replace_vcomponent(right_template, right, left);
|
||||
}
|
||||
|
||||
// Make sure the new vcomponent has the right scopeid associated to it
|
||||
@@ -207,7 +191,7 @@ impl<'b> VirtualDom {
|
||||
right.scope.set(Some(scope_id));
|
||||
|
||||
// copy out the box for both
|
||||
let old = self.scopes[scope_id].props.as_ref();
|
||||
let old = self.scopes[scope_id.0].props.as_ref();
|
||||
let new: Box<dyn AnyProps> = right.props.take().unwrap();
|
||||
let new: Box<dyn AnyProps> = unsafe { std::mem::transmute(new) };
|
||||
|
||||
@@ -219,14 +203,14 @@ impl<'b> VirtualDom {
|
||||
}
|
||||
|
||||
// First, move over the props from the old to the new, dropping old props in the process
|
||||
self.scopes[scope_id].props = Some(new);
|
||||
self.scopes[scope_id.0].props = Some(new);
|
||||
|
||||
// Now run the component and diff it
|
||||
self.run_scope(scope_id);
|
||||
self.diff_scope(scope_id);
|
||||
|
||||
self.dirty_scopes.remove(&DirtyScope {
|
||||
height: self.scopes[scope_id].height,
|
||||
height: self.scopes[scope_id.0].height,
|
||||
id: scope_id,
|
||||
});
|
||||
}
|
||||
@@ -235,10 +219,9 @@ impl<'b> VirtualDom {
|
||||
&mut self,
|
||||
right_template: &'b VNode<'b>,
|
||||
right: &'b VComponent<'b>,
|
||||
idx: usize,
|
||||
left: &'b VComponent<'b>,
|
||||
) {
|
||||
let m = self.create_component_node(right_template, right, idx);
|
||||
let m = self.create_component_node(right_template, right);
|
||||
|
||||
let pre_edits = self.mutations.edits.len();
|
||||
|
||||
@@ -297,8 +280,7 @@ impl<'b> VirtualDom {
|
||||
None => self.replace(left, [right]),
|
||||
Some(components) => components
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.for_each(|(idx, (l, r))| self.diff_vcomponent(l, r, right, idx)),
|
||||
.for_each(|(l, r)| self.diff_vcomponent(l, r, right)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -706,7 +688,7 @@ impl<'b> VirtualDom {
|
||||
Some(node) => node,
|
||||
None => {
|
||||
self.mutations.push(Mutation::PushRoot {
|
||||
id: node.root_ids.get(idx).unwrap(),
|
||||
id: node.root_ids.borrow()[idx],
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
@@ -732,10 +714,9 @@ impl<'b> VirtualDom {
|
||||
|
||||
Component(comp) => {
|
||||
let scope = comp.scope.get().unwrap();
|
||||
match unsafe { self.scopes[scope].root_node().extend_lifetime_ref() } {
|
||||
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
|
||||
RenderReturn::Ready(node) => self.push_all_real_nodes(node),
|
||||
RenderReturn::Aborted(_node) => todo!(),
|
||||
_ => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -842,7 +823,7 @@ impl<'b> VirtualDom {
|
||||
if let Some(dy) = node.dynamic_root(idx) {
|
||||
self.remove_dynamic_node(dy, gen_muts);
|
||||
} else {
|
||||
let id = node.root_ids.get(idx).unwrap();
|
||||
let id = node.root_ids.borrow()[idx];
|
||||
if gen_muts {
|
||||
self.mutations.push(Mutation::Remove { id });
|
||||
}
|
||||
@@ -934,14 +915,13 @@ impl<'b> VirtualDom {
|
||||
.expect("VComponents to always have a scope");
|
||||
|
||||
// Remove the component from the dom
|
||||
match unsafe { self.scopes[scope].root_node().extend_lifetime_ref() } {
|
||||
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
|
||||
RenderReturn::Ready(t) => self.remove_node(t, gen_muts),
|
||||
RenderReturn::Aborted(placeholder) => self.remove_placeholder(placeholder, gen_muts),
|
||||
_ => todo!(),
|
||||
};
|
||||
|
||||
// Restore the props back to the vcomponent in case it gets rendered again
|
||||
let props = self.scopes[scope].props.take();
|
||||
let props = self.scopes[scope.0].props.take();
|
||||
*comp.props.borrow_mut() = unsafe { std::mem::transmute(props) };
|
||||
|
||||
// Now drop all the resouces
|
||||
@@ -950,13 +930,13 @@ impl<'b> VirtualDom {
|
||||
|
||||
fn find_first_element(&self, node: &'b VNode<'b>) -> ElementId {
|
||||
match node.dynamic_root(0) {
|
||||
None => node.root_ids.get(0).unwrap(),
|
||||
None => node.root_ids.borrow()[0],
|
||||
Some(Text(t)) => t.id.get().unwrap(),
|
||||
Some(Fragment(t)) => self.find_first_element(&t[0]),
|
||||
Some(Placeholder(t)) => t.id.get().unwrap(),
|
||||
Some(Component(comp)) => {
|
||||
let scope = comp.scope.get().unwrap();
|
||||
match unsafe { self.scopes[scope].root_node().extend_lifetime_ref() } {
|
||||
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
|
||||
RenderReturn::Ready(t) => self.find_first_element(t),
|
||||
_ => todo!("cannot handle nonstandard nodes"),
|
||||
}
|
||||
@@ -966,13 +946,13 @@ impl<'b> VirtualDom {
|
||||
|
||||
fn find_last_element(&self, node: &'b VNode<'b>) -> ElementId {
|
||||
match node.dynamic_root(node.template.get().roots.len() - 1) {
|
||||
None => node.root_ids.last().unwrap(),
|
||||
None => *node.root_ids.borrow().last().unwrap(),
|
||||
Some(Text(t)) => t.id.get().unwrap(),
|
||||
Some(Fragment(t)) => self.find_last_element(t.last().unwrap()),
|
||||
Some(Placeholder(t)) => t.id.get().unwrap(),
|
||||
Some(Component(comp)) => {
|
||||
let scope = comp.scope.get().unwrap();
|
||||
match unsafe { self.scopes[scope].root_node().extend_lifetime_ref() } {
|
||||
match unsafe { self.scopes[scope.0].root_node().extend_lifetime_ref() } {
|
||||
RenderReturn::Ready(t) => self.find_last_element(t),
|
||||
_ => todo!("cannot handle nonstandard nodes"),
|
||||
}
|
||||
|
||||
@@ -72,9 +72,8 @@ pub(crate) mod innerlude {
|
||||
pub use crate::innerlude::{
|
||||
fc_to_builder, AnyValue, Attribute, AttributeValue, BorrowedAttributeValue, CapturedError,
|
||||
Component, DynamicNode, Element, ElementId, Event, Fragment, IntoDynNode, LazyNodes, Mutation,
|
||||
Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped, SuspenseContext,
|
||||
TaskId, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText,
|
||||
VirtualDom,
|
||||
Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
|
||||
TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText, VirtualDom,
|
||||
};
|
||||
|
||||
/// The purpose of this module is to alleviate imports of many common types
|
||||
|
||||
+3
-132
@@ -5,9 +5,8 @@ use bumpalo::boxed::Box as BumpBox;
|
||||
use bumpalo::Bump;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
cell::{Cell, RefCell, UnsafeCell},
|
||||
cell::{Cell, RefCell},
|
||||
fmt::{Arguments, Debug},
|
||||
future::Future,
|
||||
};
|
||||
|
||||
pub type TemplateId = &'static str;
|
||||
@@ -28,9 +27,6 @@ pub enum RenderReturn<'a> {
|
||||
/// In its place we've produced a placeholder to locate its spot in the dom when
|
||||
/// it recovers.
|
||||
Aborted(VPlaceholder),
|
||||
|
||||
/// An ongoing future that will resolve to a [`Element`]
|
||||
Pending(BumpBox<'a, dyn Future<Output = Element<'a>> + 'a>),
|
||||
}
|
||||
|
||||
impl<'a> Default for RenderReturn<'a> {
|
||||
@@ -58,7 +54,7 @@ pub struct VNode<'a> {
|
||||
|
||||
/// The IDs for the roots of this template - to be used when moving the template around and removing it from
|
||||
/// the actual Dom
|
||||
pub root_ids: BoxedCellSlice,
|
||||
pub root_ids: RefCell<Vec<ElementId>>,
|
||||
|
||||
/// The dynamic parts of the template
|
||||
pub dynamic_nodes: &'a [DynamicNode<'a>],
|
||||
@@ -67,112 +63,13 @@ pub struct VNode<'a> {
|
||||
pub dynamic_attrs: &'a [Attribute<'a>],
|
||||
}
|
||||
|
||||
// Saftey: There is no way to get references to the internal data of this struct so no refrences will be invalidated by mutating the data with a immutable reference (The same principle behind Cell)
|
||||
#[derive(Debug, Default)]
|
||||
pub struct BoxedCellSlice(UnsafeCell<Option<Box<[ElementId]>>>);
|
||||
|
||||
impl Clone for BoxedCellSlice {
|
||||
fn clone(&self) -> Self {
|
||||
Self(UnsafeCell::new(unsafe { (*self.0.get()).clone() }))
|
||||
}
|
||||
}
|
||||
|
||||
impl BoxedCellSlice {
|
||||
pub fn last(&self) -> Option<ElementId> {
|
||||
unsafe {
|
||||
(*self.0.get())
|
||||
.as_ref()
|
||||
.and_then(|inner| inner.as_ref().last().copied())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, idx: usize) -> Option<ElementId> {
|
||||
unsafe {
|
||||
(*self.0.get())
|
||||
.as_ref()
|
||||
.and_then(|inner| inner.as_ref().get(idx).copied())
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn get_unchecked(&self, idx: usize) -> Option<ElementId> {
|
||||
(*self.0.get())
|
||||
.as_ref()
|
||||
.and_then(|inner| inner.as_ref().get(idx).copied())
|
||||
}
|
||||
|
||||
pub fn set(&self, idx: usize, new: ElementId) {
|
||||
unsafe {
|
||||
if let Some(inner) = &mut *self.0.get() {
|
||||
inner[idx] = new;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn intialize(&self, contents: Box<[ElementId]>) {
|
||||
unsafe {
|
||||
*self.0.get() = Some(contents);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn transfer(&self, other: &Self) {
|
||||
unsafe {
|
||||
*self.0.get() = (*other.0.get()).clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_from(&self, other: &Self) {
|
||||
unsafe {
|
||||
*self.0.get() = (*other.0.get()).take();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
unsafe {
|
||||
(*self.0.get())
|
||||
.as_ref()
|
||||
.map(|inner| inner.len())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a BoxedCellSlice {
|
||||
type Item = ElementId;
|
||||
|
||||
type IntoIter = BoxedCellSliceIter<'a>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
BoxedCellSliceIter {
|
||||
index: 0,
|
||||
borrow: self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BoxedCellSliceIter<'a> {
|
||||
index: usize,
|
||||
borrow: &'a BoxedCellSlice,
|
||||
}
|
||||
|
||||
impl Iterator for BoxedCellSliceIter<'_> {
|
||||
type Item = ElementId;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let result = self.borrow.get(self.index);
|
||||
if result.is_some() {
|
||||
self.index += 1;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> VNode<'a> {
|
||||
/// Create a template with no nodes that will be skipped over during diffing
|
||||
pub fn empty() -> Element<'a> {
|
||||
Some(VNode {
|
||||
key: None,
|
||||
parent: None,
|
||||
root_ids: BoxedCellSlice::default(),
|
||||
root_ids: Default::default(),
|
||||
dynamic_nodes: &[],
|
||||
dynamic_attrs: &[],
|
||||
template: Cell::new(Template {
|
||||
@@ -688,32 +585,6 @@ impl<T: Any + PartialEq + 'static> AnyValue for T {
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait ComponentReturn<'a, A = ()> {
|
||||
fn into_return(self, cx: &'a ScopeState) -> RenderReturn<'a>;
|
||||
}
|
||||
|
||||
impl<'a> ComponentReturn<'a> for Element<'a> {
|
||||
fn into_return(self, _cx: &ScopeState) -> RenderReturn<'a> {
|
||||
match self {
|
||||
Some(node) => RenderReturn::Ready(node),
|
||||
None => RenderReturn::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct AsyncMarker;
|
||||
impl<'a, F> ComponentReturn<'a, AsyncMarker> for F
|
||||
where
|
||||
F: Future<Output = Element<'a>> + 'a,
|
||||
{
|
||||
fn into_return(self, cx: &'a ScopeState) -> RenderReturn<'a> {
|
||||
let f: &mut dyn Future<Output = Element<'a>> = cx.bump().alloc(self);
|
||||
RenderReturn::Pending(unsafe { BumpBox::from_raw(f) })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RenderReturn<'a> {
|
||||
pub(crate) unsafe fn extend_lifetime_ref<'c>(&self) -> &'c RenderReturn<'c> {
|
||||
unsafe { std::mem::transmute(self) }
|
||||
|
||||
@@ -70,6 +70,6 @@ impl EmptyBuilder {
|
||||
|
||||
/// This utility function launches the builder method so rsx! and html! macros can use the typed-builder pattern
|
||||
/// to initialize a component's props.
|
||||
pub fn fc_to_builder<'a, A, T: Properties + 'a>(_: fn(Scope<'a, T>) -> A) -> T::Builder {
|
||||
pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>) -> T::Builder {
|
||||
T::builder()
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
use crate::ScopeId;
|
||||
use slab::Slab;
|
||||
|
||||
mod suspense;
|
||||
mod task;
|
||||
mod wait;
|
||||
|
||||
pub use suspense::*;
|
||||
pub use task::*;
|
||||
|
||||
/// The type of message that can be sent to the scheduler.
|
||||
@@ -18,9 +16,6 @@ pub(crate) enum SchedulerMsg {
|
||||
|
||||
/// A task has woken and needs to be progressed
|
||||
TaskNotified(TaskId),
|
||||
|
||||
/// A task has woken and needs to be progressed
|
||||
SuspenseNotified(SuspenseId),
|
||||
}
|
||||
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
@@ -30,9 +25,6 @@ pub(crate) struct Scheduler {
|
||||
|
||||
/// Tasks created with cx.spawn
|
||||
pub tasks: RefCell<Slab<LocalTask>>,
|
||||
|
||||
/// Async components
|
||||
pub leaves: RefCell<Slab<SuspenseLeaf>>,
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
@@ -40,7 +32,6 @@ impl Scheduler {
|
||||
Rc::new(Scheduler {
|
||||
sender,
|
||||
tasks: RefCell::new(Slab::new()),
|
||||
leaves: RefCell::new(Slab::new()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,10 @@ use std::{
|
||||
collections::HashSet,
|
||||
};
|
||||
|
||||
/// An ID representing an ongoing suspended component
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
|
||||
pub(crate) struct SuspenseId(pub usize);
|
||||
|
||||
/// A boundary in the VirtualDom that captures all suspended components below it
|
||||
pub struct SuspenseContext {
|
||||
pub(crate) id: ScopeId,
|
||||
pub(crate) waiting_on: RefCell<HashSet<SuspenseId>>,
|
||||
pub(crate) mutations: RefCell<Mutations<'static>>,
|
||||
pub(crate) placeholder: Cell<Option<ElementId>>,
|
||||
pub(crate) created_on_stack: Cell<usize>,
|
||||
pub(crate) waiting_on: RefCell<HashSet<ScopeId>>,
|
||||
}
|
||||
|
||||
impl SuspenseContext {
|
||||
@@ -30,29 +23,10 @@ impl SuspenseContext {
|
||||
Self {
|
||||
id,
|
||||
waiting_on: Default::default(),
|
||||
mutations: RefCell::new(Mutations::default()),
|
||||
placeholder: Cell::new(None),
|
||||
created_on_stack: Cell::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct SuspenseLeaf {
|
||||
pub(crate) scope_id: ScopeId,
|
||||
pub(crate) notified: Cell<bool>,
|
||||
pub(crate) task: *mut dyn Future<Output = Element<'static>>,
|
||||
pub(crate) waker: Waker,
|
||||
}
|
||||
|
||||
pub struct SuspenseHandle {
|
||||
pub(crate) id: SuspenseId,
|
||||
pub(crate) tx: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
|
||||
}
|
||||
|
||||
impl ArcWake for SuspenseHandle {
|
||||
fn wake_by_ref(arc_self: &Arc<Self>) {
|
||||
_ = arc_self
|
||||
.tx
|
||||
.unbounded_send(SchedulerMsg::SuspenseNotified(arc_self.id));
|
||||
pub fn mark_suspend(&self, id: ScopeId) {
|
||||
self.waiting_on.borrow_mut().insert(id);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,5 @@
|
||||
use futures_util::FutureExt;
|
||||
use std::{
|
||||
rc::Rc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
innerlude::{Mutation, Mutations, SuspenseContext},
|
||||
nodes::RenderReturn,
|
||||
ScopeId, TaskId, VNode, VirtualDom,
|
||||
};
|
||||
|
||||
use super::SuspenseId;
|
||||
use crate::{TaskId, VirtualDom};
|
||||
use std::task::Context;
|
||||
|
||||
impl VirtualDom {
|
||||
/// Handle notifications by tasks inside the scheduler
|
||||
@@ -31,81 +20,11 @@ impl VirtualDom {
|
||||
// If the task completes...
|
||||
if task.task.borrow_mut().as_mut().poll(&mut cx).is_ready() {
|
||||
// Remove it from the scope so we dont try to double drop it when the scope dropes
|
||||
let scope = &self.scopes[task.scope];
|
||||
let scope = &self.scopes[task.scope.0];
|
||||
scope.spawned_tasks.borrow_mut().remove(&id);
|
||||
|
||||
// Remove it from the scheduler
|
||||
tasks.try_remove(id.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_suspense_boundary(&self, id: ScopeId) -> Rc<SuspenseContext> {
|
||||
self.scopes[id]
|
||||
.consume_context::<Rc<SuspenseContext>>()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn handle_suspense_wakeup(&mut self, id: SuspenseId) {
|
||||
let leaves = self.scheduler.leaves.borrow_mut();
|
||||
let leaf = leaves.get(id.0).unwrap();
|
||||
|
||||
let scope_id = leaf.scope_id;
|
||||
|
||||
// todo: cache the waker
|
||||
let mut cx = Context::from_waker(&leaf.waker);
|
||||
|
||||
// Safety: the future is always pinned to the bump arena
|
||||
let mut pinned = unsafe { std::pin::Pin::new_unchecked(&mut *leaf.task) };
|
||||
let as_pinned_mut = &mut pinned;
|
||||
|
||||
// the component finished rendering and gave us nodes
|
||||
// we should attach them to that component and then render its children
|
||||
// continue rendering the tree until we hit yet another suspended component
|
||||
if let Poll::Ready(new_nodes) = as_pinned_mut.poll_unpin(&mut cx) {
|
||||
let fiber = self.acquire_suspense_boundary(leaf.scope_id);
|
||||
|
||||
let scope = &self.scopes[scope_id];
|
||||
let arena = scope.current_frame();
|
||||
|
||||
let ret = arena.bump().alloc(match new_nodes {
|
||||
Some(new) => RenderReturn::Ready(new),
|
||||
None => RenderReturn::default(),
|
||||
});
|
||||
|
||||
arena.node.set(ret);
|
||||
|
||||
fiber.waiting_on.borrow_mut().remove(&id);
|
||||
|
||||
if let RenderReturn::Ready(template) = ret {
|
||||
let mutations_ref = &mut fiber.mutations.borrow_mut();
|
||||
let mutations = &mut **mutations_ref;
|
||||
let template: &VNode = unsafe { std::mem::transmute(template) };
|
||||
let mutations: &mut Mutations = unsafe { std::mem::transmute(mutations) };
|
||||
|
||||
std::mem::swap(&mut self.mutations, mutations);
|
||||
|
||||
let place_holder_id = scope.placeholder.get().unwrap();
|
||||
self.scope_stack.push(scope_id);
|
||||
|
||||
drop(leaves);
|
||||
|
||||
let created = self.create(template);
|
||||
self.scope_stack.pop();
|
||||
mutations.push(Mutation::ReplaceWith {
|
||||
id: place_holder_id,
|
||||
m: created,
|
||||
});
|
||||
|
||||
for leaf in self.collected_leaves.drain(..) {
|
||||
fiber.waiting_on.borrow_mut().insert(leaf);
|
||||
}
|
||||
|
||||
std::mem::swap(&mut self.mutations, mutations);
|
||||
|
||||
if fiber.waiting_on.borrow().is_empty() {
|
||||
self.finished_fibers.push(fiber.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,10 @@ use crate::{
|
||||
any_props::AnyProps,
|
||||
bump_frame::BumpFrame,
|
||||
innerlude::DirtyScope,
|
||||
innerlude::{SuspenseHandle, SuspenseId, SuspenseLeaf},
|
||||
nodes::RenderReturn,
|
||||
scopes::{ScopeId, ScopeState},
|
||||
virtual_dom::VirtualDom,
|
||||
};
|
||||
use futures_util::FutureExt;
|
||||
use std::{
|
||||
mem,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
impl VirtualDom {
|
||||
pub(super) fn new_scope(
|
||||
@@ -24,32 +16,32 @@ impl VirtualDom {
|
||||
let parent = self.acquire_current_scope_raw();
|
||||
let entry = self.scopes.vacant_entry();
|
||||
let height = unsafe { parent.map(|f| (*f).height + 1).unwrap_or(0) };
|
||||
let id = entry.key();
|
||||
let id = ScopeId(entry.key());
|
||||
|
||||
entry.insert(ScopeState {
|
||||
entry.insert(Box::new(ScopeState {
|
||||
parent,
|
||||
id,
|
||||
height,
|
||||
name,
|
||||
props: Some(props),
|
||||
tasks: self.scheduler.clone(),
|
||||
placeholder: Default::default(),
|
||||
node_arena_1: BumpFrame::new(0),
|
||||
node_arena_2: BumpFrame::new(0),
|
||||
spawned_tasks: Default::default(),
|
||||
suspended: Default::default(),
|
||||
render_cnt: Default::default(),
|
||||
hooks: Default::default(),
|
||||
hook_idx: Default::default(),
|
||||
shared_contexts: Default::default(),
|
||||
borrowed_props: Default::default(),
|
||||
attributes_to_drop: Default::default(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn acquire_current_scope_raw(&self) -> Option<*const ScopeState> {
|
||||
let id = self.scope_stack.last().copied()?;
|
||||
let scope = self.scopes.get(id)?;
|
||||
Some(scope)
|
||||
let scope = self.scopes.get(id.0)?;
|
||||
Some(scope.as_ref())
|
||||
}
|
||||
|
||||
pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> &RenderReturn {
|
||||
@@ -58,75 +50,22 @@ impl VirtualDom {
|
||||
// Remove all the outdated listeners
|
||||
self.ensure_drop_safety(scope_id);
|
||||
|
||||
let mut new_nodes = unsafe {
|
||||
self.scopes[scope_id].previous_frame().bump_mut().reset();
|
||||
let new_nodes = unsafe {
|
||||
self.scopes[scope_id.0].previous_frame().bump_mut().reset();
|
||||
|
||||
let scope = &self.scopes[scope_id];
|
||||
let scope = &self.scopes[scope_id.0];
|
||||
scope.suspended.set(false);
|
||||
|
||||
scope.hook_idx.set(0);
|
||||
|
||||
// safety: due to how we traverse the tree, we know that the scope is not currently aliased
|
||||
let props: &dyn AnyProps = scope.props.as_ref().unwrap().as_ref();
|
||||
let props: &dyn AnyProps = mem::transmute(props);
|
||||
let props: &dyn AnyProps = std::mem::transmute(props);
|
||||
|
||||
props.render(scope).extend_lifetime()
|
||||
};
|
||||
|
||||
// immediately resolve futures that can be resolved
|
||||
if let RenderReturn::Pending(task) = &mut new_nodes {
|
||||
let mut leaves = self.scheduler.leaves.borrow_mut();
|
||||
|
||||
let entry = leaves.vacant_entry();
|
||||
let suspense_id = SuspenseId(entry.key());
|
||||
|
||||
let leaf = SuspenseLeaf {
|
||||
scope_id,
|
||||
task: task.as_mut(),
|
||||
notified: Default::default(),
|
||||
waker: futures_util::task::waker(Arc::new(SuspenseHandle {
|
||||
id: suspense_id,
|
||||
tx: self.scheduler.sender.clone(),
|
||||
})),
|
||||
};
|
||||
|
||||
let mut cx = Context::from_waker(&leaf.waker);
|
||||
|
||||
// safety: the task is already pinned in the bump arena
|
||||
let mut pinned = unsafe { Pin::new_unchecked(task.as_mut()) };
|
||||
|
||||
// Keep polling until either we get a value or the future is not ready
|
||||
loop {
|
||||
match pinned.poll_unpin(&mut cx) {
|
||||
// If nodes are produced, then set it and we can break
|
||||
Poll::Ready(nodes) => {
|
||||
new_nodes = match nodes {
|
||||
Some(nodes) => RenderReturn::Ready(nodes),
|
||||
None => RenderReturn::default(),
|
||||
};
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// If no nodes are produced but the future woke up immediately, then try polling it again
|
||||
// This circumvents things like yield_now, but is important is important when rendering
|
||||
// components that are just a stream of immediately ready futures
|
||||
_ if leaf.notified.get() => {
|
||||
leaf.notified.set(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If no nodes are produced, then we need to wait for the future to be woken up
|
||||
// Insert the future into fiber leaves and break
|
||||
_ => {
|
||||
entry.insert(leaf);
|
||||
self.collected_leaves.push(suspense_id);
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let scope = &self.scopes[scope_id];
|
||||
let scope = &self.scopes[scope_id.0];
|
||||
|
||||
// We write on top of the previous frame and then make it the current by pushing the generation forward
|
||||
let frame = scope.previous_frame();
|
||||
@@ -144,6 +83,14 @@ impl VirtualDom {
|
||||
id: scope.id,
|
||||
});
|
||||
|
||||
if scope.suspended.get() {
|
||||
if matches!(allocated, RenderReturn::Aborted(_)) {
|
||||
self.suspended_scopes.insert(scope.id);
|
||||
}
|
||||
} else if !self.suspended_scopes.is_empty() {
|
||||
_ = self.suspended_scopes.remove(&scope.id);
|
||||
}
|
||||
|
||||
// rebind the lifetime now that its stored internally
|
||||
unsafe { allocated.extend_lifetime_ref() }
|
||||
}
|
||||
|
||||
+12
-99
@@ -1,24 +1,20 @@
|
||||
use crate::{
|
||||
any_props::AnyProps,
|
||||
any_props::VProps,
|
||||
arena::ElementId,
|
||||
bump_frame::BumpFrame,
|
||||
innerlude::{DynamicNode, EventHandler, VComponent, VText},
|
||||
innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
|
||||
lazynodes::LazyNodes,
|
||||
nodes::{ComponentReturn, IntoAttributeValue, IntoDynNode, RenderReturn},
|
||||
nodes::{IntoAttributeValue, IntoDynNode, RenderReturn},
|
||||
AnyValue, Attribute, AttributeValue, Element, Event, Properties, TaskId,
|
||||
};
|
||||
use bumpalo::{boxed::Box as BumpBox, Bump};
|
||||
use bumpslab::{BumpSlab, Slot};
|
||||
use rustc_hash::FxHashSet;
|
||||
use slab::{Slab, VacantEntry};
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
cell::{Cell, RefCell, UnsafeCell},
|
||||
fmt::{Arguments, Debug},
|
||||
future::Future,
|
||||
ops::{Index, IndexMut},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
@@ -66,95 +62,6 @@ impl<'a, T> std::ops::Deref for Scoped<'a, T> {
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
|
||||
pub struct ScopeId(pub usize);
|
||||
|
||||
/// A thin wrapper around a BumpSlab that uses ids to index into the slab.
|
||||
pub(crate) struct ScopeSlab {
|
||||
slab: BumpSlab<ScopeState>,
|
||||
// a slab of slots of stable pointers to the ScopeState in the bump slab
|
||||
entries: Slab<Slot<'static, ScopeState>>,
|
||||
}
|
||||
|
||||
impl Drop for ScopeSlab {
|
||||
fn drop(&mut self) {
|
||||
// Bump slab doesn't drop its contents, so we need to do it manually
|
||||
for slot in self.entries.drain() {
|
||||
self.slab.remove(slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ScopeSlab {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
slab: BumpSlab::new(),
|
||||
entries: Slab::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScopeSlab {
|
||||
pub(crate) fn get(&self, id: ScopeId) -> Option<&ScopeState> {
|
||||
self.entries.get(id.0).map(|slot| unsafe { &*slot.ptr() })
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self, id: ScopeId) -> Option<&mut ScopeState> {
|
||||
self.entries
|
||||
.get(id.0)
|
||||
.map(|slot| unsafe { &mut *slot.ptr_mut() })
|
||||
}
|
||||
|
||||
pub(crate) fn vacant_entry(&mut self) -> ScopeSlabEntry {
|
||||
let entry = self.entries.vacant_entry();
|
||||
ScopeSlabEntry {
|
||||
slab: &mut self.slab,
|
||||
entry,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, id: ScopeId) {
|
||||
self.slab.remove(self.entries.remove(id.0));
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, id: ScopeId) -> bool {
|
||||
self.entries.contains(id.0)
|
||||
}
|
||||
|
||||
pub(crate) fn iter(&self) -> impl Iterator<Item = &ScopeState> {
|
||||
self.entries.iter().map(|(_, slot)| unsafe { &*slot.ptr() })
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ScopeSlabEntry<'a> {
|
||||
slab: &'a mut BumpSlab<ScopeState>,
|
||||
entry: VacantEntry<'a, Slot<'static, ScopeState>>,
|
||||
}
|
||||
|
||||
impl<'a> ScopeSlabEntry<'a> {
|
||||
pub(crate) fn key(&self) -> ScopeId {
|
||||
ScopeId(self.entry.key())
|
||||
}
|
||||
|
||||
pub(crate) fn insert(self, scope: ScopeState) -> &'a ScopeState {
|
||||
let slot = self.slab.push(scope);
|
||||
// this is safe because the slot is only ever accessed with the lifetime of the borrow of the slab
|
||||
let slot = unsafe { std::mem::transmute(slot) };
|
||||
let entry = self.entry.insert(slot);
|
||||
unsafe { &*entry.ptr() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<ScopeId> for ScopeSlab {
|
||||
type Output = ScopeState;
|
||||
fn index(&self, id: ScopeId) -> &Self::Output {
|
||||
self.get(id).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl IndexMut<ScopeId> for ScopeSlab {
|
||||
fn index_mut(&mut self, id: ScopeId) -> &mut Self::Output {
|
||||
self.get_mut(id).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// A component's state separate from its props.
|
||||
///
|
||||
/// This struct exists to provide a common interface for all scopes without relying on generics.
|
||||
@@ -169,6 +76,7 @@ pub struct ScopeState {
|
||||
pub(crate) id: ScopeId,
|
||||
|
||||
pub(crate) height: u32,
|
||||
pub(crate) suspended: Cell<bool>,
|
||||
|
||||
pub(crate) hooks: RefCell<Vec<Box<UnsafeCell<dyn Any>>>>,
|
||||
pub(crate) hook_idx: Cell<usize>,
|
||||
@@ -182,7 +90,6 @@ pub struct ScopeState {
|
||||
pub(crate) attributes_to_drop: RefCell<Vec<*const Attribute<'static>>>,
|
||||
|
||||
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
|
||||
pub(crate) placeholder: Cell<Option<ElementId>>,
|
||||
}
|
||||
|
||||
impl<'src> ScopeState {
|
||||
@@ -574,9 +481,9 @@ impl<'src> ScopeState {
|
||||
/// fn(Scope<Props>) -> Element;
|
||||
/// async fn(Scope<Props<'_>>) -> Element;
|
||||
/// ```
|
||||
pub fn component<P, A, F: ComponentReturn<'src, A>>(
|
||||
pub fn component<P>(
|
||||
&'src self,
|
||||
component: fn(Scope<'src, P>) -> F,
|
||||
component: fn(Scope<'src, P>) -> Element<'src>,
|
||||
props: P,
|
||||
fn_name: &'static str,
|
||||
) -> DynamicNode<'src>
|
||||
@@ -655,6 +562,12 @@ impl<'src> ScopeState {
|
||||
None
|
||||
}
|
||||
|
||||
/// Mark this component as suspended and then return None
|
||||
pub fn suspend(&self) -> Option<Element> {
|
||||
self.suspended.set(true);
|
||||
None
|
||||
}
|
||||
|
||||
/// Store a value between renders. The foundational hook for all other hooks.
|
||||
///
|
||||
/// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render). The return value of this closure is stored for the lifetime of the component, and a mutable reference to it is provided on every render as the return value of `use_hook`.
|
||||
@@ -688,13 +601,13 @@ impl<'src> ScopeState {
|
||||
raw_ref.downcast_mut::<State>()
|
||||
})
|
||||
.expect(
|
||||
r###"
|
||||
r#"
|
||||
Unable to retrieve the hook that was initialized at this index.
|
||||
Consult the `rules of hooks` to understand how to use hooks properly.
|
||||
|
||||
You likely used the hook in a conditional. Hooks rely on consistent ordering between renders.
|
||||
Functions prefixed with "use" should never be called conditionally.
|
||||
"###,
|
||||
"#,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,17 @@
|
||||
use crate::{
|
||||
any_props::VProps,
|
||||
arena::{ElementId, ElementRef},
|
||||
innerlude::{DirtyScope, ErrorBoundary, Mutations, Scheduler, SchedulerMsg, ScopeSlab},
|
||||
innerlude::{DirtyScope, ErrorBoundary, Mutations, Scheduler, SchedulerMsg},
|
||||
mutations::Mutation,
|
||||
nodes::RenderReturn,
|
||||
nodes::{Template, TemplateId},
|
||||
scheduler::SuspenseId,
|
||||
scopes::{ScopeId, ScopeState},
|
||||
AttributeValue, Element, Event, Scope, SuspenseContext,
|
||||
AttributeValue, Element, Event, Scope,
|
||||
};
|
||||
use futures_util::{pin_mut, StreamExt};
|
||||
use rustc_hash::FxHashMap;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use slab::Slab;
|
||||
use std::{any::Any, borrow::BorrowMut, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
|
||||
use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
|
||||
|
||||
/// A virtual node system that progresses user events and diffs UI trees.
|
||||
///
|
||||
@@ -177,7 +176,7 @@ use std::{any::Any, borrow::BorrowMut, cell::Cell, collections::BTreeSet, future
|
||||
pub struct VirtualDom {
|
||||
// Maps a template path to a map of byteindexes to templates
|
||||
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
|
||||
pub(crate) scopes: ScopeSlab,
|
||||
pub(crate) scopes: Slab<Box<ScopeState>>,
|
||||
pub(crate) dirty_scopes: BTreeSet<DirtyScope>,
|
||||
pub(crate) scheduler: Rc<Scheduler>,
|
||||
|
||||
@@ -186,11 +185,9 @@ pub struct VirtualDom {
|
||||
|
||||
// While diffing we need some sort of way of breaking off a stream of suspended mutations.
|
||||
pub(crate) scope_stack: Vec<ScopeId>,
|
||||
pub(crate) collected_leaves: Vec<SuspenseId>,
|
||||
|
||||
// Whenever a suspense tree is finished, we push its boundary onto this stack.
|
||||
// When "render_with_deadline" is called, we pop the stack and return the mutations
|
||||
pub(crate) finished_fibers: Vec<ScopeId>,
|
||||
// Currently suspended scopes
|
||||
pub(crate) suspended_scopes: FxHashSet<ScopeId>,
|
||||
|
||||
pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>,
|
||||
|
||||
@@ -262,8 +259,7 @@ impl VirtualDom {
|
||||
elements: Default::default(),
|
||||
scope_stack: Vec::new(),
|
||||
dirty_scopes: BTreeSet::new(),
|
||||
collected_leaves: Vec::new(),
|
||||
finished_fibers: Vec::new(),
|
||||
suspended_scopes: FxHashSet::default(),
|
||||
mutations: Mutations::default(),
|
||||
};
|
||||
|
||||
@@ -272,12 +268,6 @@ impl VirtualDom {
|
||||
"app",
|
||||
);
|
||||
|
||||
// The root component is always a suspense boundary for any async children
|
||||
// This could be unexpected, so we might rethink this behavior later
|
||||
//
|
||||
// We *could* just panic if the suspense boundary is not found
|
||||
root.provide_context(Rc::new(SuspenseContext::new(ScopeId(0))));
|
||||
|
||||
// Unlike react, we provide a default error boundary that just renders the error as a string
|
||||
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId(0))));
|
||||
|
||||
@@ -291,14 +281,14 @@ impl VirtualDom {
|
||||
///
|
||||
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
|
||||
pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> {
|
||||
self.scopes.get(id)
|
||||
self.scopes.get(id.0).map(|f| f.as_ref())
|
||||
}
|
||||
|
||||
/// Get the single scope at the top of the VirtualDom tree that will always be around
|
||||
///
|
||||
/// This scope has a ScopeId of 0 and is the root of the tree
|
||||
pub fn base_scope(&self) -> &ScopeState {
|
||||
self.scopes.get(ScopeId(0)).unwrap()
|
||||
self.get_scope(ScopeId(0)).unwrap()
|
||||
}
|
||||
|
||||
/// Build the virtualdom with a global context inserted into the base scope
|
||||
@@ -313,31 +303,12 @@ impl VirtualDom {
|
||||
///
|
||||
/// Whenever the VirtualDom "works", it will re-render this scope
|
||||
pub fn mark_dirty(&mut self, id: ScopeId) {
|
||||
if let Some(scope) = self.scopes.get(id) {
|
||||
if let Some(scope) = self.get_scope(id) {
|
||||
let height = scope.height;
|
||||
self.dirty_scopes.insert(DirtyScope { height, id });
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine whether or not a scope is currently in a suspended state
|
||||
///
|
||||
/// This does not mean the scope is waiting on its own futures, just that the tree that the scope exists in is
|
||||
/// currently suspended.
|
||||
pub fn is_scope_suspended(&self, id: ScopeId) -> bool {
|
||||
!self.scopes[id]
|
||||
.consume_context::<Rc<SuspenseContext>>()
|
||||
.unwrap()
|
||||
.waiting_on
|
||||
.borrow()
|
||||
.is_empty()
|
||||
}
|
||||
|
||||
/// Determine if the tree is at all suspended. Used by SSR and other outside mechanisms to determine if the tree is
|
||||
/// ready to be rendered.
|
||||
pub fn has_suspended_work(&self) -> bool {
|
||||
!self.scheduler.leaves.borrow().is_empty()
|
||||
}
|
||||
|
||||
/// Call a listener inside the VirtualDom with data from outside the VirtualDom.
|
||||
///
|
||||
/// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
|
||||
@@ -485,7 +456,6 @@ impl VirtualDom {
|
||||
Some(msg) => match msg {
|
||||
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
|
||||
SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
|
||||
SchedulerMsg::SuspenseNotified(id) => self.handle_suspense_wakeup(id),
|
||||
},
|
||||
|
||||
// If they're not ready, then we should wait for them to be ready
|
||||
@@ -495,7 +465,7 @@ impl VirtualDom {
|
||||
Ok(None) => return,
|
||||
Err(_) => {
|
||||
// If we have any dirty scopes, or finished fiber trees then we should exit
|
||||
if !self.dirty_scopes.is_empty() || !self.finished_fibers.is_empty() {
|
||||
if !self.dirty_scopes.is_empty() || !self.suspended_scopes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -513,7 +483,6 @@ impl VirtualDom {
|
||||
match msg {
|
||||
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
|
||||
SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
|
||||
SchedulerMsg::SuspenseNotified(id) => self.handle_suspense_wakeup(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -527,7 +496,7 @@ impl VirtualDom {
|
||||
pub fn replace_template(&mut self, template: Template<'static>) {
|
||||
self.register_template_first_byte_index(template);
|
||||
// iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
|
||||
for scope in self.scopes.iter() {
|
||||
for (_, scope) in self.scopes.iter() {
|
||||
if let Some(RenderReturn::Ready(sync)) = scope.try_root_node() {
|
||||
if sync.template.get().name.rsplit_once(':').unwrap().0
|
||||
== template.name.rsplit_once(':').unwrap().0
|
||||
@@ -574,7 +543,6 @@ impl VirtualDom {
|
||||
}
|
||||
// If an error occurs, we should try to render the default error component and context where the error occured
|
||||
RenderReturn::Aborted(_placeholder) => panic!("Cannot catch errors during rebuild"),
|
||||
RenderReturn::Pending(_) => unreachable!("Root scope cannot be an async component"),
|
||||
}
|
||||
|
||||
self.finalize()
|
||||
@@ -598,6 +566,24 @@ impl VirtualDom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the virtual dom, waiting for all suspense to be finished
|
||||
///
|
||||
/// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
|
||||
pub async fn wait_for_suspense(&mut self) {
|
||||
loop {
|
||||
// println!("waiting for suspense {:?}", self.suspended_scopes);
|
||||
if self.suspended_scopes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// println!("waiting for suspense");
|
||||
self.wait_for_work().await;
|
||||
|
||||
// println!("Rendered immediately");
|
||||
_ = self.render_immediate();
|
||||
}
|
||||
}
|
||||
|
||||
/// Render what you can given the timeline and then move on
|
||||
///
|
||||
/// It's generally a good idea to put some sort of limit on the suspense process in case a future is having issues.
|
||||
@@ -609,70 +595,19 @@ impl VirtualDom {
|
||||
self.process_events();
|
||||
|
||||
loop {
|
||||
// first, unload any complete suspense trees
|
||||
for finished_fiber in self.finished_fibers.drain(..) {
|
||||
let scope = &self.scopes[finished_fiber];
|
||||
let context = scope.has_context::<Rc<SuspenseContext>>().unwrap();
|
||||
|
||||
self.mutations
|
||||
.templates
|
||||
.append(&mut context.mutations.borrow_mut().templates);
|
||||
|
||||
self.mutations
|
||||
.edits
|
||||
.append(&mut context.mutations.borrow_mut().edits);
|
||||
|
||||
// TODO: count how many nodes are on the stack?
|
||||
self.mutations.push(Mutation::ReplaceWith {
|
||||
id: context.placeholder.get().unwrap(),
|
||||
m: 1,
|
||||
})
|
||||
}
|
||||
|
||||
// Next, diff any dirty scopes
|
||||
// We choose not to poll the deadline since we complete pretty quickly anyways
|
||||
if let Some(dirty) = self.dirty_scopes.iter().next().cloned() {
|
||||
self.dirty_scopes.remove(&dirty);
|
||||
|
||||
// If the scope doesn't exist for whatever reason, then we should skip it
|
||||
if !self.scopes.contains(dirty.id) {
|
||||
if !self.scopes.contains(dirty.id.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// if the scope is currently suspended, then we should skip it, ignoring any tasks calling for an update
|
||||
if self.is_scope_suspended(dirty.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Save the current mutations length so we can split them into boundary
|
||||
let mutations_to_this_point = self.mutations.edits.len();
|
||||
|
||||
// Run the scope and get the mutations
|
||||
self.run_scope(dirty.id);
|
||||
self.diff_scope(dirty.id);
|
||||
|
||||
// If suspended leaves are present, then we should find the boundary for this scope and attach things
|
||||
// No placeholder necessary since this is a diff
|
||||
if !self.collected_leaves.is_empty() {
|
||||
let mut boundary = self.scopes[dirty.id]
|
||||
.consume_context::<Rc<SuspenseContext>>()
|
||||
.unwrap();
|
||||
|
||||
let boundary_mut = boundary.borrow_mut();
|
||||
|
||||
// Attach mutations
|
||||
boundary_mut
|
||||
.mutations
|
||||
.borrow_mut()
|
||||
.edits
|
||||
.extend(self.mutations.edits.split_off(mutations_to_this_point));
|
||||
|
||||
// Attach suspended leaves
|
||||
boundary
|
||||
.waiting_on
|
||||
.borrow_mut()
|
||||
.extend(self.collected_leaves.drain(..));
|
||||
}
|
||||
}
|
||||
|
||||
// If there's more work, then just continue, plenty of work to do
|
||||
@@ -680,11 +615,6 @@ impl VirtualDom {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If there's no pending suspense, then we have no reason to wait for anything
|
||||
if self.scheduler.leaves.borrow().is_empty() {
|
||||
return self.finalize();
|
||||
}
|
||||
|
||||
// Poll the suspense leaves in the meantime
|
||||
let mut work = self.wait_for_work();
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(not(miri))]
|
||||
|
||||
use dioxus::prelude::Props;
|
||||
use dioxus_core::*;
|
||||
use std::{cell::Cell, collections::HashSet};
|
||||
@@ -314,6 +316,7 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
|
||||
}
|
||||
|
||||
// test for panics when creating random nodes and templates
|
||||
#[cfg(not(miri))]
|
||||
#[test]
|
||||
fn create() {
|
||||
for _ in 0..1000 {
|
||||
@@ -325,6 +328,7 @@ fn create() {
|
||||
|
||||
// test for panics when diffing random nodes
|
||||
// This test will change the template every render which is not very realistic, but it helps stress the system
|
||||
#[cfg(not(miri))]
|
||||
#[test]
|
||||
fn diff() {
|
||||
for _ in 0..100000 {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
//! Tests related to safety of the library.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::SuspenseContext;
|
||||
|
||||
/// Ensure no issues with not calling rebuild
|
||||
#[test]
|
||||
@@ -17,8 +14,4 @@ fn root_node_isnt_null() {
|
||||
|
||||
// The height should be 0
|
||||
assert_eq!(scope.height(), 0);
|
||||
|
||||
// There should be a default suspense context
|
||||
// todo: there should also be a default error boundary
|
||||
assert!(scope.has_context::<Rc<SuspenseContext>>().is_some());
|
||||
}
|
||||
@@ -1,100 +1,43 @@
|
||||
use dioxus::core::ElementId;
|
||||
use dioxus::core::{Mutation::*, SuspenseContext};
|
||||
use dioxus::prelude::*;
|
||||
use std::future::IntoFuture;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
// wait just a moment, not enough time for the boundary to resolve
|
||||
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
let mut dom = VirtualDom::new(app);
|
||||
_ = dom.rebuild();
|
||||
dom.wait_for_suspense().await;
|
||||
let out = dioxus_ssr::pre_render(&dom);
|
||||
|
||||
{
|
||||
let mutations = dom.rebuild().santize();
|
||||
assert_eq!(out, "<div>Waiting for... child</div>");
|
||||
|
||||
// We should at least get the top-level template in before pausing for the children
|
||||
// note: we dont test template edits anymore
|
||||
// assert_eq!(
|
||||
// mutations.templates,
|
||||
// [
|
||||
// CreateElement { name: "div" },
|
||||
// CreateStaticText { value: "Waiting for child..." },
|
||||
// CreateStaticPlaceholder,
|
||||
// AppendChildren { m: 2 },
|
||||
// SaveTemplate { name: "template", m: 1 }
|
||||
// ]
|
||||
// );
|
||||
|
||||
// And we should load it in and assign the placeholder properly
|
||||
assert_eq!(
|
||||
mutations.edits,
|
||||
[
|
||||
LoadTemplate { name: "template", index: 0, id: ElementId(1) },
|
||||
// hmmmmmmmmm.... with suspense how do we guarantee that IDs increase linearly?
|
||||
// can we even?
|
||||
AssignId { path: &[1], id: ElementId(3) },
|
||||
AppendChildren { m: 1, id: ElementId(0) },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
dom.wait_for_work().await;
|
||||
dbg!(out);
|
||||
});
|
||||
}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
cx.render(rsx!(
|
||||
div {
|
||||
"Waiting for child..."
|
||||
suspense_boundary {}
|
||||
"Waiting for... "
|
||||
suspended_child {}
|
||||
}
|
||||
))
|
||||
}
|
||||
|
||||
fn suspense_boundary(cx: Scope) -> Element {
|
||||
cx.use_hook(|| {
|
||||
cx.provide_context(Rc::new(SuspenseContext::new(cx.scope_id())));
|
||||
});
|
||||
fn suspended_child(cx: Scope) -> Element {
|
||||
let val = use_state(cx, || 0);
|
||||
|
||||
// Ensure the right types are found
|
||||
cx.has_context::<Rc<SuspenseContext>>().unwrap();
|
||||
if **val < 3 {
|
||||
let mut val = val.clone();
|
||||
cx.spawn(async move {
|
||||
val += 1;
|
||||
});
|
||||
return cx.suspend()?;
|
||||
}
|
||||
|
||||
cx.render(rsx!(async_child {}))
|
||||
}
|
||||
|
||||
async fn async_child(cx: Scope<'_>) -> Element {
|
||||
use_future!(cx, || tokio::time::sleep(Duration::from_millis(10))).await;
|
||||
cx.render(rsx!(async_text {}))
|
||||
}
|
||||
|
||||
async fn async_text(cx: Scope<'_>) -> Element {
|
||||
let username = use_future!(cx, || async {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
"async child 1"
|
||||
});
|
||||
|
||||
let age = use_future!(cx, || async {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||
1234
|
||||
});
|
||||
|
||||
let (_user, _age) = use_future!(cx, || async {
|
||||
tokio::join!(
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)),
|
||||
tokio::time::sleep(std::time::Duration::from_secs(2))
|
||||
);
|
||||
("async child 1", 1234)
|
||||
})
|
||||
.await;
|
||||
|
||||
let (username, age) = tokio::join!(username.into_future(), age.into_future());
|
||||
|
||||
cx.render(rsx!( div { "Hello! {username}, you are {age}, {_user} {_age}" } ))
|
||||
render!("child")
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use std::time::Duration;
|
||||
use std::{sync::atomic::AtomicUsize, time::Duration};
|
||||
|
||||
static mut POLL_COUNT: usize = 0;
|
||||
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
#[cfg(not(miri))]
|
||||
#[tokio::test]
|
||||
async fn it_works() {
|
||||
let mut dom = VirtualDom::new(app);
|
||||
@@ -18,7 +19,10 @@ async fn it_works() {
|
||||
|
||||
// By the time the tasks are finished, we should've accumulated ticks from two tasks
|
||||
// Be warned that by setting the delay to too short, tokio might not schedule in the tasks
|
||||
assert_eq!(unsafe { POLL_COUNT }, 135);
|
||||
assert_eq!(
|
||||
POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed),
|
||||
135
|
||||
);
|
||||
}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
@@ -26,14 +30,14 @@ fn app(cx: Scope) -> Element {
|
||||
cx.spawn(async {
|
||||
for x in 0..10 {
|
||||
tokio::time::sleep(Duration::from_micros(50)).await;
|
||||
unsafe { POLL_COUNT += x }
|
||||
POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
cx.spawn(async {
|
||||
for x in 0..10 {
|
||||
tokio::time::sleep(Duration::from_micros(25)).await;
|
||||
unsafe { POLL_COUNT += x * 2 }
|
||||
POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.3.0"
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2018"
|
||||
description = "WebView renderer for Dioxus"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/desktop.html"
|
||||
keywords = ["dom", "ui", "gui", "react"]
|
||||
|
||||
@@ -8,6 +8,7 @@ pub(crate) struct FileDialogRequest {
|
||||
#[serde(default)]
|
||||
accept: Option<String>,
|
||||
multiple: bool,
|
||||
directory: bool,
|
||||
pub event: String,
|
||||
pub target: usize,
|
||||
pub bubbles: bool,
|
||||
@@ -36,30 +37,52 @@ pub(crate) fn get_file_event(_request: &FileDialogRequest) -> Vec<PathBuf> {
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
pub(crate) fn get_file_event(request: &FileDialogRequest) -> Vec<PathBuf> {
|
||||
let mut dialog = rfd::FileDialog::new();
|
||||
fn get_file_event_for_folder(
|
||||
request: &FileDialogRequest,
|
||||
dialog: rfd::FileDialog,
|
||||
) -> Vec<PathBuf> {
|
||||
if request.multiple {
|
||||
dialog.pick_folders().into_iter().flatten().collect()
|
||||
} else {
|
||||
dialog.pick_folder().into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
let filters: Vec<_> = request
|
||||
.accept
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.split(',')
|
||||
.filter_map(|s| Filters::from_str(s).ok())
|
||||
.collect();
|
||||
fn get_file_event_for_file(
|
||||
request: &FileDialogRequest,
|
||||
mut dialog: rfd::FileDialog,
|
||||
) -> Vec<PathBuf> {
|
||||
let filters: Vec<_> = request
|
||||
.accept
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.split(',')
|
||||
.filter_map(|s| Filters::from_str(s).ok())
|
||||
.collect();
|
||||
|
||||
let file_extensions: Vec<_> = filters
|
||||
.iter()
|
||||
.flat_map(|f| f.as_extensions().into_iter())
|
||||
.collect();
|
||||
let file_extensions: Vec<_> = filters
|
||||
.iter()
|
||||
.flat_map(|f| f.as_extensions().into_iter())
|
||||
.collect();
|
||||
|
||||
dialog = dialog.add_filter("name", file_extensions.as_slice());
|
||||
dialog = dialog.add_filter("name", file_extensions.as_slice());
|
||||
|
||||
let files: Vec<_> = if request.multiple {
|
||||
dialog.pick_files().into_iter().flatten().collect()
|
||||
let files: Vec<_> = if request.multiple {
|
||||
dialog.pick_files().into_iter().flatten().collect()
|
||||
} else {
|
||||
dialog.pick_file().into_iter().collect()
|
||||
};
|
||||
|
||||
files
|
||||
}
|
||||
|
||||
let dialog = rfd::FileDialog::new();
|
||||
|
||||
if request.directory {
|
||||
get_file_event_for_folder(request, dialog)
|
||||
} else {
|
||||
dialog.pick_file().into_iter().collect()
|
||||
};
|
||||
|
||||
files
|
||||
get_file_event_for_file(request, dialog)
|
||||
}
|
||||
}
|
||||
|
||||
enum Filters {
|
||||
|
||||
@@ -24,7 +24,7 @@ fn module_loader(root_name: &str) -> String {
|
||||
let target_id = find_real_id(target);
|
||||
if (target_id !== null) {
|
||||
const send = (event_name) => {
|
||||
const message = serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
|
||||
const message = serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), directory: target.getAttribute("webkitdirectory") === "true", multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
|
||||
window.ipc.postMessage(message);
|
||||
};
|
||||
send("change&input");
|
||||
|
||||
@@ -7,7 +7,7 @@ description = "TUI-based renderer for Dioxus"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/tui.html"
|
||||
keywords = ["dom", "ui", "gui", "react", "terminal"]
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
dioxus = { workspace = true }
|
||||
|
||||
@@ -20,7 +20,7 @@ fn app(cx: Scope) -> Element {
|
||||
background_color: "hsl({hue}, 70%, {brightness}%)",
|
||||
onmousemove: move |evt| {
|
||||
if let RenderReturn::Ready(node) = cx.root_node() {
|
||||
if let Some(id) = node.root_ids.get(0){
|
||||
if let Some(id) = node.root_ids.borrow().get(0).cloned() {
|
||||
let node = tui_query.get(mapping.get_node_id(id).unwrap());
|
||||
let Size{width, height} = node.size().unwrap();
|
||||
let pos = evt.inner().element_coordinates();
|
||||
|
||||
Generated
+8
-8
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dioxus",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.2",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dioxus",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dioxus-ext": "./pkg",
|
||||
@@ -3720,9 +3720,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/word-wrap": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",
|
||||
"integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==",
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.4.tgz",
|
||||
"integrity": "sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -6444,9 +6444,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"word-wrap": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",
|
||||
"integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==",
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.4.tgz",
|
||||
"integrity": "sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA==",
|
||||
"dev": true
|
||||
},
|
||||
"wrappy": {
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.3.0"
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2018"
|
||||
description = "Global state management for Dioxus"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com"
|
||||
keywords = ["dom", "ui", "gui", "react", "state-management"]
|
||||
|
||||
+10
-10
@@ -1,4 +1,3 @@
|
||||
|
||||
<div align="center">
|
||||
<h1>Fermi ⚛</h1>
|
||||
<p>
|
||||
@@ -6,7 +5,6 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
<div align="center">
|
||||
<!-- Crates version -->
|
||||
<a href="https://crates.io/crates/fermi">
|
||||
@@ -30,21 +28,21 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
-----
|
||||
---
|
||||
|
||||
Fermi is a global state management solution for Dioxus that's as easy as `use_state`.
|
||||
|
||||
Inspired by atom-based state management solutions, all state in Fermi starts as an `atom`:
|
||||
|
||||
```rust, ignore
|
||||
static NAME: Atom<&str> = |_| "Dioxus";
|
||||
static NAME: Atom<&str> = Atom(|_| "Dioxus");
|
||||
```
|
||||
|
||||
From anywhere in our app, we can read the value of our atom:
|
||||
|
||||
```rust, ignores
|
||||
```rust, ignore
|
||||
fn NameCard(cx: Scope) -> Element {
|
||||
let name = use_read(cx, NAME);
|
||||
let name = use_read(cx, &NAME);
|
||||
cx.render(rsx!{ h1 { "Hello, {name}"} })
|
||||
}
|
||||
```
|
||||
@@ -53,7 +51,7 @@ We can also set the value of our atom, also from anywhere in our app:
|
||||
|
||||
```rust, ignore
|
||||
fn NameCard(cx: Scope) -> Element {
|
||||
let set_name = use_set(cx, NAME);
|
||||
let set_name = use_set(cx, &NAME);
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| set_name("Fermi"),
|
||||
@@ -66,10 +64,10 @@ fn NameCard(cx: Scope) -> Element {
|
||||
If needed, we can update the atom's value, based on itself:
|
||||
|
||||
```rust, ignore
|
||||
static COUNT: Atom<i32> = |_| 0;
|
||||
static COUNT: Atom<i32> = Atom(|_| 0);
|
||||
|
||||
fn Counter(cx: Scope) -> Element {
|
||||
let mut count = use_atom_state(cx, COUNT);
|
||||
let mut count = use_atom_state(cx, &COUNT);
|
||||
|
||||
cx.render(rsx!{
|
||||
p {
|
||||
@@ -86,6 +84,7 @@ fn Counter(cx: Scope) -> Element {
|
||||
It's that simple!
|
||||
|
||||
## Installation
|
||||
|
||||
Fermi is currently under construction, so you have to use the `master` branch to get started.
|
||||
|
||||
```toml
|
||||
@@ -93,10 +92,10 @@ Fermi is currently under construction, so you have to use the `master` branch to
|
||||
fermi = { git = "https://github.com/dioxuslabs/dioxus" }
|
||||
```
|
||||
|
||||
|
||||
## Running examples
|
||||
|
||||
The examples here use Dioxus Desktop to showcase their functionality. To run an example, use
|
||||
|
||||
```sh
|
||||
$ cargo run --example fermi
|
||||
```
|
||||
@@ -104,6 +103,7 @@ $ cargo run --example fermi
|
||||
## Features
|
||||
|
||||
Broadly our feature set required to be released includes:
|
||||
|
||||
- [x] Support for Atoms
|
||||
- [x] Support for AtomRef (for values that aren't `Clone`)
|
||||
- [ ] Support for Atom Families
|
||||
|
||||
@@ -1,24 +1,21 @@
|
||||
use crate::{AtomId, AtomRoot, Readable, Writable};
|
||||
|
||||
pub type Atom<T> = fn(AtomBuilder) -> T;
|
||||
pub struct Atom<T>(pub fn(AtomBuilder) -> T);
|
||||
pub struct AtomBuilder;
|
||||
|
||||
impl<V: 'static> Readable<V> for Atom<V> {
|
||||
impl<V> Readable<V> for &'static Atom<V> {
|
||||
fn read(&self, _root: AtomRoot) -> Option<V> {
|
||||
todo!()
|
||||
}
|
||||
fn init(&self) -> V {
|
||||
(*self)(AtomBuilder)
|
||||
self.0(AtomBuilder)
|
||||
}
|
||||
fn unique_id(&self) -> AtomId {
|
||||
AtomId {
|
||||
ptr: *self as *const (),
|
||||
type_id: std::any::TypeId::of::<V>(),
|
||||
}
|
||||
*self as *const Atom<V> as *const ()
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: 'static> Writable<V> for Atom<V> {
|
||||
impl<V> Writable<V> for &'static Atom<V> {
|
||||
fn write(&self, _root: AtomRoot, _value: V) {
|
||||
todo!()
|
||||
}
|
||||
@@ -26,6 +23,22 @@ impl<V: 'static> Writable<V> for Atom<V> {
|
||||
|
||||
#[test]
|
||||
fn atom_compiles() {
|
||||
static TEST_ATOM: Atom<&str> = |_| "hello";
|
||||
dbg!(TEST_ATOM.init());
|
||||
static TEST_ATOM: Atom<&str> = Atom(|_| "hello");
|
||||
dbg!((&TEST_ATOM).init());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atom_is_unique() {
|
||||
static TEST_ATOM_1: Atom<&str> = Atom(|_| "hello");
|
||||
static TEST_ATOM_2: Atom<&str> = Atom(|_| "hello");
|
||||
assert_eq!((&TEST_ATOM_1).unique_id(), (&TEST_ATOM_1).unique_id());
|
||||
assert_ne!((&TEST_ATOM_1).unique_id(), (&TEST_ATOM_2).unique_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atom_is_unique_2() {
|
||||
struct S(String);
|
||||
static TEST_ATOM_1: Atom<Vec<S>> = Atom(|_| Vec::new());
|
||||
static TEST_ATOM_2: Atom<Vec<String>> = Atom(|_| Vec::new());
|
||||
assert_ne!((&TEST_ATOM_1).unique_id(), (&TEST_ATOM_2).unique_id());
|
||||
}
|
||||
@@ -2,26 +2,23 @@ use crate::{AtomId, AtomRoot, Readable, Writable};
|
||||
use im_rc::HashMap as ImMap;
|
||||
|
||||
pub struct AtomFamilyBuilder;
|
||||
pub type AtomFamily<K, V> = fn(AtomFamilyBuilder) -> ImMap<K, V>;
|
||||
pub struct AtomFamily<K, V>(pub fn(AtomFamilyBuilder) -> ImMap<K, V>);
|
||||
|
||||
impl<K, V: 'static> Readable<ImMap<K, V>> for AtomFamily<K, V> {
|
||||
impl<K, V> Readable<ImMap<K, V>> for &'static AtomFamily<K, V> {
|
||||
fn read(&self, _root: AtomRoot) -> Option<ImMap<K, V>> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn init(&self) -> ImMap<K, V> {
|
||||
(*self)(AtomFamilyBuilder)
|
||||
self.0(AtomFamilyBuilder)
|
||||
}
|
||||
|
||||
fn unique_id(&self) -> AtomId {
|
||||
AtomId {
|
||||
ptr: *self as *const (),
|
||||
type_id: std::any::TypeId::of::<V>(),
|
||||
}
|
||||
*self as *const AtomFamily<K, V> as *const ()
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V: 'static> Writable<ImMap<K, V>> for AtomFamily<K, V> {
|
||||
impl<K, V> Writable<ImMap<K, V>> for &'static AtomFamily<K, V> {
|
||||
fn write(&self, _root: AtomRoot, _value: ImMap<K, V>) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
@@ -2,27 +2,24 @@ use crate::{AtomId, AtomRoot, Readable};
|
||||
use std::cell::RefCell;
|
||||
|
||||
pub struct AtomRefBuilder;
|
||||
pub type AtomRef<T> = fn(AtomRefBuilder) -> T;
|
||||
pub struct AtomRef<T>(pub fn(AtomRefBuilder) -> T);
|
||||
|
||||
impl<V: 'static> Readable<RefCell<V>> for AtomRef<V> {
|
||||
impl<V> Readable<RefCell<V>> for &'static AtomRef<V> {
|
||||
fn read(&self, _root: AtomRoot) -> Option<RefCell<V>> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn init(&self) -> RefCell<V> {
|
||||
RefCell::new((*self)(AtomRefBuilder))
|
||||
RefCell::new(self.0(AtomRefBuilder))
|
||||
}
|
||||
|
||||
fn unique_id(&self) -> AtomId {
|
||||
AtomId {
|
||||
ptr: *self as *const (),
|
||||
type_id: std::any::TypeId::of::<V>(),
|
||||
}
|
||||
*self as *const AtomRef<V> as *const ()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atom_compiles() {
|
||||
static TEST_ATOM: AtomRef<Vec<String>> = |_| vec![];
|
||||
dbg!(TEST_ATOM.init());
|
||||
static TEST_ATOM: AtomRef<Vec<String>> = AtomRef(|_| vec![]);
|
||||
dbg!((&TEST_ATOM).init());
|
||||
}
|
||||
@@ -13,7 +13,10 @@ use std::{
|
||||
///
|
||||
///
|
||||
///
|
||||
pub fn use_atom_ref<T: 'static>(cx: &ScopeState, atom: AtomRef<T>) -> &UseAtomRef<T> {
|
||||
pub fn use_atom_ref<'a, T: 'static>(
|
||||
cx: &'a ScopeState,
|
||||
atom: &'static AtomRef<T>,
|
||||
) -> &'a UseAtomRef<T> {
|
||||
let root = use_atom_root(cx);
|
||||
|
||||
&cx.use_hook(|| {
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::{
|
||||
/// static COUNT: Atom<u32> = |_| 0;
|
||||
///
|
||||
/// fn Example(cx: Scope) -> Element {
|
||||
/// let mut count = use_atom_state(cx, COUNT);
|
||||
/// let mut count = use_atom_state(cx, &COUNT);
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
/// div {
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
|
||||
|
||||
use dioxus_core::ScopeId;
|
||||
use im_rc::HashSet;
|
||||
|
||||
use crate::Readable;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct AtomId {
|
||||
pub ptr: *const (),
|
||||
pub type_id: TypeId,
|
||||
}
|
||||
pub type AtomId = *const ();
|
||||
|
||||
pub struct AtomRoot {
|
||||
pub atoms: RefCell<HashMap<AtomId, Slot>>,
|
||||
@@ -54,15 +44,7 @@ impl AtomRoot {
|
||||
// initialize the value if it's not already initialized
|
||||
if let Some(slot) = atoms.get_mut(&f.unique_id()) {
|
||||
slot.subscribers.insert(scope);
|
||||
match slot.value.clone().downcast() {
|
||||
Ok(res) => res,
|
||||
Err(e) => panic!(
|
||||
"Downcasting atom failed: {:?}. Has typeid of {:?} but needs typeid of {:?}",
|
||||
f.unique_id(),
|
||||
e.type_id(),
|
||||
TypeId::of::<V>()
|
||||
),
|
||||
}
|
||||
slot.value.clone().downcast().unwrap()
|
||||
} else {
|
||||
let value = Rc::new(f.init());
|
||||
let mut subscribers = HashSet::new();
|
||||
|
||||
@@ -3,35 +3,40 @@ name = "dioxus-fullstack"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Fullstack Dioxus Utilities"
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/DioxusLabs/dioxus/"
|
||||
homepage = "https://dioxuslabs.com"
|
||||
keywords = ["dom", "ui", "gui", "react", "ssr", "fullstack"]
|
||||
|
||||
[dependencies]
|
||||
# server functions
|
||||
server_fn = { git = "https://github.com/leptos-rs/leptos", rev = "15a4e54435eb5a539afb75891292bcccd2cc8e85", default-features = false, features = ["stable"] }
|
||||
server_fn = { git = "https://github.com/leptos-rs/leptos", rev = "6b90e1babd425c9a324181c86e3fd1b942c9b10f", default-features = false }
|
||||
dioxus_server_macro = { path = "server-macro" }
|
||||
|
||||
# warp
|
||||
warp = { version = "0.3.3", optional = true }
|
||||
warp = { version = "0.3.5", features = ["compression-gzip"], optional = true }
|
||||
http-body = { version = "0.4.5", optional = true }
|
||||
http-body-util = "0.1.0-rc.2"
|
||||
|
||||
# axum
|
||||
axum = { version = "0.6.1", features = ["ws"], optional = true }
|
||||
tower-http = { version = "0.4.0", optional = true, features = ["fs"] }
|
||||
axum = { version = "0.6.1", features = ["ws", "macros"], optional = true }
|
||||
tower-http = { version = "0.4.0", optional = true, features = ["fs", "compression-gzip"] }
|
||||
tower = { version = "0.4.13", features = ["util"], optional = true }
|
||||
axum-macros = "0.3.7"
|
||||
|
||||
# salvo
|
||||
salvo = { version = "0.37.7", optional = true, features = ["serve-static", "ws"] }
|
||||
salvo = { version = "0.46.0", optional = true, features = ["serve-static", "websocket", "compression"] }
|
||||
serde = "1.0.159"
|
||||
|
||||
# Dioxus + SSR
|
||||
dioxus-core = { workspace = true }
|
||||
dioxus = { workspace = true }
|
||||
dioxus-ssr = { workspace = true, optional = true }
|
||||
hyper = { version = "0.14.25", optional = true }
|
||||
http = { version = "0.2.9", optional = true }
|
||||
|
||||
# Router Intigration
|
||||
dioxus-router = { workspace = true, optional = true }
|
||||
|
||||
log = { workspace = true }
|
||||
once_cell = "1.17.1"
|
||||
thiserror = { workspace = true }
|
||||
@@ -43,9 +48,13 @@ serde_json = { version = "1.0.95", optional = true }
|
||||
tokio-stream = { version = "0.1.12", features = ["sync"], optional = true }
|
||||
futures-util = { workspace = true, optional = true }
|
||||
postcard = { version = "1.0.4", features = ["use-std"] }
|
||||
yazi = "0.1.5"
|
||||
base64 = "0.21.0"
|
||||
|
||||
pin-project = "1.1.2"
|
||||
async-trait = "0.1.71"
|
||||
bytes = "1.4.0"
|
||||
tower-layer = "0.3.2"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
dioxus-hot-reload = { workspace = true }
|
||||
|
||||
@@ -54,10 +63,14 @@ web-sys = { version = "0.3.61", features = ["Window", "Document", "Element", "Ht
|
||||
|
||||
[features]
|
||||
default = ["hot-reload", "default-tls"]
|
||||
hot-reload = ["serde_json", "tokio-stream", "futures-util"]
|
||||
warp = ["dep:warp", "http-body", "ssr"]
|
||||
router = ["dioxus-router"]
|
||||
hot-reload = ["serde_json", "futures-util"]
|
||||
warp = ["dep:warp", "ssr"]
|
||||
axum = ["dep:axum", "tower-http", "ssr"]
|
||||
salvo = ["dep:salvo", "ssr"]
|
||||
ssr = ["server_fn/ssr", "tokio", "dioxus-ssr", "hyper", "http"]
|
||||
ssr = ["server_fn/ssr", "tokio", "dioxus-ssr", "tower", "hyper", "http", "http-body", "dioxus-router/ssr", "tokio-stream"]
|
||||
default-tls = ["server_fn/default-tls"]
|
||||
rustls = ["server_fn/rustls"]
|
||||
|
||||
[dev-dependencies]
|
||||
dioxus-fullstack = { path = ".", features = ["router"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
dist
|
||||
target
|
||||
static
|
||||
@@ -0,0 +1,53 @@
|
||||
[package]
|
||||
name = "axum-auth"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
dioxus-web = { workspace = true, features = ["hydrate"], optional = true }
|
||||
dioxus = { workspace = true }
|
||||
dioxus-fullstack = { workspace = true }
|
||||
axum = { version = "0.6.12", optional = true }
|
||||
tokio = { workspace = true, features = ["full"], optional = true }
|
||||
serde = "1.0.159"
|
||||
execute = "0.2.12"
|
||||
tower-http = { version = "0.4.1", features = ["auth"], optional = true }
|
||||
simple_logger = { version = "4.2.0", optional = true }
|
||||
async-trait = { version = "0.1.71", optional = true }
|
||||
sqlx = { version = "0.7.0", features = [
|
||||
"macros",
|
||||
"migrate",
|
||||
"postgres",
|
||||
"sqlite",
|
||||
"_unstable-all-types",
|
||||
"tls-rustls",
|
||||
"runtime-tokio",
|
||||
], optional = true }
|
||||
anyhow = "1.0.71"
|
||||
http = { version = "0.2.9", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
|
||||
[dependencies.axum_session]
|
||||
version = "0.3.0"
|
||||
features = ["sqlite-rustls"]
|
||||
optional = true
|
||||
|
||||
[dependencies.axum_session_auth]
|
||||
version = "0.3.0"
|
||||
features = ["sqlite-rustls"]
|
||||
optional = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
ssr = ["axum", "tokio", "dioxus-fullstack/axum", "tower-http", "simple_logger", "async-trait", "sqlx", "axum_session", "axum_session_auth", "http", "tower"]
|
||||
web = ["dioxus-web"]
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
panic = "abort"
|
||||
opt-level = 'z'
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
@@ -0,0 +1,262 @@
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
http::Method,
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use axum_session::{SessionConfig, SessionLayer, SessionSqlitePool, SessionStore};
|
||||
use axum_session_auth::*;
|
||||
use core::pin::Pin;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
|
||||
use std::error::Error;
|
||||
use std::future::Future;
|
||||
use std::{collections::HashSet, net::SocketAddr, str::FromStr};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
pub anonymous: bool,
|
||||
pub username: String,
|
||||
pub permissions: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Clone)]
|
||||
pub struct SqlPermissionTokens {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
impl Default for User {
|
||||
fn default() -> Self {
|
||||
let mut permissions = HashSet::new();
|
||||
|
||||
permissions.insert("Category::View".to_owned());
|
||||
|
||||
Self {
|
||||
id: 1,
|
||||
anonymous: true,
|
||||
username: "Guest".into(),
|
||||
permissions,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Authentication<User, i64, SqlitePool> for User {
|
||||
async fn load_user(userid: i64, pool: Option<&SqlitePool>) -> Result<User, anyhow::Error> {
|
||||
let pool = pool.unwrap();
|
||||
|
||||
User::get_user(userid, pool)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("Could not load user"))
|
||||
}
|
||||
|
||||
fn is_authenticated(&self) -> bool {
|
||||
!self.anonymous
|
||||
}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
!self.anonymous
|
||||
}
|
||||
|
||||
fn is_anonymous(&self) -> bool {
|
||||
self.anonymous
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HasPermission<SqlitePool> for User {
|
||||
async fn has(&self, perm: &str, _pool: &Option<&SqlitePool>) -> bool {
|
||||
self.permissions.contains(perm)
|
||||
}
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub async fn get_user(id: i64, pool: &SqlitePool) -> Option<Self> {
|
||||
let sqluser = sqlx::query_as::<_, SqlUser>("SELECT * FROM users WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
//lets just get all the tokens the user can use, we will only use the full permissions if modifing them.
|
||||
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
|
||||
"SELECT token FROM user_permissions WHERE user_id = $1;",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
Some(sqluser.into_user(Some(sql_user_perms)))
|
||||
}
|
||||
|
||||
pub async fn create_user_tables(pool: &SqlitePool) {
|
||||
sqlx::query(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
"id" INTEGER PRIMARY KEY,
|
||||
"anonymous" BOOLEAN NOT NULL,
|
||||
"username" VARCHAR(256) NOT NULL
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS user_permissions (
|
||||
"user_id" INTEGER NOT NULL,
|
||||
"token" VARCHAR(256) NOT NULL
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO users
|
||||
(id, anonymous, username) SELECT 1, true, 'Guest'
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
anonymous = EXCLUDED.anonymous,
|
||||
username = EXCLUDED.username
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO users
|
||||
(id, anonymous, username) SELECT 2, false, 'Test'
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
anonymous = EXCLUDED.anonymous,
|
||||
username = EXCLUDED.username
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO user_permissions
|
||||
(user_id, token) SELECT 2, 'Category::View'
|
||||
"#,
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Clone)]
|
||||
pub struct SqlUser {
|
||||
pub id: i32,
|
||||
pub anonymous: bool,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
impl SqlUser {
|
||||
pub fn into_user(self, sql_user_perms: Option<Vec<SqlPermissionTokens>>) -> User {
|
||||
User {
|
||||
id: self.id,
|
||||
anonymous: self.anonymous,
|
||||
username: self.username,
|
||||
permissions: if let Some(user_perms) = sql_user_perms {
|
||||
user_perms
|
||||
.into_iter()
|
||||
.map(|x| x.token)
|
||||
.collect::<HashSet<String>>()
|
||||
} else {
|
||||
HashSet::<String>::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn connect_to_database() -> SqlitePool {
|
||||
let connect_opts = SqliteConnectOptions::from_str("sqlite::memory:").unwrap();
|
||||
|
||||
SqlitePoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect_with(connect_opts)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub struct Session(
|
||||
pub axum_session_auth::AuthSession<
|
||||
crate::auth::User,
|
||||
i64,
|
||||
axum_session_auth::SessionSqlitePool,
|
||||
sqlx::SqlitePool,
|
||||
>,
|
||||
);
|
||||
|
||||
impl std::ops::Deref for Session {
|
||||
type Target = axum_session_auth::AuthSession<
|
||||
crate::auth::User,
|
||||
i64,
|
||||
axum_session_auth::SessionSqlitePool,
|
||||
sqlx::SqlitePool,
|
||||
>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for Session {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthSessionLayerNotFound;
|
||||
|
||||
impl std::fmt::Display for AuthSessionLayerNotFound {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "AuthSessionLayer was not found")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AuthSessionLayerNotFound {}
|
||||
|
||||
impl IntoResponse for AuthSessionLayerNotFound {
|
||||
fn into_response(self) -> Response {
|
||||
(
|
||||
http::status::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"AuthSessionLayer was not found",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S: std::marker::Sync + std::marker::Send> axum::extract::FromRequestParts<S> for Session {
|
||||
type Rejection = AuthSessionLayerNotFound;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut http::request::Parts,
|
||||
state: &S,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
axum_session_auth::AuthSession::<
|
||||
crate::auth::User,
|
||||
i64,
|
||||
axum_session_auth::SessionSqlitePool,
|
||||
sqlx::SqlitePool,
|
||||
>::from_request_parts(parts, state)
|
||||
.await
|
||||
.map(Session)
|
||||
.map_err(|_| AuthSessionLayerNotFound)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case, unused)]
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
mod auth;
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "web")]
|
||||
// Hydrate the application on the client
|
||||
dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true));
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
use crate::auth::*;
|
||||
use axum::routing::*;
|
||||
use axum_session::SessionConfig;
|
||||
use axum_session::SessionStore;
|
||||
use axum_session_auth::AuthConfig;
|
||||
use axum_session_auth::SessionSqlitePool;
|
||||
simple_logger::SimpleLogger::new().init().unwrap();
|
||||
tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(async move {
|
||||
let pool = connect_to_database().await;
|
||||
|
||||
//This Defaults as normal Cookies.
|
||||
//To enable Private cookies for integrity, and authenticity please check the next Example.
|
||||
let session_config = SessionConfig::default().with_table_name("test_table");
|
||||
let auth_config = AuthConfig::<i64>::default().with_anonymous_user_id(Some(1));
|
||||
let session_store = SessionStore::<SessionSqlitePool>::new(
|
||||
Some(pool.clone().into()),
|
||||
session_config,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
//Create the Database table for storing our Session Data.
|
||||
session_store.initiate().await.unwrap();
|
||||
User::create_user_tables(&pool).await;
|
||||
|
||||
// build our application with some routes
|
||||
let app = Router::new()
|
||||
// Server side render the application, serve static assets, and register server functions
|
||||
.serve_dioxus_application("", ServeConfigBuilder::new(app, ()))
|
||||
.layer(
|
||||
axum_session_auth::AuthSessionLayer::<
|
||||
crate::auth::User,
|
||||
i64,
|
||||
axum_session_auth::SessionSqlitePool,
|
||||
sqlx::SqlitePool,
|
||||
>::new(Some(pool))
|
||||
.with_config(auth_config),
|
||||
)
|
||||
.layer(axum_session::SessionLayer::new(session_store));
|
||||
|
||||
// run it
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
let user_name = use_state(cx, || "?".to_string());
|
||||
let permissions = use_state(cx, || "?".to_string());
|
||||
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
button {
|
||||
onclick: move |_| {
|
||||
async move {
|
||||
login().await.unwrap();
|
||||
}
|
||||
},
|
||||
"Login Test User"
|
||||
}
|
||||
}
|
||||
div {
|
||||
button {
|
||||
onclick: move |_| {
|
||||
to_owned![user_name];
|
||||
async move {
|
||||
if let Ok(data) = get_user_name().await {
|
||||
user_name.set(data);
|
||||
}
|
||||
}
|
||||
},
|
||||
"Get User Name"
|
||||
}
|
||||
"User name: {user_name}"
|
||||
}
|
||||
div {
|
||||
button {
|
||||
onclick: move |_| {
|
||||
to_owned![permissions];
|
||||
async move {
|
||||
if let Ok(data) = get_permissions().await {
|
||||
permissions.set(data);
|
||||
}
|
||||
}
|
||||
},
|
||||
"Get Permissions"
|
||||
}
|
||||
"Permissions: {permissions}"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[server(GetUserName)]
|
||||
pub async fn get_user_name() -> Result<String, ServerFnError> {
|
||||
let session: crate::auth::Session = extract().await?;
|
||||
Ok(session.0.current_user.unwrap().username.to_string())
|
||||
}
|
||||
|
||||
#[server(Login)]
|
||||
pub async fn login() -> Result<(), ServerFnError> {
|
||||
let auth: crate::auth::Session = extract().await?;
|
||||
auth.login_user(2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[server(Permissions)]
|
||||
pub async fn get_permissions() -> Result<String, ServerFnError> {
|
||||
let method: axum::http::Method = extract().await?;
|
||||
let auth: crate::auth::Session = extract().await?;
|
||||
let current_user = auth.current_user.clone().unwrap_or_default();
|
||||
|
||||
// lets check permissions only and not worry about if they are anon or not
|
||||
if !axum_session_auth::Auth::<crate::auth::User, i64, sqlx::SqlitePool>::build(
|
||||
[axum::http::Method::POST],
|
||||
false,
|
||||
)
|
||||
.requires(axum_session_auth::Rights::any([
|
||||
axum_session_auth::Rights::permission("Category::View"),
|
||||
axum_session_auth::Rights::permission("Admin::View"),
|
||||
]))
|
||||
.validate(¤t_user, &method, None)
|
||||
.await
|
||||
{
|
||||
return Ok(format!(
|
||||
"User {}, Does not have permissions needed to view this page please login",
|
||||
current_user.username
|
||||
));
|
||||
}
|
||||
|
||||
Ok(format!(
|
||||
"User has Permissions needed. Here are the Users permissions: {:?}",
|
||||
current_user.permissions
|
||||
))
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Run with:
|
||||
// ```bash
|
||||
// cargo run --bin client --features="desktop"
|
||||
// cargo run --bin client --features desktop
|
||||
// ```
|
||||
|
||||
use axum_desktop::*;
|
||||
@@ -8,6 +8,6 @@ use dioxus_fullstack::prelude::server_fn::set_server_url;
|
||||
|
||||
fn main() {
|
||||
// Set the url of the server where server functions are hosted.
|
||||
set_server_url("http://localhost:8080");
|
||||
set_server_url("http://127.0.0.0:8080");
|
||||
dioxus_desktop::launch(app)
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
// Run with:
|
||||
// ```bash
|
||||
// cargo run --bin server --features="ssr"
|
||||
// cargo run --bin server --features ssr
|
||||
// ```
|
||||
|
||||
use axum_desktop::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
dist
|
||||
target
|
||||
target
|
||||
static
|
||||
@@ -7,15 +7,24 @@ publish = false
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
dioxus-web = { workspace = true, features=["hydrate"], optional = true }
|
||||
dioxus-web = { workspace = true, features = ["hydrate"], optional = true }
|
||||
dioxus = { workspace = true }
|
||||
dioxus-fullstack = { workspace = true }
|
||||
axum = { version = "0.6.12", optional = true }
|
||||
tokio = { workspace = true, features = ["full"], optional = true }
|
||||
serde = "1.0.159"
|
||||
execute = "0.2.12"
|
||||
tower-http = { version = "0.4.1", features = ["auth"] }
|
||||
simple_logger = "4.2.0"
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
default = []
|
||||
ssr = ["axum", "tokio", "dioxus-fullstack/axum"]
|
||||
web = ["dioxus-web"]
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
panic = "abort"
|
||||
opt-level = 'z'
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
@@ -1,56 +1,15 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dioxus build --features web
|
||||
//! cargo run --features ssr --no-default-features
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_snake_case, unused)]
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use dioxus_fullstack::{launch, prelude::*};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "web")]
|
||||
dioxus_web::launch_with_props(
|
||||
app,
|
||||
get_root_props_from_document().unwrap_or_default(),
|
||||
dioxus_web::Config::new().hydrate(true),
|
||||
);
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
// Start hot reloading
|
||||
hot_reload_init!(dioxus_hot_reload::Config::new().with_rebuild_callback(|| {
|
||||
execute::shell("dioxus build --features web")
|
||||
.spawn()
|
||||
.unwrap()
|
||||
.wait()
|
||||
.unwrap();
|
||||
execute::shell("cargo run --features ssr --no-default-features")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
true
|
||||
}));
|
||||
|
||||
tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(async move {
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
|
||||
axum::Server::bind(&addr)
|
||||
.serve(
|
||||
axum::Router::new()
|
||||
.serve_dioxus_application(
|
||||
"",
|
||||
ServeConfigBuilder::new(app, AppProps { count: 12345 }).build(),
|
||||
)
|
||||
.into_make_service(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
|
||||
struct AppProps {
|
||||
count: i32,
|
||||
@@ -67,12 +26,11 @@ fn app(cx: Scope<AppProps>) -> Element {
|
||||
button {
|
||||
onclick: move |_| {
|
||||
to_owned![text];
|
||||
let sc = cx.sc();
|
||||
async move {
|
||||
if let Ok(data) = get_server_data().await {
|
||||
println!("Client received: {}", data);
|
||||
text.set(data.clone());
|
||||
post_server_data(sc, data).await.unwrap();
|
||||
post_server_data(data).await.unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -83,12 +41,10 @@ fn app(cx: Scope<AppProps>) -> Element {
|
||||
}
|
||||
|
||||
#[server(PostServerData)]
|
||||
async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
|
||||
// The server context contains information about the current request and allows you to modify the response.
|
||||
cx.response_headers_mut()
|
||||
.insert("Set-Cookie", "foo=bar".parse().unwrap());
|
||||
async fn post_server_data(data: String) -> Result<(), ServerFnError> {
|
||||
let axum::extract::Host(host): axum::extract::Host = extract()?;
|
||||
println!("Server received: {}", data);
|
||||
println!("Request parts are {:?}", cx.request_parts());
|
||||
println!("{:?}", host);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -97,3 +53,9 @@ async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), S
|
||||
async fn get_server_data() -> Result<String, ServerFnError> {
|
||||
Ok("Hello from the server!".to_string())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
launch!(@([127, 0, 0, 1], 8080), app, {
|
||||
serve_cfg: ServeConfigBuilder::new(app, AppProps { count: 0 }),
|
||||
});
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
dist
|
||||
target
|
||||
target
|
||||
static
|
||||
@@ -7,18 +7,15 @@ publish = false
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
dioxus-web = { workspace = true, features=["hydrate"], optional = true }
|
||||
dioxus-web = { workspace = true, features = ["hydrate"], optional = true }
|
||||
dioxus = { workspace = true }
|
||||
dioxus-router = { workspace = true }
|
||||
dioxus-fullstack = { workspace = true }
|
||||
dioxus-router = { workspace = true}
|
||||
dioxus-fullstack = { workspace = true, features = ["router"] }
|
||||
axum = { version = "0.6.12", optional = true }
|
||||
tokio = { workspace = true, features = ["full"], optional = true }
|
||||
serde = "1.0.159"
|
||||
tower-http = { version = "0.4.0", features = ["fs"], optional = true }
|
||||
http = { version = "0.2.9", optional = true }
|
||||
execute = "0.2.12"
|
||||
tokio = {workspace = true, features = ["full"], optional = true }
|
||||
serde = { version = "1.0.159", features = ["derive"] }
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
ssr = ["axum", "tokio", "dioxus-fullstack/axum", "tower-http", "http"]
|
||||
default = []
|
||||
ssr = ["axum", "tokio", "dioxus-fullstack/axum"]
|
||||
web = ["dioxus-web", "dioxus-router/web"]
|
||||
@@ -1,122 +1,61 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dioxus build --features web
|
||||
//! cargo run --features ssr --no-default-features
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use dioxus_router::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use dioxus_router::prelude::*;
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "web")]
|
||||
dioxus_web::launch_with_props(
|
||||
App,
|
||||
AppProps { route: None },
|
||||
dioxus_web::Config::new().hydrate(true),
|
||||
);
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
// Start hot reloading
|
||||
hot_reload_init!(dioxus_hot_reload::Config::new().with_rebuild_callback(|| {
|
||||
execute::shell("dioxus build --features web")
|
||||
.spawn()
|
||||
.unwrap()
|
||||
.wait()
|
||||
.unwrap();
|
||||
execute::shell("cargo run --features ssr --no-default-features")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
true
|
||||
}));
|
||||
|
||||
use axum::extract::State;
|
||||
tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(async move {
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
|
||||
|
||||
axum::Server::bind(&addr)
|
||||
.serve(
|
||||
axum::Router::new()
|
||||
// Serve the dist/assets folder with the javascript and WASM files created by the CLI
|
||||
.serve_static_assets("./dist")
|
||||
// Register server functions
|
||||
.register_server_fns("")
|
||||
// Connect to the hot reload server
|
||||
.connect_hot_reload()
|
||||
// If the path is unknown, render the application
|
||||
.fallback(
|
||||
move |uri: http::uri::Uri, State(ssr_state): State<SSRState>| {
|
||||
let rendered = ssr_state.render(
|
||||
&ServeConfigBuilder::new(
|
||||
App,
|
||||
AppProps {
|
||||
route: Some(format!("http://{addr}{uri}")),
|
||||
},
|
||||
)
|
||||
.build(),
|
||||
);
|
||||
async move { axum::body::Full::from(rendered) }
|
||||
},
|
||||
)
|
||||
.with_state(SSRState::default())
|
||||
.into_make_service(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
launch_router!(@([127, 0, 0, 1], 8080), Route, {
|
||||
incremental: IncrementalRendererConfig::default().invalidate_after(std::time::Duration::from_secs(120)),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Props, PartialEq, Serialize, Deserialize)]
|
||||
struct AppProps {
|
||||
route: Option<String>,
|
||||
#[derive(Clone, Routable, Debug, PartialEq)]
|
||||
enum Route {
|
||||
#[route("/")]
|
||||
Home {},
|
||||
#[route("/blog/:id")]
|
||||
Blog { id: i32 },
|
||||
}
|
||||
|
||||
fn App(cx: Scope<AppProps>) -> Element {
|
||||
cx.render(rsx! {
|
||||
Router {
|
||||
initial_url: cx.props.route.clone(),
|
||||
|
||||
Route { to: "/blog",
|
||||
Link {
|
||||
to: "/",
|
||||
"Go to counter"
|
||||
}
|
||||
table {
|
||||
tbody {
|
||||
for _ in 0..100 {
|
||||
tr {
|
||||
for _ in 0..100 {
|
||||
td { "hello world!" }
|
||||
}
|
||||
}
|
||||
#[inline_props]
|
||||
fn Blog(cx: Scope, id: i32) -> Element {
|
||||
render! {
|
||||
Link { target: Route::Home {}, "Go to counter" }
|
||||
table {
|
||||
tbody {
|
||||
for _ in 0..*id {
|
||||
tr {
|
||||
for _ in 0..*id {
|
||||
td { "hello world!" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// Fallback
|
||||
Route { to: "",
|
||||
Counter {}
|
||||
},
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn Counter(cx: Scope) -> Element {
|
||||
#[inline_props]
|
||||
fn Home(cx: Scope) -> Element {
|
||||
let mut count = use_state(cx, || 0);
|
||||
let text = use_state(cx, || "...".to_string());
|
||||
|
||||
cx.render(rsx! {
|
||||
Link {
|
||||
to: "/blog",
|
||||
target: Route::Blog {
|
||||
id: *count.get()
|
||||
},
|
||||
"Go to blog"
|
||||
}
|
||||
div{
|
||||
div {
|
||||
h1 { "High-Five counter: {count}" }
|
||||
button { onclick: move |_| count += 1, "Up high!" }
|
||||
button { onclick: move |_| count -= 1, "Down low!" }
|
||||
@@ -131,7 +70,7 @@ fn Counter(cx: Scope) -> Element {
|
||||
}
|
||||
}
|
||||
},
|
||||
"Run a server function"
|
||||
"Run server function!"
|
||||
}
|
||||
"Server said: {text}"
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
dist
|
||||
target
|
||||
target
|
||||
static
|
||||
@@ -16,6 +16,6 @@ salvo = { version = "0.37.9", optional = true }
|
||||
execute = "0.2.12"
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
default = []
|
||||
ssr = ["salvo", "tokio", "dioxus-fullstack/salvo"]
|
||||
web = ["dioxus-web"]
|
||||
@@ -1,50 +1,19 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dioxus build --features web
|
||||
//! cargo run --features ssr --no-default-features
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_snake_case, unused)]
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "web")]
|
||||
dioxus_web::launch_with_props(
|
||||
app,
|
||||
get_root_props_from_document().unwrap_or_default(),
|
||||
dioxus_web::Config::new().hydrate(true),
|
||||
);
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
// Start hot reloading
|
||||
hot_reload_init!(dioxus_hot_reload::Config::new().with_rebuild_callback(|| {
|
||||
execute::shell("dioxus build --features web")
|
||||
.spawn()
|
||||
.unwrap()
|
||||
.wait()
|
||||
.unwrap();
|
||||
execute::shell("cargo run --features ssr --no-default-features")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
true
|
||||
}));
|
||||
|
||||
use salvo::prelude::*;
|
||||
tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(async move {
|
||||
let router = Router::new().serve_dioxus_application(
|
||||
"",
|
||||
ServeConfigBuilder::new(app, AppProps { count: 12345 }),
|
||||
);
|
||||
Server::new(TcpListener::bind("127.0.0.1:8080"))
|
||||
.serve(router)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
launch!(@([127, 0, 0, 1], 8080), app, (AppProps { count: 5 }), {
|
||||
incremental: IncrementalRendererConfig::default().invalidate_after(std::time::Duration::from_secs(120)),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
|
||||
@@ -55,7 +24,6 @@ struct AppProps {
|
||||
fn app(cx: Scope<AppProps>) -> Element {
|
||||
let mut count = use_state(cx, || cx.props.count);
|
||||
let text = use_state(cx, || "...".to_string());
|
||||
let server_context = cx.sc();
|
||||
|
||||
cx.render(rsx! {
|
||||
h1 { "High-Five counter: {count}" }
|
||||
@@ -63,12 +31,12 @@ fn app(cx: Scope<AppProps>) -> Element {
|
||||
button { onclick: move |_| count -= 1, "Down low!" }
|
||||
button {
|
||||
onclick: move |_| {
|
||||
to_owned![text, server_context];
|
||||
to_owned![text];
|
||||
async move {
|
||||
if let Ok(data) = get_server_data().await {
|
||||
println!("Client received: {}", data);
|
||||
text.set(data.clone());
|
||||
post_server_data(server_context, data).await.unwrap();
|
||||
post_server_data(data).await.unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -79,10 +47,9 @@ fn app(cx: Scope<AppProps>) -> Element {
|
||||
}
|
||||
|
||||
#[server(PostServerData)]
|
||||
async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
|
||||
async fn post_server_data(data: String) -> Result<(), ServerFnError> {
|
||||
// The server context contains information about the current request and allows you to modify the response.
|
||||
cx.response_headers_mut()
|
||||
.insert("Set-Cookie", "foo=bar".parse().unwrap());
|
||||
let cx = server_context();
|
||||
println!("Server received: {}", data);
|
||||
println!("Request parts are {:?}", cx.request_parts());
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
docs
|
||||
target
|
||||
static
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "static-hydrated"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
dioxus-web = { workspace = true, features = ["hydrate"], optional = true }
|
||||
dioxus = { workspace = true }
|
||||
dioxus-fullstack = { workspace = true, features = ["router"] }
|
||||
dioxus-router = { workspace = true}
|
||||
tokio = { workspace = true, features = ["full"], optional = true }
|
||||
serde = "1.0.159"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
ssr = ["tokio", "dioxus-fullstack/ssr"]
|
||||
web = ["dioxus-web"]
|
||||
@@ -0,0 +1,46 @@
|
||||
[application]
|
||||
|
||||
# App (Project) Name
|
||||
name = "Dioxus"
|
||||
|
||||
# Dioxus App Default Platform
|
||||
# desktop, web, mobile, ssr
|
||||
default_platform = "web"
|
||||
|
||||
# `build` & `serve` dist path
|
||||
out_dir = "docs"
|
||||
|
||||
# resource (public) file folder
|
||||
asset_dir = "public"
|
||||
|
||||
[web.app]
|
||||
|
||||
# HTML title tag content
|
||||
title = "dioxus | ⛺"
|
||||
|
||||
[web.watcher]
|
||||
|
||||
# when watcher trigger, regenerate the `index.html`
|
||||
reload_html = true
|
||||
|
||||
# which files or dirs will be watcher monitoring
|
||||
watch_path = ["src", "public"]
|
||||
|
||||
# include `assets` in web platform
|
||||
[web.resource]
|
||||
|
||||
# CSS style file
|
||||
style = ["tailwind.css"]
|
||||
|
||||
# Javascript code file
|
||||
script = []
|
||||
|
||||
[web.resource.dev]
|
||||
|
||||
# serve: [dev-server] only
|
||||
|
||||
# CSS style file
|
||||
style = []
|
||||
|
||||
# Javascript code file
|
||||
script = []
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case, unused)]
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::{launch, prelude::*};
|
||||
use dioxus_router::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// Generate all routes and output them to the docs path
|
||||
#[cfg(feature = "ssr")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
pre_cache_static_routes_with_props(
|
||||
&ServeConfigBuilder::new_with_router(dioxus_fullstack::router::FullstackRouterConfig::<
|
||||
Route,
|
||||
>::default())
|
||||
.assets_path("docs")
|
||||
.incremental(IncrementalRendererConfig::default().static_dir("docs"))
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Hydrate the page
|
||||
#[cfg(feature = "web")]
|
||||
fn main() {
|
||||
dioxus_web::launch_with_props(
|
||||
dioxus_fullstack::router::RouteWithCfg::<Route>,
|
||||
dioxus_fullstack::prelude::get_root_props_from_document()
|
||||
.expect("Failed to get root props from document"),
|
||||
dioxus_web::Config::default().hydrate(true),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "web", feature = "ssr")))]
|
||||
fn main() {}
|
||||
|
||||
#[derive(Clone, Routable, Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum Route {
|
||||
#[route("/")]
|
||||
Home {},
|
||||
#[route("/blog")]
|
||||
Blog,
|
||||
}
|
||||
|
||||
#[inline_props]
|
||||
fn Blog(cx: Scope) -> Element {
|
||||
render! {
|
||||
Link { target: Route::Home {}, "Go to counter" }
|
||||
table {
|
||||
tbody {
|
||||
for _ in 0..100 {
|
||||
tr {
|
||||
for _ in 0..100 {
|
||||
td { "hello world!" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline_props]
|
||||
fn Home(cx: Scope) -> Element {
|
||||
let mut count = use_state(cx, || 0);
|
||||
let text = use_state(cx, || "...".to_string());
|
||||
|
||||
cx.render(rsx! {
|
||||
Link {
|
||||
target: Route::Blog {},
|
||||
"Go to blog"
|
||||
}
|
||||
div {
|
||||
h1 { "High-Five counter: {count}" }
|
||||
button { onclick: move |_| count += 1, "Up high!" }
|
||||
button { onclick: move |_| count -= 1, "Down low!" }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
dist
|
||||
target
|
||||
target
|
||||
static
|
||||
@@ -16,6 +16,6 @@ warp = { version = "0.3.3", optional = true }
|
||||
execute = "0.2.12"
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
default = []
|
||||
ssr = ["warp", "tokio", "dioxus-fullstack/warp"]
|
||||
web = ["dioxus-web"]
|
||||
@@ -1,47 +1,19 @@
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```sh
|
||||
//! dioxus build --features web
|
||||
//! cargo run --features ssr --no-default-features
|
||||
//! dx build --features web
|
||||
//! cargo run --features ssr
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_snake_case, unused)]
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_fullstack::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "web")]
|
||||
dioxus_web::launch_with_props(
|
||||
app,
|
||||
get_root_props_from_document().unwrap_or_default(),
|
||||
dioxus_web::Config::new().hydrate(true),
|
||||
);
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
// Start hot reloading
|
||||
hot_reload_init!(dioxus_hot_reload::Config::new().with_rebuild_callback(|| {
|
||||
execute::shell("dioxus build --features web")
|
||||
.spawn()
|
||||
.unwrap()
|
||||
.wait()
|
||||
.unwrap();
|
||||
execute::shell("cargo run --features ssr --no-default-features")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
true
|
||||
}));
|
||||
|
||||
tokio::runtime::Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(async move {
|
||||
let routes = serve_dioxus_application(
|
||||
"",
|
||||
ServeConfigBuilder::new(app, AppProps { count: 12345 }),
|
||||
);
|
||||
warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
|
||||
});
|
||||
}
|
||||
launch!(@([127, 0, 0, 1], 8080), app, (AppProps { count: 5 }), {
|
||||
incremental: IncrementalRendererConfig::default().invalidate_after(std::time::Duration::from_secs(120)),
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
|
||||
@@ -52,20 +24,19 @@ struct AppProps {
|
||||
fn app(cx: Scope<AppProps>) -> Element {
|
||||
let mut count = use_state(cx, || cx.props.count);
|
||||
let text = use_state(cx, || "...".to_string());
|
||||
let server_context = cx.sc();
|
||||
|
||||
cx.render(rsx! {
|
||||
h1 { "High-Five counter: {count}" }
|
||||
button { onclick: move |_| count += 10, "Up high!" }
|
||||
button { onclick: move |_| count += 1, "Up high!" }
|
||||
button { onclick: move |_| count -= 1, "Down low!" }
|
||||
button {
|
||||
onclick: move |_| {
|
||||
to_owned![text, server_context];
|
||||
to_owned![text];
|
||||
async move {
|
||||
if let Ok(data) = get_server_data().await {
|
||||
println!("Client received: {}", data);
|
||||
text.set(data.clone());
|
||||
post_server_data(server_context, data).await.unwrap();
|
||||
post_server_data(data).await.unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -76,10 +47,9 @@ fn app(cx: Scope<AppProps>) -> Element {
|
||||
}
|
||||
|
||||
#[server(PostServerData)]
|
||||
async fn post_server_data(cx: DioxusServerContext, data: String) -> Result<(), ServerFnError> {
|
||||
async fn post_server_data(data: String) -> Result<(), ServerFnError> {
|
||||
// The server context contains information about the current request and allows you to modify the response.
|
||||
cx.response_headers_mut()
|
||||
.insert("Set-Cookie", "foo=bar".parse().unwrap());
|
||||
let cx = server_context();
|
||||
println!("Server received: {}", data);
|
||||
println!("Request parts are {:?}", cx.request_parts());
|
||||
|
||||
|
||||
@@ -6,9 +6,11 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0.63"
|
||||
quote = "1.0.26"
|
||||
server_fn_macro = { git = "https://github.com/leptos-rs/leptos", rev = "15a4e54435eb5a539afb75891292bcccd2cc8e85", features = ["stable"] }
|
||||
server_fn_macro = { git = "https://github.com/leptos-rs/leptos", rev = "6b90e1babd425c9a324181c86e3fd1b942c9b10f" }
|
||||
syn = { version = "2", features = ["full"] }
|
||||
convert_case = "0.6.0"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
@@ -1,6 +1,12 @@
|
||||
use convert_case::{Case, Converter};
|
||||
use proc_macro::TokenStream;
|
||||
use quote::ToTokens;
|
||||
use proc_macro2::Literal;
|
||||
use quote::{ToTokens, __private::TokenStream as TokenStream2};
|
||||
use server_fn_macro::*;
|
||||
use syn::{
|
||||
parse::{Parse, ParseStream},
|
||||
Ident, ItemFn, Token,
|
||||
};
|
||||
|
||||
/// Declares that a function is a [server function](dioxus_fullstack). This means that
|
||||
/// its body will only run on the server, i.e., when the `ssr` feature is enabled.
|
||||
@@ -54,18 +60,147 @@ use server_fn_macro::*;
|
||||
/// or response or other server-only dependencies, but it does *not* have access to reactive state that exists in the client.
|
||||
#[proc_macro_attribute]
|
||||
pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
let context = ServerContext {
|
||||
ty: syn::parse_quote!(DioxusServerContext),
|
||||
path: syn::parse_quote!(::dioxus_fullstack::prelude::DioxusServerContext),
|
||||
// before we pass this off to the server function macro, we apply extractors and middleware
|
||||
let mut function: syn::ItemFn = match syn::parse(s).map_err(|e| e.to_compile_error()) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
// extract all #[middleware] attributes
|
||||
let mut middlewares: Vec<Middleware> = vec![];
|
||||
function.attrs.retain(|attr| {
|
||||
if attr.meta.path().is_ident("middleware") {
|
||||
if let Ok(middleware) = attr.parse_args() {
|
||||
middlewares.push(middleware);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
|
||||
let ItemFn {
|
||||
attrs,
|
||||
vis,
|
||||
sig,
|
||||
block,
|
||||
} = function;
|
||||
let mapped_body = quote::quote! {
|
||||
#(#attrs)*
|
||||
#vis #sig {
|
||||
#block
|
||||
}
|
||||
};
|
||||
|
||||
let server_fn_path: syn::Path = syn::parse_quote!(::dioxus_fullstack::prelude::server_fn);
|
||||
let trait_obj_wrapper: syn::Type =
|
||||
syn::parse_quote!(::dioxus_fullstack::prelude::ServerFnTraitObj);
|
||||
let mut args: ServerFnArgs = match syn::parse(args) {
|
||||
Ok(args) => args,
|
||||
Err(e) => return e.to_compile_error().into(),
|
||||
};
|
||||
if args.struct_name.is_none() {
|
||||
let upper_cammel_case_name = Converter::new()
|
||||
.from_case(Case::Snake)
|
||||
.to_case(Case::UpperCamel)
|
||||
.convert(&sig.ident.to_string());
|
||||
args.struct_name = Some(Ident::new(&upper_cammel_case_name, sig.ident.span()));
|
||||
}
|
||||
let struct_name = args.struct_name.as_ref().unwrap();
|
||||
match server_macro_impl(
|
||||
args.into(),
|
||||
s.into(),
|
||||
syn::parse_quote!(::dioxus_fullstack::prelude::ServerFnTraitObj),
|
||||
Some(context),
|
||||
Some(syn::parse_quote!(::dioxus_fullstack::prelude::server_fn)),
|
||||
quote::quote!(#args),
|
||||
mapped_body,
|
||||
trait_obj_wrapper,
|
||||
None,
|
||||
Some(server_fn_path.clone()),
|
||||
) {
|
||||
Err(e) => e.to_compile_error().into(),
|
||||
Ok(s) => s.to_token_stream().into(),
|
||||
Ok(tokens) => quote::quote! {
|
||||
#tokens
|
||||
#[cfg(feature = "ssr")]
|
||||
#server_fn_path::inventory::submit! {
|
||||
::dioxus_fullstack::prelude::ServerFnMiddleware {
|
||||
prefix: #struct_name::PREFIX,
|
||||
url: #struct_name::URL,
|
||||
middleware: || vec![
|
||||
#(
|
||||
std::sync::Arc::new(#middlewares),
|
||||
),*
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
.to_token_stream()
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Middleware {
|
||||
expr: syn::Expr,
|
||||
}
|
||||
|
||||
impl ToTokens for Middleware {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||
let expr = &self.expr;
|
||||
tokens.extend(quote::quote! {
|
||||
#expr
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Middleware {
|
||||
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
|
||||
let arg: syn::Expr = input.parse()?;
|
||||
Ok(Middleware { expr: arg })
|
||||
}
|
||||
}
|
||||
|
||||
struct ServerFnArgs {
|
||||
struct_name: Option<Ident>,
|
||||
_comma: Option<Token![,]>,
|
||||
prefix: Option<Literal>,
|
||||
_comma2: Option<Token![,]>,
|
||||
encoding: Option<Literal>,
|
||||
_comma3: Option<Token![,]>,
|
||||
fn_path: Option<Literal>,
|
||||
}
|
||||
|
||||
impl ToTokens for ServerFnArgs {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||
let struct_name = self.struct_name.as_ref().map(|s| quote::quote! { #s, });
|
||||
let prefix = self.prefix.as_ref().map(|p| quote::quote! { #p, });
|
||||
let encoding = self.encoding.as_ref().map(|e| quote::quote! { #e, });
|
||||
let fn_path = self.fn_path.as_ref().map(|f| quote::quote! { #f, });
|
||||
tokens.extend(quote::quote! {
|
||||
#struct_name
|
||||
#prefix
|
||||
#encoding
|
||||
#fn_path
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for ServerFnArgs {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let struct_name = input.parse()?;
|
||||
let _comma = input.parse()?;
|
||||
let prefix = input.parse()?;
|
||||
let _comma2 = input.parse()?;
|
||||
let encoding = input.parse()?;
|
||||
let _comma3 = input.parse()?;
|
||||
let fn_path = input.parse()?;
|
||||
|
||||
Ok(Self {
|
||||
struct_name,
|
||||
_comma,
|
||||
prefix,
|
||||
_comma2,
|
||||
encoding,
|
||||
_comma3,
|
||||
fn_path,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -55,19 +55,17 @@
|
||||
//! ```
|
||||
|
||||
use axum::{
|
||||
body::{self, Body, BoxBody, Full},
|
||||
extract::{State, WebSocketUpgrade},
|
||||
body::{self, Body, BoxBody},
|
||||
extract::State,
|
||||
handler::Handler,
|
||||
http::{Request, Response, StatusCode},
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use dioxus_core::VirtualDom;
|
||||
use server_fn::{Encoding, Payload, ServerFunctionRegistry};
|
||||
use std::error::Error;
|
||||
use server_fn::{Encoding, ServerFunctionRegistry};
|
||||
use std::sync::Arc;
|
||||
use tokio::task::spawn_blocking;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::{
|
||||
prelude::*, render::SSRState, serve_config::ServeConfig, server_context::DioxusServerContext,
|
||||
@@ -92,7 +90,7 @@ pub trait DioxusRouterExt<S> {
|
||||
/// .register_server_fns_with_handler("", |func| {
|
||||
/// move |req: Request<Body>| async move {
|
||||
/// let (parts, body) = req.into_parts();
|
||||
/// let parts: Arc<RequestParts> = Arc::new(parts.into());
|
||||
/// let parts: Arc<http::request::Parts> = Arc::new(parts.into());
|
||||
/// let server_context = DioxusServerContext::new(parts.clone());
|
||||
/// server_fn_handler(server_context, func.clone(), parts, body).await
|
||||
/// }
|
||||
@@ -106,7 +104,7 @@ pub trait DioxusRouterExt<S> {
|
||||
fn register_server_fns_with_handler<H, T>(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
handler: impl FnMut(server_fn::ServerFnTraitObj<DioxusServerContext>) -> H,
|
||||
handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
|
||||
) -> Self
|
||||
where
|
||||
H: Handler<T, S>,
|
||||
@@ -231,7 +229,7 @@ where
|
||||
fn register_server_fns_with_handler<H, T>(
|
||||
self,
|
||||
server_fn_route: &'static str,
|
||||
mut handler: impl FnMut(server_fn::ServerFnTraitObj<DioxusServerContext>) -> H,
|
||||
mut handler: impl FnMut(server_fn::ServerFnTraitObj<()>) -> H,
|
||||
) -> Self
|
||||
where
|
||||
H: Handler<T, S, Body>,
|
||||
@@ -256,11 +254,22 @@ where
|
||||
|
||||
fn register_server_fns(self, server_fn_route: &'static str) -> Self {
|
||||
self.register_server_fns_with_handler(server_fn_route, |func| {
|
||||
move |req: Request<Body>| async move {
|
||||
let (parts, body) = req.into_parts();
|
||||
let parts: Arc<RequestParts> = Arc::new(parts.into());
|
||||
let server_context = DioxusServerContext::new(parts.clone());
|
||||
server_fn_handler(server_context, func.clone(), parts, body).await
|
||||
use crate::layer::Service;
|
||||
move |req: Request<Body>| {
|
||||
let mut service = crate::server_fn_service(Default::default(), func);
|
||||
async move {
|
||||
let (req, body) = req.into_parts();
|
||||
let req = Request::from_parts(req, body);
|
||||
let res = service.run(req);
|
||||
match res.await {
|
||||
Ok(res) => Ok::<_, std::convert::Infallible>(res.map(|b| b.into())),
|
||||
Err(_e) => {
|
||||
let mut res = Response::new(Body::empty());
|
||||
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -311,15 +320,13 @@ where
|
||||
cfg: impl Into<ServeConfig<P>>,
|
||||
) -> Self {
|
||||
let cfg = cfg.into();
|
||||
let ssr_state = SSRState::new(&cfg);
|
||||
|
||||
// Add server functions and render index.html
|
||||
self.serve_static_assets(cfg.assets_path)
|
||||
.route(
|
||||
"/",
|
||||
get(render_handler).with_state((cfg, SSRState::default())),
|
||||
)
|
||||
.connect_hot_reload()
|
||||
.register_server_fns(server_fn_route)
|
||||
.fallback(get(render_handler).with_state((cfg, ssr_state)))
|
||||
}
|
||||
|
||||
fn connect_hot_reload(self) -> Self {
|
||||
@@ -330,7 +337,7 @@ where
|
||||
Router::new()
|
||||
.route(
|
||||
"/disconnect",
|
||||
get(|ws: WebSocketUpgrade| async {
|
||||
get(|ws: axum::extract::WebSocketUpgrade| async {
|
||||
ws.on_upgrade(|mut ws| async move {
|
||||
use axum::extract::ws::Message;
|
||||
let _ = ws.send(Message::Text("connected".into())).await;
|
||||
@@ -352,96 +359,42 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_request_parts_to_response<B>(
|
||||
headers: hyper::header::HeaderMap,
|
||||
response: &mut axum::response::Response<B>,
|
||||
) {
|
||||
let mut_headers = response.headers_mut();
|
||||
for (key, value) in headers.iter() {
|
||||
mut_headers.insert(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
async fn render_handler<P: Clone + serde::Serialize + Send + Sync + 'static>(
|
||||
State((cfg, ssr_state)): State<(ServeConfig<P>, SSRState)>,
|
||||
request: Request<Body>,
|
||||
) -> impl IntoResponse {
|
||||
let (parts, _) = request.into_parts();
|
||||
let parts: Arc<RequestParts> = Arc::new(parts.into());
|
||||
let server_context = DioxusServerContext::new(parts);
|
||||
let mut vdom =
|
||||
VirtualDom::new_with_props(cfg.app, cfg.props.clone()).with_root_context(server_context);
|
||||
let _ = vdom.rebuild();
|
||||
let url = parts.uri.path_and_query().unwrap().to_string();
|
||||
let parts: Arc<RwLock<http::request::Parts>> = Arc::new(RwLock::new(parts.into()));
|
||||
let server_context = DioxusServerContext::new(parts.clone());
|
||||
|
||||
let rendered = ssr_state.render_vdom(&vdom, &cfg);
|
||||
Full::from(rendered)
|
||||
}
|
||||
|
||||
/// A default handler for server functions. It will deserialize the request, call the server function, and serialize the response.
|
||||
pub async fn server_fn_handler(
|
||||
server_context: DioxusServerContext,
|
||||
function: server_fn::ServerFnTraitObj<DioxusServerContext>,
|
||||
parts: Arc<RequestParts>,
|
||||
body: Body,
|
||||
) -> impl IntoResponse {
|
||||
let body = hyper::body::to_bytes(body).await;
|
||||
let Ok(body) = body else {
|
||||
return report_err(body.err().unwrap());
|
||||
};
|
||||
|
||||
// Because the future returned by `server_fn_handler` is `Send`, and the future returned by this function must be send, we need to spawn a new runtime
|
||||
let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
|
||||
let query_string = parts.uri.query().unwrap_or_default().to_string();
|
||||
spawn_blocking({
|
||||
move || {
|
||||
tokio::runtime::Runtime::new()
|
||||
.expect("couldn't spawn runtime")
|
||||
.block_on(async {
|
||||
let query = &query_string.into();
|
||||
let data = match &function.encoding() {
|
||||
Encoding::Url | Encoding::Cbor => &body,
|
||||
Encoding::GetJSON | Encoding::GetCBOR => query,
|
||||
};
|
||||
let resp = match function.call(server_context.clone(), data).await {
|
||||
Ok(serialized) => {
|
||||
// if this is Accept: application/json then send a serialized JSON response
|
||||
let accept_header = parts
|
||||
.headers
|
||||
.get("Accept")
|
||||
.and_then(|value| value.to_str().ok());
|
||||
let mut res = Response::builder();
|
||||
*res.headers_mut().expect("empty response should be valid") =
|
||||
server_context.take_response_headers();
|
||||
if accept_header == Some("application/json")
|
||||
|| accept_header
|
||||
== Some(
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
)
|
||||
|| accept_header == Some("application/cbor")
|
||||
{
|
||||
res = res.status(StatusCode::OK);
|
||||
}
|
||||
|
||||
let resp = match serialized {
|
||||
Payload::Binary(data) => res
|
||||
.header("Content-Type", "application/cbor")
|
||||
.body(body::boxed(Full::from(data))),
|
||||
Payload::Url(data) => res
|
||||
.header(
|
||||
"Content-Type",
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
)
|
||||
.body(body::boxed(data)),
|
||||
Payload::Json(data) => res
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body::boxed(data)),
|
||||
};
|
||||
|
||||
resp.unwrap()
|
||||
}
|
||||
Err(e) => report_err(e),
|
||||
};
|
||||
|
||||
resp_tx.send(resp).unwrap();
|
||||
})
|
||||
match ssr_state.render(url, &cfg, &server_context).await {
|
||||
Ok(rendered) => {
|
||||
let crate::render::RenderResponse { html, freshness } = rendered;
|
||||
let mut response = axum::response::Html::from(html).into_response();
|
||||
freshness.write(response.headers_mut());
|
||||
let headers = server_context.response_parts().unwrap().headers.clone();
|
||||
apply_request_parts_to_response(headers, &mut response);
|
||||
response
|
||||
}
|
||||
});
|
||||
resp_rx.await.unwrap()
|
||||
Err(e) => {
|
||||
log::error!("Failed to render page: {}", e);
|
||||
report_err(e).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn report_err<E: Error>(e: E) -> Response<BoxBody> {
|
||||
fn report_err<E: std::fmt::Display>(e: E) -> Response<BoxBody> {
|
||||
Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(body::boxed(format!("Error: {}", e)))
|
||||
@@ -450,7 +403,7 @@ fn report_err<E: Error>(e: E) -> Response<BoxBody> {
|
||||
|
||||
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "ssr"))]
|
||||
pub async fn hot_reload_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
|
||||
pub async fn hot_reload_handler(ws: axum::extract::WebSocketUpgrade) -> impl IntoResponse {
|
||||
use axum::extract::ws::Message;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
|
||||
@@ -16,3 +16,145 @@ pub mod axum_adapter;
|
||||
pub mod salvo_adapter;
|
||||
#[cfg(feature = "warp")]
|
||||
pub mod warp_adapter;
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use http::StatusCode;
|
||||
|
||||
use server_fn::{Encoding, Payload};
|
||||
use tokio::task::spawn_blocking;
|
||||
|
||||
use crate::{
|
||||
layer::{BoxedService, Service},
|
||||
prelude::{DioxusServerContext, ProvideServerContext},
|
||||
};
|
||||
|
||||
/// Create a server function handler with the given server context and server function.
|
||||
pub fn server_fn_service(
|
||||
context: DioxusServerContext,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
) -> crate::layer::BoxedService {
|
||||
let prefix = function.prefix().to_string();
|
||||
let url = function.url().to_string();
|
||||
if let Some(middleware) = crate::server_fn::MIDDLEWARE.get(&(&prefix, &url)) {
|
||||
let mut service = BoxedService(Box::new(ServerFnHandler::new(context, function)));
|
||||
for middleware in middleware {
|
||||
service = middleware.layer(service);
|
||||
}
|
||||
service
|
||||
} else {
|
||||
BoxedService(Box::new(ServerFnHandler::new(context, function)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
/// A default handler for server functions. It will deserialize the request body, call the server function, and serialize the response.
|
||||
pub struct ServerFnHandler {
|
||||
server_context: DioxusServerContext,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
}
|
||||
|
||||
impl ServerFnHandler {
|
||||
/// Create a new server function handler with the given server context and server function.
|
||||
pub fn new(
|
||||
server_context: impl Into<DioxusServerContext>,
|
||||
function: server_fn::ServerFnTraitObj<()>,
|
||||
) -> Self {
|
||||
let server_context = server_context.into();
|
||||
Self {
|
||||
server_context,
|
||||
function,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for ServerFnHandler {
|
||||
fn run(
|
||||
&mut self,
|
||||
req: http::Request<hyper::body::Body>,
|
||||
) -> std::pin::Pin<
|
||||
Box<
|
||||
dyn std::future::Future<
|
||||
Output = Result<http::Response<hyper::body::Body>, server_fn::ServerFnError>,
|
||||
> + Send,
|
||||
>,
|
||||
> {
|
||||
let Self {
|
||||
server_context,
|
||||
function,
|
||||
} = self.clone();
|
||||
Box::pin(async move {
|
||||
let query = req.uri().query().unwrap_or_default().as_bytes().to_vec();
|
||||
let (parts, body) = req.into_parts();
|
||||
let body = hyper::body::to_bytes(body).await?.to_vec();
|
||||
let headers = &parts.headers;
|
||||
let accept_header = headers.get("Accept").cloned();
|
||||
let parts = Arc::new(RwLock::new(parts));
|
||||
|
||||
// Because the future returned by `server_fn_handler` is `Send`, and the future returned by this function must be send, we need to spawn a new runtime
|
||||
let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
|
||||
spawn_blocking({
|
||||
let function = function.clone();
|
||||
let mut server_context = server_context.clone();
|
||||
server_context.parts = parts;
|
||||
move || {
|
||||
tokio::runtime::Runtime::new()
|
||||
.expect("couldn't spawn runtime")
|
||||
.block_on(async move {
|
||||
let data = match function.encoding() {
|
||||
Encoding::Url | Encoding::Cbor => &body,
|
||||
Encoding::GetJSON | Encoding::GetCBOR => &query,
|
||||
};
|
||||
let server_function_future = function.call((), data);
|
||||
let server_function_future = ProvideServerContext::new(
|
||||
server_function_future,
|
||||
server_context.clone(),
|
||||
);
|
||||
let resp = server_function_future.await;
|
||||
|
||||
resp_tx.send(resp).unwrap();
|
||||
})
|
||||
}
|
||||
});
|
||||
let result = resp_rx.await.unwrap();
|
||||
let mut res = http::Response::builder();
|
||||
|
||||
// Set the headers from the server context
|
||||
let parts = server_context.parts.read().unwrap();
|
||||
*res.headers_mut().expect("empty headers should be valid") = parts.headers.clone();
|
||||
|
||||
let serialized = result?;
|
||||
// if this is Accept: application/json then send a serialized JSON response
|
||||
let accept_header = accept_header.as_ref().and_then(|value| value.to_str().ok());
|
||||
if accept_header == Some("application/json")
|
||||
|| accept_header
|
||||
== Some(
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
)
|
||||
|| accept_header == Some("application/cbor")
|
||||
{
|
||||
res = res.status(StatusCode::OK);
|
||||
}
|
||||
|
||||
Ok(match serialized {
|
||||
Payload::Binary(data) => {
|
||||
res = res.header("Content-Type", "application/cbor");
|
||||
res.body(data.into())?
|
||||
}
|
||||
Payload::Url(data) => {
|
||||
res = res.header(
|
||||
"Content-Type",
|
||||
"application/\
|
||||
x-www-form-urlencoded",
|
||||
);
|
||||
res.body(data.into())?
|
||||
}
|
||||
Payload::Json(data) => {
|
||||
res = res.header("Content-Type", "application/json");
|
||||
res.body(data.into())?
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user