Merge branch 'master' into add-file-data-drag-event

This commit is contained in:
Evan Almloff committed 2024-01-08 14:16:09 -06:00
commit 56798b3d1c
407 files changed
+16602 -11298

No files matched your search

+6 -5
View File
@@ -8,13 +8,14 @@ use std::fmt::{Result, Write};
use dioxus_rsx::IfmtInput;
use crate::write_ifmt;
use crate::{indent::IndentOptions, write_ifmt};
/// The output buffer that tracks indent and string
#[derive(Debug, Default)]
pub struct Buffer {
pub buf: String,
pub indent: usize,
pub indent_level: usize,
pub indent: IndentOptions,
}
impl Buffer {
@@ -31,16 +32,16 @@ impl Buffer {
}
pub fn tab(&mut self) -> Result {
self.write_tabs(self.indent)
self.write_tabs(self.indent_level)
}
pub fn indented_tab(&mut self) -> Result {
self.write_tabs(self.indent + 1)
self.write_tabs(self.indent_level + 1)
}
pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result {
for _ in 0..num {
write!(self.buf, " ")?
write!(self.buf, "{}", self.indent.indent_str())?
}
Ok(())
}
+63 -33
View File
@@ -49,6 +49,7 @@ impl Writer<'_> {
attributes,
children,
brace,
..
} = el;
/*
@@ -66,7 +67,7 @@ impl Writer<'_> {
// check if we have a lot of attributes
let attr_len = self.is_short_attrs(attributes);
let is_short_attr_list = (attr_len + self.out.indent * 4) < 80;
let is_short_attr_list = (attr_len + self.out.indent_level * 4) < 80;
let children_len = self.is_short_children(children);
let is_small_children = children_len.is_some();
@@ -86,7 +87,7 @@ impl Writer<'_> {
// if we have few children and few attributes, make it a one-liner
if is_short_attr_list && is_small_children {
if children_len.unwrap() + attr_len + self.out.indent * 4 < 100 {
if children_len.unwrap() + attr_len + self.out.indent_level * 4 < 100 {
opt_level = ShortOptimization::Oneliner;
} else {
opt_level = ShortOptimization::PropsOnTop;
@@ -165,7 +166,7 @@ impl Writer<'_> {
fn write_attributes(
&mut self,
attributes: &[ElementAttrNamed],
attributes: &[AttributeType],
key: &Option<IfmtInput>,
sameline: bool,
) -> Result {
@@ -185,11 +186,11 @@ impl Writer<'_> {
}
while let Some(attr) = attr_iter.next() {
self.out.indent += 1;
self.out.indent_level += 1;
if !sameline {
self.write_comments(attr.attr.start())?;
self.write_comments(attr.start())?;
}
self.out.indent -= 1;
self.out.indent_level -= 1;
if !sameline {
self.out.indented_tabbed_line()?;
@@ -209,12 +210,34 @@ impl Writer<'_> {
Ok(())
}
fn write_attribute(&mut self, attr: &ElementAttrNamed) -> Result {
match &attr.attr {
ElementAttr::AttrText { name, value } => {
write!(self.out, "{name}: {value}", value = ifmt_to_string(value))?;
fn write_attribute_name(&mut self, attr: &ElementAttrName) -> Result {
match attr {
ElementAttrName::BuiltIn(name) => {
write!(self.out, "{}", name)?;
}
ElementAttr::AttrExpression { name, value } => {
ElementAttrName::Custom(name) => {
write!(self.out, "{}", name.to_token_stream())?;
}
}
Ok(())
}
fn write_attribute_value(&mut self, value: &ElementAttrValue) -> Result {
match value {
ElementAttrValue::AttrOptionalExpr { condition, value } => {
write!(
self.out,
"if {condition} {{ ",
condition = prettyplease::unparse_expr(condition),
)?;
self.write_attribute_value(value)?;
write!(self.out, " }}")?;
}
ElementAttrValue::AttrLiteral(value) => {
write!(self.out, "{value}", value = ifmt_to_string(value))?;
}
ElementAttrValue::AttrExpr(value) => {
let out = prettyplease::unparse_expr(value);
let mut lines = out.split('\n').peekable();
let first = lines.next().unwrap();
@@ -222,9 +245,9 @@ impl Writer<'_> {
// a one-liner for whatever reason
// Does not need a new line
if lines.peek().is_none() {
write!(self.out, "{name}: {first}")?;
write!(self.out, "{first}")?;
} else {
writeln!(self.out, "{name}: {first}")?;
writeln!(self.out, "{first}")?;
while let Some(line) = lines.next() {
self.out.indented_tab()?;
@@ -237,22 +260,7 @@ impl Writer<'_> {
}
}
}
ElementAttr::CustomAttrText { name, value } => {
write!(
self.out,
"{name}: {value}",
name = name.to_token_stream(),
value = ifmt_to_string(value)
)?;
}
ElementAttr::CustomAttrExpression { name, value } => {
let out = prettyplease::unparse_expr(value);
write!(self.out, "{}: {}", name.to_token_stream(), out)?;
}
ElementAttr::EventTokens { name, tokens } => {
ElementAttrValue::EventTokens(tokens) => {
let out = self.retrieve_formatted_expr(tokens).to_string();
let mut lines = out.split('\n').peekable();
@@ -261,9 +269,9 @@ impl Writer<'_> {
// a one-liner for whatever reason
// Does not need a new line
if lines.peek().is_none() {
write!(self.out, "{name}: {first}")?;
write!(self.out, "{first}")?;
} else {
writeln!(self.out, "{name}: {first}")?;
writeln!(self.out, "{first}")?;
while let Some(line) = lines.next() {
self.out.indented_tab()?;
@@ -281,6 +289,28 @@ impl Writer<'_> {
Ok(())
}
fn write_attribute(&mut self, attr: &AttributeType) -> Result {
match attr {
AttributeType::Named(attr) => self.write_named_attribute(attr),
AttributeType::Spread(attr) => self.write_spread_attribute(attr),
}
}
fn write_named_attribute(&mut self, attr: &ElementAttrNamed) -> Result {
self.write_attribute_name(&attr.attr.name)?;
write!(self.out, ": ")?;
self.write_attribute_value(&attr.attr.value)?;
Ok(())
}
fn write_spread_attribute(&mut self, attr: &Expr) -> Result {
write!(self.out, "..")?;
write!(self.out, "{}", prettyplease::unparse_expr(attr))?;
Ok(())
}
// make sure the comments are actually relevant to this element.
// test by making sure this element is the primary element on this line
pub fn current_span_is_primary(&self, location: Span) -> bool {
@@ -398,14 +428,14 @@ impl Writer<'_> {
for idx in start.line..end.line {
let line = &self.src[idx];
if line.trim().starts_with("//") {
for _ in 0..self.out.indent + 1 {
for _ in 0..self.out.indent_level + 1 {
write!(self.out, " ")?
}
writeln!(self.out, "{}", line.trim()).unwrap();
}
}
for _ in 0..self.out.indent {
for _ in 0..self.out.indent_level {
write!(self.out, " ")?
}
+3 -3
View File
@@ -29,7 +29,7 @@ impl Writer<'_> {
let first_line = &self.src[start.line - 1];
write!(self.out, "{}", &first_line[start.column - 1..].trim_start())?;
let prev_block_indent_level = crate::leading_whitespaces(first_line) / 4;
let prev_block_indent_level = self.out.indent.count_indents(first_line);
for (id, line) in self.src[start.line..end.line].iter().enumerate() {
writeln!(self.out)?;
@@ -43,9 +43,9 @@ impl Writer<'_> {
};
// trim the leading whitespace
let previous_indent = crate::leading_whitespaces(line) / 4;
let previous_indent = self.out.indent.count_indents(line);
let offset = previous_indent.saturating_sub(prev_block_indent_level);
let required_indent = self.out.indent + offset;
let required_indent = self.out.indent_level + offset;
self.out.write_tabs(required_indent)?;
let line = line.trim_start();
+108
View File
@@ -0,0 +1,108 @@
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum IndentType {
Spaces,
Tabs,
}
#[derive(Debug, Clone)]
pub struct IndentOptions {
width: usize,
indent_string: String,
}
impl IndentOptions {
pub fn new(typ: IndentType, width: usize) -> Self {
assert_ne!(width, 0, "Cannot have an indent width of 0");
Self {
width,
indent_string: match typ {
IndentType::Tabs => "\t".into(),
IndentType::Spaces => " ".repeat(width),
},
}
}
/// Gets a string containing one indent worth of whitespace
pub fn indent_str(&self) -> &str {
&self.indent_string
}
/// Computes the line length in characters, counting tabs as the indent width.
pub fn line_length(&self, line: &str) -> usize {
line.chars()
.map(|ch| if ch == '\t' { self.width } else { 1 })
.sum()
}
/// Estimates how many times the line has been indented.
pub fn count_indents(&self, mut line: &str) -> usize {
let mut indent = 0;
while !line.is_empty() {
// Try to count tabs
let num_tabs = line.chars().take_while(|ch| *ch == '\t').count();
if num_tabs > 0 {
indent += num_tabs;
line = &line[num_tabs..];
continue;
}
// Try to count spaces
let num_spaces = line.chars().take_while(|ch| *ch == ' ').count();
if num_spaces >= self.width {
// Intentionally floor here to take only the amount of space that matches an indent
let num_space_indents = num_spaces / self.width;
indent += num_space_indents;
line = &line[num_space_indents * self.width..];
continue;
}
// Line starts with either non-indent characters or an unevent amount of spaces,
// so no more indent remains.
break;
}
indent
}
}
impl Default for IndentOptions {
fn default() -> Self {
Self::new(IndentType::Spaces, 4)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn count_indents() {
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents("no indentation here!"),
0
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"),
1
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\tv += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\t v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 2).count_indents(" v += 2"),
2
);
}
}
+16 -15
View File
@@ -1,3 +1,7 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
use std::fmt::{Display, Write};
use crate::writer::*;
@@ -12,8 +16,11 @@ mod collect_macros;
mod component;
mod element;
mod expr;
mod indent;
mod writer;
pub use indent::{IndentOptions, IndentType};
/// A modification to the original file to be applied by an IDE
///
/// Right now this re-writes entire rsx! blocks at a time, instead of precise line-by-line changes.
@@ -43,7 +50,7 @@ pub struct FormattedBlock {
/// back to the file precisely.
///
/// Nested blocks of RSX will be handled automatically
pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
pub fn fmt_file(contents: &str, indent: IndentOptions) -> Vec<FormattedBlock> {
let mut formatted_blocks = Vec::new();
let parsed = syn::parse_file(contents).unwrap();
@@ -57,6 +64,7 @@ pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
}
let mut writer = Writer::new(contents);
writer.out.indent = indent;
// Don't parse nested macros
let mut end_span = LineColumn { column: 0, line: 0 };
@@ -72,7 +80,10 @@ pub fn fmt_file(contents: &str) -> Vec<FormattedBlock> {
let rsx_start = macro_path.span().start();
writer.out.indent = leading_whitespaces(writer.src[rsx_start.line - 1]) / 4;
writer.out.indent_level = writer
.out
.indent
.count_indents(writer.src[rsx_start.line - 1]);
write_body(&mut writer, &body);
@@ -155,12 +166,13 @@ pub fn fmt_block_from_expr(raw: &str, expr: ExprMacro) -> Option<String> {
buf.consume()
}
pub fn fmt_block(block: &str, indent_level: usize) -> Option<String> {
pub fn fmt_block(block: &str, indent_level: usize, indent: IndentOptions) -> Option<String> {
let body = syn::parse_str::<dioxus_rsx::CallBody>(block).unwrap();
let mut buf = Writer::new(block);
buf.out.indent = indent_level;
buf.out.indent = indent;
buf.out.indent_level = indent_level;
write_body(&mut buf, &body);
@@ -226,14 +238,3 @@ 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()
}
+56 -38
View File
@@ -1,4 +1,4 @@
use dioxus_rsx::{BodyNode, ElementAttr, ElementAttrNamed, ForLoop};
use dioxus_rsx::{AttributeType, BodyNode, ElementAttrValue, ForLoop};
use proc_macro2::{LineColumn, Span};
use quote::ToTokens;
use std::{
@@ -96,11 +96,11 @@ impl<'a> Writer<'a> {
// Push out the indent level and write each component, line by line
pub fn write_body_indented(&mut self, children: &[BodyNode]) -> Result {
self.out.indent += 1;
self.out.indent_level += 1;
self.write_body_no_indent(children)?;
self.out.indent -= 1;
self.out.indent_level -= 1;
Ok(())
}
@@ -132,12 +132,45 @@ impl<'a> Writer<'a> {
Ok(())
}
pub(crate) fn is_short_attrs(&mut self, attributes: &[ElementAttrNamed]) -> usize {
pub(crate) fn attr_value_len(&mut self, value: &ElementAttrValue) -> usize {
match value {
ElementAttrValue::AttrOptionalExpr { condition, value } => {
let condition_len = self.retrieve_formatted_expr(condition).len();
let value_len = self.attr_value_len(value);
condition_len + value_len + 6
}
ElementAttrValue::AttrLiteral(lit) => ifmt_to_string(lit).len(),
ElementAttrValue::AttrExpr(expr) => expr.span().line_length(),
ElementAttrValue::EventTokens(tokens) => {
let location = Location::new(tokens.span().start());
let len = if let std::collections::hash_map::Entry::Vacant(e) =
self.cached_formats.entry(location)
{
let formatted = prettyplease::unparse_expr(tokens);
let len = if formatted.contains('\n') {
10000
} else {
formatted.len()
};
e.insert(formatted);
len
} else {
self.cached_formats[&location].len()
};
len
}
}
}
pub(crate) fn is_short_attrs(&mut self, attributes: &[AttributeType]) -> usize {
let mut total = 0;
for attr in attributes {
if self.current_span_is_primary(attr.attr.start()) {
'line: for line in self.src[..attr.attr.start().start().line - 1].iter().rev() {
if self.current_span_is_primary(attr.start()) {
'line: for line in self.src[..attr.start().start().line - 1].iter().rev() {
match (line.trim().starts_with("//"), line.is_empty()) {
(true, _) => return 100000,
(_, true) => continue 'line,
@@ -146,40 +179,25 @@ impl<'a> Writer<'a> {
}
}
total += match &attr.attr {
ElementAttr::AttrText { value, name } => {
ifmt_to_string(value).len() + name.span().line_length() + 6
}
ElementAttr::AttrExpression { name, value } => {
value.span().line_length() + name.span().line_length() + 6
}
ElementAttr::CustomAttrText { value, name } => {
ifmt_to_string(value).len() + name.to_token_stream().to_string().len() + 6
}
ElementAttr::CustomAttrExpression { name, value } => {
name.to_token_stream().to_string().len() + value.span().line_length() + 6
}
ElementAttr::EventTokens { tokens, name } => {
let location = Location::new(tokens.span().start());
let len = if let std::collections::hash_map::Entry::Vacant(e) =
self.cached_formats.entry(location)
{
let formatted = prettyplease::unparse_expr(tokens);
let len = if formatted.contains('\n') {
10000
} else {
formatted.len()
};
e.insert(formatted);
len
} else {
self.cached_formats[&location].len()
match attr {
AttributeType::Named(attr) => {
let name_len = match &attr.attr.name {
dioxus_rsx::ElementAttrName::BuiltIn(name) => {
let name = name.to_string();
name.len()
}
dioxus_rsx::ElementAttrName::Custom(name) => name.value().len() + 2,
};
len + name.span().line_length() + 6
total += name_len;
total += self.attr_value_len(&attr.attr.value);
}
AttributeType::Spread(expr) => {
let expr_len = self.retrieve_formatted_expr(expr).len();
total += expr_len + 3;
}
};
total += 6;
}
total
@@ -218,7 +236,7 @@ impl<'a> Writer<'a> {
}
}
trait SpanLength {
pub(crate) trait SpanLength {
fn line_length(&self) -> usize;
}
impl SpanLength for Span {
+1 -1
View File
@@ -12,7 +12,7 @@ macro_rules! twoway {
#[test]
fn $name() {
let src = include_str!(concat!("./samples/", stringify!($name), ".rsx"));
let formatted = dioxus_autofmt::fmt_file(src);
let formatted = dioxus_autofmt::fmt_file(src, Default::default());
let out = dioxus_autofmt::apply_formats(src, formatted);
// normalize line endings
let out = out.replace("\r", "");
+1 -1
View File
@@ -33,7 +33,7 @@ rsx! {
}
// No children, minimal props
img { class: "mb-6 mx-auto h-24", src: "artemis-assets/images/friends.png", alt: "" }
img { class: "mb-6 mx-auto h-24", src: "artemis-assets/images/friends.png" }
// One level compression
div {
+10 -5
View File
@@ -1,10 +1,12 @@
use dioxus_autofmt::{IndentOptions, IndentType};
macro_rules! twoway {
($val:literal => $name:ident) => {
($val:literal => $name:ident ($indent:expr)) => {
#[test]
fn $name() {
let src_right = include_str!(concat!("./wrong/", $val, ".rsx"));
let src_wrong = include_str!(concat!("./wrong/", $val, ".wrong.rsx"));
let formatted = dioxus_autofmt::fmt_file(src_wrong);
let formatted = dioxus_autofmt::fmt_file(src_wrong, $indent);
let out = dioxus_autofmt::apply_formats(src_wrong, formatted);
// normalize line endings
@@ -16,8 +18,11 @@ macro_rules! twoway {
};
}
twoway!("comments" => comments);
twoway!("comments-4sp" => comments_4sp (IndentOptions::new(IndentType::Spaces, 4)));
twoway!("comments-tab" => comments_tab (IndentOptions::new(IndentType::Tabs, 4)));
twoway!("multi" => multi);
twoway!("multi-4sp" => multi_4sp (IndentOptions::new(IndentType::Spaces, 4)));
twoway!("multi-tab" => multi_tab (IndentOptions::new(IndentType::Tabs, 4)));
twoway!("multiexpr" => multiexpr);
twoway!("multiexpr-4sp" => multiexpr_4sp (IndentOptions::new(IndentType::Spaces, 4)));
twoway!("multiexpr-tab" => multiexpr_tab (IndentOptions::new(IndentType::Tabs, 4)));
@@ -0,0 +1,7 @@
rsx! {
div {
// Comments
class: "asdasd",
"hello world"
}
}
@@ -0,0 +1,5 @@
rsx! {
div {
// Comments
class: "asdasd", "hello world" }
}
@@ -0,0 +1,3 @@
fn app(cx: Scope) -> Element {
cx.render(rsx! { div { "hello world" } })
}
@@ -0,0 +1,5 @@
fn app(cx: Scope) -> Element {
cx.render(rsx! {
div {"hello world" }
})
}
@@ -0,0 +1,8 @@
fn ItWroks() {
cx.render(rsx! {
div { class: "flex flex-wrap items-center dark:text-white py-16 border-t font-light",
left,
right
}
})
}
@@ -0,0 +1,5 @@
fn ItWroks() {
cx.render(rsx! {
div { class: "flex flex-wrap items-center dark:text-white py-16 border-t font-light", left, right }
})
}
-3
View File
@@ -11,13 +11,10 @@ keywords = ["dom", "ui", "gui", "react"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
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", "visit"] }
serde = { version = "1.0.136", features = ["derive"] }
owo-colors = { version = "3.5.0", features = ["supports-colors"] }
prettyplease = { workspace = true }
[dev-dependencies]
indoc = "2.0.3"
+2 -2
View File
@@ -6,7 +6,7 @@
[![Discord chat][discord-badge]][discord-url]
[crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg
[crates-url]: https://crates.io/crates/dioxus-autofmt
[crates-url]: https://crates.io/crates/dioxus-check
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
@@ -16,7 +16,7 @@
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) |
[API Docs](https://docs.rs/dioxus-check) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
+4
View File
@@ -1,3 +1,7 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
mod check;
mod issues;
mod metadata;
-31
View File
@@ -1,31 +0,0 @@
# .github/workflows/build.yml
on:
release:
types: [created]
jobs:
release:
name: release ${{ matrix.target }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
archive: tar.gz tar.xz
- target: x86_64-unknown-linux-musl
archive: tar.gz tar.xz
- target: x86_64-apple-darwin
archive: tar.gz tar.xz
- target: x86_64-pc-windows-gnu
archive: zip
steps:
- uses: actions/checkout@master
- name: Compile and release
uses: rust-build/rust-build.action@latest
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUSTTARGET: ${{ matrix.target }}
ARCHIVE_TYPES: ${{ matrix.archive }}
-34
View File
@@ -1,34 +0,0 @@
name: github pages
on:
push:
paths:
- docs/**
branches:
- master
jobs:
deploy:
runs-on: ubuntu-20.04
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
steps:
- uses: actions/checkout@v2
- name: Setup mdBook
uses: peaceiris/actions-mdbook@v1
with:
mdbook-version: '0.4.10'
# mdbook-version: 'latest'
- run: cd docs && mdbook build
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@v4.2.3
with:
branch: gh-pages # The branch the action should deploy to.
folder: docs/book # The folder the action should deploy.
target-folder: docs/nightly/cli
repository-name: dioxuslabs/docsite
clean: false
token: ${{ secrets.DEPLOY_KEY }} # let's pretend I don't need it for now
-52
View File
@@ -1,52 +0,0 @@
on: [push, pull_request]
name: Rust CI
jobs:
check:
name: Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- run: cargo check
test:
name: Test Suite
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- run: cargo test
fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- run: rustup component add rustfmt
- run: cargo fmt --all -- --check
# clippy:
# name: Clippy
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v2
# - uses: actions-rs/toolchain@v1
# with:
# profile: minimal
# toolchain: stable
# override: true
# - uses: Swatinem/rust-cache@v1
# - run: rustup component add clippy
# - uses: actions-rs/cargo@v1
# with:
# command: clippy
# args: -- -D warnings
-4778
View File
File diff suppressed because it is too large. Load diff
+9 -11
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-cli"
version = "0.4.1"
version = "0.4.3"
authors = ["Jonathan Kelley"]
edition = "2021"
description = "CLI tool for developing, testing, and publishing Dioxus apps"
@@ -22,18 +22,15 @@ serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
toml = "0.5.8"
fs_extra = "1.2.0"
cargo_toml = "0.11.4"
cargo_toml = "0.16.0"
futures = "0.3.21"
notify = { version = "5.0.0-pre.16", features = ["serde"] }
html_parser = { workspace = true }
binary-install = "0.0.2"
convert_case = "0.5.0"
cargo_metadata = "0.15.0"
tokio = { version = "1.16.1", features = ["full"] }
tokio = { version = "1.16.1", features = ["fs", "sync", "rt", "macros"] }
atty = "0.2.14"
regex = "1.5.4"
chrono = "0.4.19"
anyhow = "1.0.53"
anyhow = "1"
hyper = "0.14.17"
hyper-rustls = "0.23.2"
indicatif = "0.17.5"
@@ -59,7 +56,6 @@ tar = "0.4.38"
zip = "0.6.2"
tower = "0.4.12"
syn = { version = "2.0", features = ["full", "extra-traits"] }
proc-macro2 = { version = "1.0", features = ["span-locations"] }
lazy_static = "1.4.0"
# plugin packages
@@ -71,14 +67,15 @@ mlua = { version = "0.8.1", features = [
"macros",
], optional = true }
ctrlc = "3.2.3"
gitignore = "1.0.7"
open = "4.1.0"
cargo-generate = "0.18"
toml_edit = "0.19.11"
# bundling
tauri-bundler = { version = "=1.3.0", features = ["native-tls-vendored"] }
tauri-utils = "=1.4.*"
tauri-bundler = { version = "=1.4.*", features = ["native-tls-vendored"] }
tauri-utils = "=1.5.*"
manganis-cli-support= { git = "https://github.com/DioxusLabs/collect-assets", features = ["webp", "html"] }
dioxus-autofmt = { workspace = true }
dioxus-check = { workspace = true }
@@ -88,6 +85,7 @@ 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" }
gitignore = "1.0.8"
[features]
default = []
+6 -6
View File
@@ -4,14 +4,14 @@
</div>
The **dioxus-cli** (inspired by wasm-pack and webpack) is a tool for getting Dioxus projects up and running.
It handles all building, bundling, development and publishing to simplify development.
It handles building, bundling, development and publishing to simplify development.
## Installation
### Install the stable version (recommended)
```
cargo install dioxus-cli --locked
```shell
cargo install dioxus-cli
```
### Install the latest development build through git
@@ -20,7 +20,7 @@ To get the latest bug fixes and features, you can install the development versio
However, this is not fully tested.
That means you're probably going to have more bugs despite having the latest bug fixes.
```
```shell
cargo install --git https://github.com/DioxusLabs/dioxus dioxus-cli
```
@@ -29,7 +29,7 @@ and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
### Install from local folder
```
```shell
cargo install --path . --debug
```
@@ -40,7 +40,7 @@ It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxu
Alternatively, you can specify the template path:
```
```shell
dx create hello --template gh:dioxuslabs/dioxus-template
```
-1
View File
@@ -1 +0,0 @@
book
-6
View File
@@ -1,6 +0,0 @@
[book]
authors = ["YuKun Liu"]
language = "en"
multilingual = false
src = "src"
title = "Dioxus CLI"
-13
View File
@@ -1,13 +0,0 @@
# Summary
- [Introduction](./introduction.md)
- [Installation](./installation.md)
- [Create a project](./creating.md)
- [Configure a project](./configure.md)
- [Plugin development](./plugin/README.md)
- [API.Log](plugin/interface/log.md)
- [API.Command](plugin/interface/command.md)
- [API.OS](plugin/interface/os.md)
- [API.Directories](plugin/interface/dirs.md)
- [API.Network](plugin/interface/network.md)
- [API.Path](plugin/interface/path.md)
-197
View File
@@ -1,197 +0,0 @@
# Configure Project
This chapter will teach you how to configure the CLI with the `Dioxus.toml` file.
There's an [example](#config-example) which has comments to describe individual keys.
You can copy that or view this documentation for a more complete learning experience.
"🔒" indicates a mandatory item. Some headers are mandatory, but none of the keys inside them are. It might look weird, but it's normal. Simply don't include any keys.
## Structure
Each header has it's TOML form directly under it.
### Application 🔒
```toml
[application]
```
Application-wide configuration. Applies to both web and desktop.
1. **name** 🔒 - Project name & title.
```toml
name = "my_project"
```
2. **default_platform** 🔒 - The platform this project targets
```toml
# Currently supported platforms: web, desktop
default_platform = "web"
```
3. **out_dir** - The directory to place the build artifacts from `dx build` or `dx serve` into. This is also where the `assets` directory will be copied into.
```toml
out_dir = "dist"
```
4. **asset_dir** - The directory with your static assets. The CLI will automatically copy these assets into the **out_dir** after a build/serve.
```toml
asset_dir = "public"
```
5. **sub_package** - The sub package in the workspace to build by default.
```toml
sub_package = "my-crate"
```
### Web.App 🔒
```toml
[web.app]
```
Web-specific configuration.
1. **title** - The title of the web page.
```toml
# HTML title tag content
title = "project_name"
```
2. **base_path** - The base path to build the application for serving at. This can be useful when serving your application in a subdirectory under a domain. For example when building a site to be served on GitHub Pages.
```toml
# The application will be served at domain.com/my_application/, so we need to modify the base_path to the path where the application will be served
base_path = "my_application"
```
### Web.Watcher ✍
```toml
[web.watcher]
```
Development server configuration.
1. **reload_html** - If this is true, the cli will rebuild the index.html file every time the application is rebuilt
```toml
reload_html = true
```
2. **watch_path** - The files & directories to monitor for changes
```toml
watch_path = ["src", "public"]
```
3. **index_on_404** - If enabled, Dioxus will serve the root page when a route is not found.
*This is needed when serving an application that uses the router*.
However, when serving your app using something else than Dioxus (e.g. GitHub Pages), you will have to check how to configure it on that platform.
In GitHub Pages, you can make a copy of `index.html` named `404.html` in the same directory.
```toml
index_on_404 = true
```
### Web.Resource 🔒
```toml
[web.resource]
```
Static resource configuration.
1. **style** - CSS files to include in your application.
```toml
style = [
# Include from public_dir.
"./assets/style.css",
# Or some asset from online cdn.
"https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.css"
]
```
2. **script** - JavaScript files to include in your application.
```toml
script = [
# Include from asset_dir.
"./public/index.js",
# Or from an online CDN.
"https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js"
]
```
### Web.Resource.Dev 🔒
```toml
[web.resource.dev]
```
This is the same as [`[web.resource]`](#webresource-), but it only works in development servers.
For example, if you want to include a file in a `dx serve` server, but not a `dx serve --release` server, put it here.
### Web.Proxy
```toml
[[web.proxy]]
```
Configuration related to any proxies your application requires during development. Proxies will forward requests to a new service.
1. **backend** - The URL to the server to proxy. The CLI will forward any requests under the backend relative route to the backend instead of returning 404
```toml
backend = "http://localhost:8000/api/"
```
This will cause any requests made to the dev server with prefix /api/ to be redirected to the backend server at http://localhost:8000. The path and query parameters will be passed on as-is (path rewriting is currently not supported).
## Config example
This includes all fields, mandatory or not.
```toml
[application]
# App name
name = "project_name"
# The Dioxus platform to default to
default_platform = "web"
# `build` & `serve` output path
out_dir = "dist"
# The static resource path
asset_dir = "public"
[web.app]
# HTML title tag content
title = "project_name"
[web.watcher]
# When watcher is triggered, regenerate the `index.html`
reload_html = true
# Which files or dirs will be monitored
watch_path = ["src", "public"]
# Include style or script assets
[web.resource]
# CSS style file
style = []
# Javascript code file
script = []
[web.resource.dev]
# Same as [web.resource], but for development servers
# CSS style file
style = []
# JavaScript files
script = []
[[web.proxy]]
backend = "http://localhost:8000/api/"
```
-37
View File
@@ -1,37 +0,0 @@
# Create a Project
Once you have the Dioxus CLI installed, you can use it to create your own project!
## Initializing a default project
First, run the `dx create` command to create a new project:
```
dx create hello-dioxus
```
> It will clone this [template](https://github.com/DioxusLabs/dioxus-template).
> This default template is used for `web` platform application.
>
> You can choose to create your project from a different template by passing the `template` argument:
> ```
> dx init hello-dioxus --template=gh:dioxuslabs/dioxus-template
> ```
Next, navigate into your new project:
```
cd hello-dioxus
```
> Make sure the WASM target is installed before running the projects.
> You can install the WASM target for rust using rustup:
> ```
> rustup target add wasm32-unknown-unknown
> ```
Finally, serve your project:
```
dx serve
```
By default, the CLI serves your website at [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/).
-23
View File
@@ -1,23 +0,0 @@
# Installation
## Install the latest development build through git
To get the latest bug fixes and features, you can install the development version from git.
```
cargo install --git https://github.com/Dioxuslabs/cli
```
This will download `Dioxus-CLI` source from GitHub master branch,
and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
## Install stable through `crates.io`
The published version of the Dioxus CLI is updated less often, but is more stable than the git version.
```
cargo install dioxus-cli --locked
```
Run `dx --help` for a list of all the available commands.
Furthermore, you can run `dx <COMMAND> --help` to get help with a specific command.
-18
View File
@@ -1,18 +0,0 @@
# Introduction
The 📦✨ **Dioxus CLI** is a tool to help get Dioxus projects off the ground.
## Features
* Build and pack a Dioxus project
* `html` to `rsx` conversion tool
* Hot Reload for `web` platform
* Create a Dioxus project from `git` repo
* And more!
<!-- Checkmarks don't render on the website, so I've just made a normal list. You can uncomment this if the website rendering is fixed.
- [x] `html` to `rsx` conversion tool
- [x] Hot Reload for `web` platform
- [x] Create a Dioxus project from `git` repo
- [x] Build & pack Dioxus project
- [ ] Automatically format Dioxus `rsx` code
-->
-140
View File
@@ -1,140 +0,0 @@
# CLI Plugin development
**IMPORTANT: Ignore this documentation. Plugins are yet to be released and chances are it won't work for you. This is just what plugins *could* look like.**
In the past we used `dx tool` to use and install tools, but it was a flawed system.
Tools were hard-coded by us, but people want more tools than we could code, so this plugin system was made to let
anyone develop plugins and use them in Dioxus projects.
Plugin resources:
* [Source code](https://github.com/DioxusLabs/dioxus/tree/master/packages/cli/src/plugin)
* [Unofficial Dioxus plugin community](https://github.com/DioxusPluginCommunity). Contains certain plugins you can use right now.
### Why Lua?
We chose Lua `5.4` to be the plugin developing language,
because it's extremely lightweight, embeddable and easy to learn.
We installed Lua into the CLI, so you don't need to do it yourself.
Lua resources:
* [Official website](https://www.lua.org/). You can basically find everything here.
* [Awesome Lua](https://github.com/LewisJEllis/awesome-lua). Additional resources (such as Lua plugins for your favorite IDE), and other *awesome* tools!
## Creating a plugin
A plugin is just an `init.lua` file.
You can include other files using `dofile(path)`.
You need to have a plugin and a manager instance, which you can get using `require`:
```lua
local plugin = require("plugin")
local manager = require("manager")
```
You need to set some `manager` fields and then initialize the plugin:
```lua
manager.name = "My first plugin"
manager.repository = "https://github.com/john-doe/my-first-plugin" -- The repository URL.
manager.author = "John Doe <john.doe@example.com>"
manager.version = "0.1.0"
plugin.init(manager)
```
You also need to return the `manager`, which basically represents your plugin:
```lua
-- Your code here.
-- End of file.
manager.serve.interval = 1000
return manager
```
And you're ready to go. Now, go and have a look at the stuff below and the API documentation.
### Plugin info
You will encounter this type in the events below. The keys are as follows:
* `name: string` - The name of the plugin.
* `repository: string` - The plugin repository URL.
* `author: string` - The author of the plugin.
* `version: string` - The plugin version.
### Event management
The plugin library has certain events that you can subscribe to.
* `manager.on_init` - Triggers the first time the plugin is loaded.
* `manager.build.on_start(info)` - Triggers before the build process. E.g., before `dx build`.
* `manager.build.on_finish(info)` - Triggers after the build process. E.g., after `dx build`.
* `manager.serve.on_start(info)` - Triggers before the serving process. E.g., before `dx serve`.
* `manager.serve.on_rebuild_start(info)` - Triggers before the server rebuilds the web with hot reload.
* `manager.serve.on_rebuild_end(info)` - Triggers after the server rebuilds the web with hot reload.
* `manager.serve.on_shutdown` - Triggers when the server is shutdown. E.g., when the `dx serve` process is terminated.
To subscribe to an event, you simply need to assign it to a function:
```lua
manager.build.on_start = function (info)
log.info("[plugin] Build starting: " .. info.name)
end
```
### Plugin template
```lua
package.path = library_dir .. "/?.lua"
local plugin = require("plugin")
local manager = require("manager")
-- deconstruct api functions
local log = plugin.log
-- plugin information
manager.name = "Hello Dixous Plugin"
manager.repository = "https://github.com/mrxiaozhuox/hello-dioxus-plugin"
manager.author = "YuKun Liu <mrxzx.info@gmail.com>"
manager.version = "0.0.1"
-- init manager info to plugin api
plugin.init(manager)
manager.on_init = function ()
-- when the first time plugin been load, this function will be execute.
-- system will create a `dcp.json` file to verify init state.
log.info("[plugin] Start to init plugin: " .. manager.name)
end
---@param info BuildInfo
manager.build.on_start = function (info)
-- before the build work start, system will execute this function.
log.info("[plugin] Build starting: " .. info.name)
end
---@param info BuildInfo
manager.build.on_finish = function (info)
-- when the build work is done, system will execute this function.
log.info("[plugin] Build finished: " .. info.name)
end
---@param info ServeStartInfo
manager.serve.on_start = function (info)
-- this function will after clean & print to run, so you can print some thing.
log.info("[plugin] Serve start: " .. info.name)
end
---@param info ServeRebuildInfo
manager.serve.on_rebuild = function (info)
-- this function will after clean & print to run, so you can print some thing.
local files = plugin.tool.dump(info.changed_files)
log.info("[plugin] Serve rebuild: '" .. files .. "'")
end
manager.serve.on_shutdown = function ()
log.info("[plugin] Serve shutdown")
end
manager.serve.interval = 1000
return manager
```
@@ -1,21 +0,0 @@
# Command Functions
You can use command functions to execute code and scripts.
Type definition:
```
Stdio: "Inherit" | "Piped" | "Null"
```
### `exec(commands: [string], stdout: Stdio, stderr: Stdio)`
You can use this function to run some commands on the current system.
```lua
local cmd = plugin.command
manager.test = function ()
cmd.exec({"git", "clone", "https://github.com/DioxusLabs/cli-plugin-library"})
end
```
> Warning: This function doesn't catch exceptions.
@@ -1,30 +0,0 @@
# Dirs Functions
Dirs functions are for getting various directory paths. Not to be confused with `plugin.path`.
### `plugin_dir() -> string`
Get the plugin's root directory path.
```lua
local path = plugin.dirs.plugin_dir()
-- example: ~/Development/DioxusCli/plugin/test-plugin/
```
### `bin_dir() -> string`
Get the plugin's binary directory path. Put binary files like `tailwind-cli` or `sass-cli` in this directory.
```lua
local path = plugin.dirs.bin_dir()
-- example: ~/Development/DioxusCli/plugin/test-plugin/bin/
```
### `temp_dir() -> string`
Get the plugin's temporary directory path. Put any temporary files here.
```lua
local path = plugin.dirs.bin_dir()
-- example: ~/Development/DioxusCli/plugin/test-plugin/temp/
```
@@ -1,48 +0,0 @@
# Log Functions
You can use log functions to print various logging information.
### `trace(info: string)`
Print trace log info.
```lua
local log = plugin.log
log.trace("trace information")
```
### `debug(info: string)`
Print debug log info.
```lua
local log = plugin.log
log.debug("debug information")
```
### `info(info: string)`
Print info log info.
```lua
local log = plugin.log
log.info("info information")
```
### `warn(info: string)`
Print warning log info.
```lua
local log = plugin.log
log.warn("warn information")
```
### `error(info: string)`
Print error log info.
```lua
local log = plugin.log
log.error("error information")
```
@@ -1,37 +0,0 @@
# Network Functions
You can use Network functions to download & read some data from the internet.
### `download_file(url: string, path: string) -> boolean`
Downloads a file from the specified URL,
and returns a `boolean` that represents the download status (true: success, false: failure).
You need to pass a target URL and a local path (where you want to save this file).
```lua
-- this file will download to plugin temp directory
local status = plugin.network.download_file(
"http://xxx.com/xxx.zip",
plugin.dirs.temp_dir()
)
if status != true then
log.error("Download Failed")
end
```
### `clone_repo(url: string, path: string) -> boolean`
Clone a repository from the given URL into the given path.
Returns a `boolean` that represents the clone status (true: success, false: failure).
The system executing this function must have git installed.
```lua
local status = plugin.network.clone_repo(
"http://github.com/mrxiaozhuox/dioxus-starter",
plugin.dirs.bin_dir()
)
if status != true then
log.error("Clone Failed")
end
```
@@ -1,11 +0,0 @@
# OS Functions
OS functions are for getting system information.
### `current_platform() -> string ("windows" | "macos" | "linux")`
Get the current OS platform.
```lua
local platform = plugin.os.current_platform()
```
@@ -1,38 +0,0 @@
# Path Functions
You can use path functions to perform operations on valid path strings.
### `join(path: string, extra: string) -> string`
<!-- TODO: Add specifics.
From the example given, it seems like it just creates a subdirectory path.
What would it do when "extending" file paths? -->
Extend a path; you can extend both directory and file paths.
```lua
local current_path = "~/hello/dioxus"
local new_path = plugin.path.join(current_path, "world")
-- new_path = "~/hello/dioxus/world"
```
### `parent(path: string) -> string`
Return the parent path of the specified path. The parent path is always a directory.
```lua
local current_path = "~/hello/dioxus"
local new_path = plugin.path.parent(current_path)
-- new_path = "~/hello/"
```
### `exists(path: string) -> boolean`
Check if the specified path exists, as either a file or a directory.
### `is_file(path: string) -> boolean`
Check if the specified path is a file.
### `is_dir(path: string) -> boolean`
Check if the specified path is a directory.
-18
View File
@@ -1,18 +0,0 @@
local Api = require("./interface")
local log = Api.log;
local manager = {
name = "Dioxus-CLI Plugin Demo",
repository = "http://github.com/DioxusLabs/cli",
author = "YuKun Liu <mrxzx.info@gmail.com>",
}
manager.onLoad = function ()
log.info("plugin loaded.")
end
manager.onStartBuild = function ()
log.warn("system start to build")
end
return manager
@@ -1,25 +0,0 @@
local interface = {}
if plugin_logger ~= nil then
interface.log = plugin_logger
else
interface.log = {
trace = function (info)
print("trace: " .. info)
end,
debug = function (info)
print("debug: " .. info)
end,
info = function (info)
print("info: " .. info)
end,
warn = function (info)
print("warn: " .. info)
end,
error = function (info)
print("error: " .. info)
end,
}
end
return interface
+2 -2
View File
@@ -1,5 +1,5 @@
// Dioxus-CLI
// https://github.com/DioxusLabs/cli
// https://github.com/DioxusLabs/dioxus/tree/master/packages/cli
(function () {
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -22,4 +22,4 @@
}
};
ws.onclose = reload_upon_connect;
})()
})()
+1 -1
View File
@@ -23,7 +23,7 @@ title = "Dioxus | An elegant GUI library for Rust"
index_on_404 = true
watch_path = ["src"]
watch_path = ["src", "examples"]
# include `assets` in web platform
[web.resource]
+127 -60
View File
@@ -2,31 +2,35 @@ use crate::{
config::{CrateConfig, ExecutableType},
error::{Error, Result},
tools::Tool,
DioxusConfig,
};
use cargo_metadata::{diagnostic::Diagnostic, Message};
use indicatif::{ProgressBar, ProgressStyle};
use lazy_static::lazy_static;
use manganis_cli_support::AssetManifestExt;
use serde::Serialize;
use std::{
fs::{copy, create_dir_all, File},
io::Read,
io::{Read, Write},
panic,
path::PathBuf,
time::Duration,
};
use wasm_bindgen_cli_support::Bindgen;
lazy_static! {
static ref PROGRESS_BARS: indicatif::MultiProgress = indicatif::MultiProgress::new();
}
#[derive(Serialize, Debug, Clone)]
pub struct BuildResult {
pub warnings: Vec<Diagnostic>,
pub elapsed_time: u128,
}
#[allow(unused)]
pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildResult> {
// [1] Build the project with cargo, generating a wasm32-unknown-unknown target (is there a more specific, better target to leverage?)
// [2] Generate the appropriate build folders
// [3] Wasm-bindgen the .wasm fiile, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
// [3] Wasm-bindgen the .wasm file, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
// [4] Wasm-opt the .wasm file with whatever optimizations need to be done
// [5][OPTIONAL] Builds the Tailwind CSS file using the Tailwind standalone binary
// [6] Link up the html page to the wasm module
@@ -41,6 +45,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
..
} = config;
let _gaurd = WebAssetConfigDropGuard::new();
// start to build the assets
let ignore_files = build_assets(config)?;
@@ -48,14 +54,25 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
// [1] Build the .wasm module
log::info!("🚅 Running build command...");
let cmd = subprocess::Exec::cmd("cargo");
let cmd = cmd
let wasm_check_command = std::process::Command::new("rustup")
.args(["show"])
.output()?;
let wasm_check_output = String::from_utf8(wasm_check_command.stdout).unwrap();
if !wasm_check_output.contains("wasm32-unknown-unknown") {
log::info!("wasm32-unknown-unknown target not detected, installing..");
let _ = std::process::Command::new("rustup")
.args(["target", "add", "wasm32-unknown-unknown"])
.output()?;
}
let cmd = subprocess::Exec::cmd("cargo")
.env("CARGO_TARGET_DIR", target_dir)
.cwd(crate_dir)
.arg("build")
.arg("--target")
.arg("wasm32-unknown-unknown")
.arg("--message-format=json")
.arg("--quiet");
.arg("--message-format=json");
let cmd = if config.release {
cmd.arg("--release")
@@ -65,7 +82,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
let cmd = if config.verbose {
cmd.arg("--verbose")
} else {
cmd
cmd.arg("--quiet")
};
let cmd = if config.custom_profile.is_some() {
@@ -82,6 +99,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
cmd
};
let cmd = cmd.args(&config.cargo_args);
let cmd = match executable {
ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
@@ -239,19 +258,28 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
}
}
if !skip_assets {
process_assets(config)?;
}
Ok(BuildResult {
warnings: warning_messages,
elapsed_time: t_start.elapsed().as_millis(),
})
}
pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResult> {
pub fn build_desktop(
config: &CrateConfig,
_is_serve: bool,
skip_assets: 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 = subprocess::Exec::cmd("cargo")
.env("CARGO_TARGET_DIR", &config.target_dir)
.cwd(&config.crate_dir)
.arg("build")
.arg("--message-format=json");
@@ -261,6 +289,8 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
}
if config.verbose {
cmd = cmd.arg("--verbose");
} else {
cmd = cmd.arg("--quiet");
}
if config.custom_profile.is_some() {
@@ -273,6 +303,14 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
cmd = cmd.arg("--features").arg(features_str);
}
if let Some(target) = &config.target {
cmd = cmd.arg("--target").arg(target);
}
let target_platform = config.target.as_deref().unwrap_or("");
cmd = cmd.args(&config.cargo_args);
let cmd = match &config.executable {
crate::ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
crate::ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
@@ -290,12 +328,17 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
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)
config
.target_dir
.join(target_platform)
.join(release_type)
.join(name)
}
crate::ExecutableType::Example(name) => {
file_name = name.clone();
config
.target_dir
.join(target_platform)
.join(release_type)
.join("examples")
.join(name)
@@ -312,7 +355,7 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
if !config.out_dir.is_dir() {
create_dir_all(&config.out_dir)?;
}
copy(res_path, &config.out_dir.join(target_file))?;
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() {
@@ -347,6 +390,13 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
}
}
if !skip_assets {
// Collect assets
process_assets(config)?;
// Create the __assets_head.html file for bundling
create_assets_head(config)?;
}
log::info!(
"🚩 Build completed: [./{}]",
config
@@ -366,11 +416,19 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
})
}
fn create_assets_head(config: &CrateConfig) -> Result<()> {
let manifest = config.asset_manifest();
let mut file = File::create(config.out_dir.join("__assets_head.html"))?;
file.write_all(manifest.head().as_bytes())?;
Ok(())
}
fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
let mut warning_messages: Vec<Diagnostic> = vec![];
let pb = ProgressBar::new_spinner();
let mut pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(200));
pb = PROGRESS_BARS.add(pb);
pb.set_style(
ProgressStyle::with_template("{spinner:.dim.bold} {wide_msg}")
.unwrap()
@@ -378,14 +436,6 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
);
pb.set_message("💼 Waiting to start build the project...");
struct StopSpinOnDrop(ProgressBar);
impl Drop for StopSpinOnDrop {
fn drop(&mut self) {
self.0.finish_and_clear();
}
}
let stdout = cmd.detached().stream_stdout()?;
let reader = std::io::BufReader::new(stdout);
@@ -421,13 +471,17 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
std::process::exit(1);
}
}
_ => (), // Unknown message
_ => {
// Unknown message
}
}
}
Ok(warning_messages)
}
pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
pub fn gen_page(config: &CrateConfig, serve: bool, skip_assets: bool) -> String {
let _gaurd = WebAssetConfigDropGuard::new();
let crate_root = crate::cargo::crate_root().unwrap();
let custom_html_file = crate_root.join("index.html");
let mut html = if custom_html_file.is_file() {
@@ -442,14 +496,14 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
String::from(include_str!("./assets/index.html"))
};
let resouces = config.web.resource.clone();
let resources = config.dioxus_config.web.resource.clone();
let mut style_list = resouces.style.unwrap_or_default();
let mut script_list = resouces.script.unwrap_or_default();
let mut style_list = resources.style.unwrap_or_default();
let mut script_list = resources.script.unwrap_or_default();
if serve {
let mut dev_style = resouces.dev.style.clone().unwrap_or_default();
let mut dev_script = resouces.dev.script.unwrap_or_default();
let mut dev_style = resources.dev.style.clone().unwrap_or_default();
let mut dev_script = resources.dev.script.unwrap_or_default();
style_list.append(&mut dev_style);
script_list.append(&mut dev_script);
}
@@ -462,13 +516,18 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
))
}
if config
.dioxus_config
.application
.tools
.clone()
.unwrap_or_default()
.contains_key("tailwindcss")
{
style_str.push_str("<link rel=\"stylesheet\" href=\"tailwind.css\">\n");
style_str.push_str("<link rel=\"stylesheet\" href=\"/{base_path}/tailwind.css\">\n");
}
if !skip_assets {
let manifest = config.asset_manifest();
style_str.push_str(&manifest.head());
}
replace_or_insert_before("{style_include}", &style_str, "</head", &mut html);
@@ -490,11 +549,11 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
);
}
let base_path = match &config.web.app.base_path {
let base_path = match &config.dioxus_config.web.app.base_path {
Some(path) => path,
None => ".",
};
let app_name = &config.application.name;
let app_name = &config.dioxus_config.application.name;
// Check if a script already exists
if html.contains("{app_name}") && html.contains("{base_path}") {
html = html.replace("{app_name}", app_name);
@@ -519,6 +578,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
}
let title = config
.dioxus_config
.web
.app
.title
@@ -689,34 +749,41 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
Ok(result)
}
// use binary_install::{Cache, Download};
/// Process any assets collected from the binary
fn process_assets(config: &CrateConfig) -> anyhow::Result<()> {
let manifest = config.asset_manifest();
// /// Attempts to find `wasm-opt` in `PATH` locally, or failing that downloads a
// /// precompiled binary.
// ///
// /// Returns `Some` if a binary was found or it was successfully downloaded.
// /// Returns `None` if a binary wasn't found in `PATH` and this platform doesn't
// /// have precompiled binaries. Returns an error if we failed to download the
// /// binary.
// pub fn find_wasm_opt(
// cache: &Cache,
// install_permitted: bool,
// ) -> Result<install::Status, failure::Error> {
// // First attempt to look up in PATH. If found assume it works.
// if let Ok(path) = which::which("wasm-opt") {
// PBAR.info(&format!("found wasm-opt at {:?}", path));
let static_asset_output_dir = PathBuf::from(
config
.dioxus_config
.web
.app
.base_path
.clone()
.unwrap_or_default(),
);
let static_asset_output_dir = config.out_dir.join(static_asset_output_dir);
// match path.as_path().parent() {
// Some(path) => return Ok(install::Status::Found(Download::at(path))),
// None => {}
// }
// }
manifest.copy_static_assets_to(static_asset_output_dir)?;
// let version = "version_78";
// Ok(install::download_prebuilt(
// &install::Tool::WasmOpt,
// cache,
// version,
// install_permitted,
// )?)
// }
Ok(())
}
pub(crate) struct WebAssetConfigDropGuard;
impl WebAssetConfigDropGuard {
pub fn new() -> Self {
// Set up the collect asset config
manganis_cli_support::Config::default()
.with_assets_serve_location("/")
.save();
Self {}
}
}
impl Drop for WebAssetConfigDropGuard {
fn drop(&mut self) {
// Reset the config
manganis_cli_support::Config::default().save();
}
}
+147 -66
View File
@@ -1,3 +1,4 @@
use dioxus_autofmt::{IndentOptions, IndentType};
use futures::{stream::FuturesUnordered, StreamExt};
use std::{fs, path::Path, process::exit};
@@ -26,16 +27,19 @@ pub struct Autoformat {
impl Autoformat {
// Todo: autoformat the entire crate
pub async fn autoformat(self) -> Result<()> {
let Autoformat { check, raw, file } = self;
// Default to formatting the project
if self.raw.is_none() && self.file.is_none() {
if let Err(e) = autoformat_project(self.check).await {
if raw.is_none() && file.is_none() {
if let Err(e) = autoformat_project(check).await {
eprintln!("error formatting project: {}", e);
exit(1);
}
}
if let Some(raw) = self.raw {
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0) {
if let Some(raw) = raw {
let indent = indentation_for(".")?;
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
println!("{}", inner);
} else {
// exit process with error
@@ -45,33 +49,90 @@ impl Autoformat {
}
// Format single file
if let Some(file) = self.file {
let file_content = fs::read_to_string(&file);
match file_content {
Ok(s) => {
let edits = dioxus_autofmt::fmt_file(&s);
let out = dioxus_autofmt::apply_formats(&s, edits);
match fs::write(&file, out) {
Ok(_) => {
println!("formatted {}", file);
}
Err(e) => {
eprintln!("failed to write formatted content to file: {}", e);
}
}
}
Err(e) => {
eprintln!("failed to open file: {}", e);
exit(1);
}
}
if let Some(file) = file {
refactor_file(file)?;
}
Ok(())
}
}
fn refactor_file(file: String) -> Result<(), Error> {
let indent = indentation_for(".")?;
let file_content = if file == "-" {
let mut contents = String::new();
std::io::stdin().read_to_string(&mut contents)?;
Ok(contents)
} else {
fs::read_to_string(&file)
};
let Ok(s) = file_content else {
eprintln!("failed to open file: {}", file_content.unwrap_err());
exit(1);
};
let edits = dioxus_autofmt::fmt_file(&s, indent);
let out = dioxus_autofmt::apply_formats(&s, edits);
if file == "-" {
print!("{}", out);
} else if let Err(e) = fs::write(&file, out) {
eprintln!("failed to write formatted content to file: {e}",);
} else {
println!("formatted {}", file);
}
Ok(())
}
fn get_project_files(config: &CrateConfig) -> Vec<PathBuf> {
let mut files = vec![];
let gitignore_path = config.crate_dir.join(".gitignore");
if gitignore_path.is_file() {
let gitigno = gitignore::File::new(gitignore_path.as_path()).unwrap();
if let Ok(git_files) = gitigno.included_files() {
let git_files = git_files
.into_iter()
.filter(|f| f.ends_with(".rs") && !is_target_dir(f));
files.extend(git_files)
};
} else {
collect_rs_files(&config.crate_dir, &mut files);
}
files
}
fn is_target_dir(file: &Path) -> bool {
let stripped = if let Ok(cwd) = std::env::current_dir() {
file.strip_prefix(cwd).unwrap_or(file)
} else {
file
};
if let Some(first) = stripped.components().next() {
first.as_os_str() == "target"
} else {
false
}
}
async fn format_file(
path: impl AsRef<Path>,
indent: IndentOptions,
) -> Result<usize, tokio::io::Error> {
let contents = tokio::fs::read_to_string(&path).await?;
let edits = dioxus_autofmt::fmt_file(&contents, indent);
let len = edits.len();
if !edits.is_empty() {
let out = dioxus_autofmt::apply_formats(&contents, edits);
tokio::fs::write(path, out).await?;
}
Ok(len)
}
/// Read every .rs file accessible when considering the .gitignore and try to format it
///
/// Runs using Tokio for multithreading, so it should be really really fast
@@ -80,42 +141,27 @@ impl Autoformat {
async fn autoformat_project(check: bool) -> Result<()> {
let crate_config = crate::CrateConfig::new(None)?;
let mut files_to_format = vec![];
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
let files_to_format = get_project_files(&crate_config);
if files_to_format.is_empty() {
return Ok(());
}
let indent = indentation_for(&files_to_format[0])?;
let counts = files_to_format
.into_iter()
.filter(|file| {
if file.components().any(|f| f.as_os_str() == "target") {
return false;
}
true
})
.map(|path| async {
let _path = path.clone();
let res = tokio::spawn(async move {
let contents = tokio::fs::read_to_string(&path).await?;
let edits = dioxus_autofmt::fmt_file(&contents);
let len = edits.len();
if !edits.is_empty() {
let out = dioxus_autofmt::apply_formats(&contents, edits);
tokio::fs::write(&path, out).await?;
}
Ok(len) as Result<usize, tokio::io::Error>
})
.await;
let path_clone = path.clone();
let res = tokio::spawn(format_file(path, indent.clone())).await;
match res {
Err(err) => {
eprintln!("error formatting file: {}\n{err}", _path.display());
eprintln!("error formatting file: {}\n{err}", path_clone.display());
None
}
Ok(Err(err)) => {
eprintln!("error formatting file: {}\n{err}", _path.display());
eprintln!("error formatting file: {}\n{err}", path_clone.display());
None
}
Ok(Ok(res)) => Some(res),
@@ -125,13 +171,7 @@ async fn autoformat_project(check: bool) -> Result<()> {
.collect::<Vec<_>>()
.await;
let files_formatted: usize = counts
.into_iter()
.map(|f| match f {
Some(res) => res,
_ => 0,
})
.sum();
let files_formatted: usize = counts.into_iter().flatten().sum();
if files_formatted > 0 && check {
eprintln!("{} files needed formatting", files_formatted);
@@ -141,26 +181,67 @@ async fn autoformat_project(check: bool) -> Result<()> {
Ok(())
}
fn collect_rs_files(folder: &Path, files: &mut Vec<PathBuf>) {
let Ok(folder) = folder.read_dir() else {
fn indentation_for(file_or_dir: impl AsRef<Path>) -> Result<IndentOptions> {
let out = std::process::Command::new("cargo")
.args(["fmt", "--", "--print-config", "current"])
.arg(file_or_dir.as_ref())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.output()?;
if !out.status.success() {
return Err(Error::CargoError("cargo fmt failed".into()));
}
let config = String::from_utf8_lossy(&out.stdout);
let hard_tabs = config
.lines()
.find(|line| line.starts_with("hard_tabs "))
.and_then(|line| line.split_once('='))
.map(|(_, value)| value.trim() == "true")
.ok_or_else(|| {
Error::RuntimeError("Could not find hard_tabs option in rustfmt config".into())
})?;
let tab_spaces = config
.lines()
.find(|line| line.starts_with("tab_spaces "))
.and_then(|line| line.split_once('='))
.map(|(_, value)| value.trim().parse::<usize>())
.ok_or_else(|| {
Error::RuntimeError("Could not find tab_spaces option in rustfmt config".into())
})?
.map_err(|_| {
Error::RuntimeError("Could not parse tab_spaces option in rustfmt config".into())
})?;
Ok(IndentOptions::new(
if hard_tabs {
IndentType::Tabs
} else {
IndentType::Spaces
},
tab_spaces,
))
}
fn collect_rs_files(folder: &impl AsRef<Path>, files: &mut Vec<PathBuf>) {
if is_target_dir(folder.as_ref()) {
return;
}
let Ok(folder) = folder.as_ref().read_dir() else {
return;
};
// load the gitignore
for entry in folder {
let Ok(entry) = entry else {
continue;
};
let path = entry.path();
if path.is_dir() {
collect_rs_files(&path, files);
}
if let Some(ext) = path.extension() {
if ext == "rs" {
if ext == "rs" && !is_target_dir(&path) {
files.push(path);
}
}
+54 -12
View File
@@ -1,6 +1,8 @@
use crate::cfg::Platform;
#[cfg(feature = "plugin")]
use crate::plugin::PluginManager;
use crate::server::fullstack::FullstackServerEnvGuard;
use crate::server::fullstack::FullstackWebEnvGuard;
use crate::{cfg::Platform, WebAssetConfigDropGuard};
use super::*;
@@ -13,23 +15,26 @@ pub struct Build {
}
impl Build {
pub fn build(self, bin: Option<PathBuf>) -> Result<()> {
pub fn build(self, bin: Option<PathBuf>, target_dir: Option<&std::path::Path>) -> Result<()> {
let mut crate_config = crate::CrateConfig::new(bin)?;
if let Some(target_dir) = target_dir {
crate_config.target_dir = target_dir.to_path_buf();
}
// change the release state.
crate_config.with_release(self.build.release);
crate_config.with_verbose(self.build.verbose);
if self.build.example.is_some() {
crate_config.as_example(self.build.example.unwrap());
crate_config.as_example(self.build.example.clone().unwrap());
}
if self.build.profile.is_some() {
crate_config.set_profile(self.build.profile.unwrap());
crate_config.set_profile(self.build.profile.clone().unwrap());
}
if self.build.features.is_some() {
crate_config.set_features(self.build.features.unwrap());
crate_config.set_features(self.build.features.clone().unwrap());
}
let platform = self
@@ -37,19 +42,56 @@ impl Build {
.platform
.unwrap_or(crate_config.dioxus_config.application.default_platform);
#[cfg(feature = "plugin")]
let _ = PluginManager::on_build_start(&crate_config, &platform);
if let Some(target) = self.build.target.clone() {
crate_config.set_target(target);
}
crate_config.set_cargo_args(self.build.cargo_args.clone());
// #[cfg(feature = "plugin")]
// let _ = PluginManager::on_build_start(&crate_config, &platform);
match platform {
Platform::Web => {
crate::builder::build(&crate_config, true)?;
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
}
Platform::Desktop => {
crate::builder::build_desktop(&crate_config, false)?;
crate::builder::build_desktop(&crate_config, false, self.build.skip_assets)?;
}
Platform::Fullstack => {
// Fullstack mode must be built with web configs on the desktop (server) binary as well as the web binary
let _config = WebAssetConfigDropGuard::new();
{
let mut web_config = crate_config.clone();
let _gaurd = FullstackWebEnvGuard::new(&self.build);
let web_feature = self.build.client_feature;
let features = &mut web_config.features;
match features {
Some(features) => {
features.push(web_feature);
}
None => web_config.features = Some(vec![web_feature]),
};
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
}
{
let mut desktop_config = crate_config.clone();
let desktop_feature = self.build.server_feature;
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let _gaurd =
FullstackServerEnvGuard::new(self.build.force_debug, self.build.release);
crate::builder::build_desktop(&desktop_config, false, self.build.skip_assets)?;
}
}
}
let temp = gen_page(&crate_config.dioxus_config, false);
let temp = gen_page(&crate_config, false, self.build.skip_assets);
let mut file = std::fs::File::create(
crate_config
@@ -66,8 +108,8 @@ impl Build {
)?;
file.write_all(temp.as_bytes())?;
#[cfg(feature = "plugin")]
let _ = PluginManager::on_build_finish(&crate_config, &platform);
// #[cfg(feature = "plugin")]
// let _ = PluginManager::on_build_finish(&crate_config, &platform);
Ok(())
}
+31 -7
View File
@@ -76,8 +76,14 @@ impl Bundle {
crate_config.set_profile(self.build.profile.unwrap());
}
if let Some(target) = &self.build.target {
crate_config.set_target(target.to_string());
}
crate_config.set_cargo_args(self.build.cargo_args);
// build the desktop app
build_desktop(&crate_config, false)?;
build_desktop(&crate_config, false, false)?;
// copy the binary to the out dir
let package = crate_config.manifest.package.unwrap();
@@ -128,14 +134,27 @@ impl Bundle {
}
}
// Add all assets from collect assets to the bundle
{
let config = manganis_cli_support::Config::current();
let location = config.assets_serve_location().to_string();
let location = format!("./{}", location);
println!("Adding assets from {} to bundle", location);
if let Some(resources) = &mut bundle_settings.resources {
resources.push(location);
} else {
bundle_settings.resources = Some(vec![location]);
}
}
let mut settings = SettingsBuilder::new()
.project_out_directory(crate_config.out_dir)
.package_settings(PackageSettings {
product_name: crate_config.dioxus_config.application.name.clone(),
version: package.version,
description: package.description.unwrap_or_default(),
homepage: package.homepage,
authors: Some(package.authors),
version: package.version().to_string(),
description: package.description().unwrap_or_default().to_string(),
homepage: Some(package.homepage().unwrap_or_default().to_string()),
authors: Some(Vec::from(package.authors())),
default_run: Some(crate_config.dioxus_config.application.name.clone()),
})
.binaries(binaries)
@@ -148,6 +167,11 @@ impl Bundle {
.collect(),
);
}
if let Some(target) = &self.build.target {
settings = settings.target(target.to_string());
}
let settings = settings.build();
// on macos we need to set CI=true (https://github.com/tauri-apps/tauri/issues/2567)
@@ -156,9 +180,9 @@ impl Bundle {
tauri_bundler::bundle::bundle_project(settings.unwrap()).unwrap_or_else(|err|{
#[cfg(target_os = "macos")]
panic!("Failed to bundle project: {}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
panic!("Failed to bundle project: {:#?}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
#[cfg(not(target_os = "macos"))]
panic!("Failed to bundle project: {}", err);
panic!("Failed to bundle project: {:#?}", err);
});
Ok(())
+83 -9
View File
@@ -6,15 +6,16 @@ use super::*;
/// Config options for the build system.
#[derive(Clone, Debug, Default, Deserialize, Parser)]
pub struct ConfigOptsBuild {
/// The index HTML file to drive the bundling process [default: index.html]
#[arg(long)]
pub target: Option<PathBuf>,
/// Build in release mode [default: false]
#[clap(long)]
#[serde(default)]
pub release: bool,
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
#[clap(long)]
#[serde(default)]
pub force_debug: bool,
// Use verbose output [default: false]
#[clap(long)]
#[serde(default)]
@@ -32,17 +33,53 @@ pub struct ConfigOptsBuild {
#[clap(long, value_enum)]
pub platform: Option<Platform>,
/// Skip collecting assets from dependencies [default: false]
#[clap(long)]
#[serde(default)]
pub skip_assets: bool,
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
/// The feature to use for the client in a fullstack app [default: "web"]
#[clap(long, default_value_t = { "web".to_string() })]
pub client_feature: String,
/// The feature to use for the server in a fullstack app [default: "ssr"]
#[clap(long, default_value_t = { "ssr".to_string() })]
pub server_feature: String,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
impl From<ConfigOptsServe> for ConfigOptsBuild {
fn from(serve: ConfigOptsServe) -> Self {
Self {
target: serve.target,
release: serve.release,
verbose: serve.verbose,
example: serve.example,
profile: serve.profile,
platform: serve.platform,
features: serve.features,
client_feature: serve.client_feature,
server_feature: serve.server_feature,
skip_assets: serve.skip_assets,
force_debug: serve.force_debug,
cargo_args: serve.cargo_args,
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Parser)]
pub struct ConfigOptsServe {
/// The index HTML file to drive the bundling process [default: index.html]
#[arg(short, long)]
pub target: Option<PathBuf>,
/// Port of dev server
#[clap(long)]
#[clap(default_value_t = 8080)]
@@ -62,6 +99,11 @@ pub struct ConfigOptsServe {
#[serde(default)]
pub release: bool,
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
#[clap(long)]
#[serde(default)]
pub force_debug: bool,
// Use verbose output [default: false]
#[clap(long)]
#[serde(default)]
@@ -71,7 +113,7 @@ pub struct ConfigOptsServe {
#[clap(long)]
pub profile: Option<String>,
/// Build platform: support Web & Desktop [default: "default_platform"]
/// Build platform: support Web, Desktop, and Fullstack [default: "default_platform"]
#[clap(long, value_enum)]
pub platform: Option<Platform>,
@@ -89,6 +131,27 @@ pub struct ConfigOptsServe {
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
/// Skip collecting assets from dependencies [default: false]
#[clap(long)]
#[serde(default)]
pub skip_assets: bool,
/// The feature to use for the client in a fullstack app [default: "web"]
#[clap(long, default_value_t = { "web".to_string() })]
pub client_feature: String,
/// The feature to use for the server in a fullstack app [default: "ssr"]
#[clap(long, default_value_t = { "ssr".to_string() })]
pub server_feature: String,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Debug)]
@@ -99,6 +162,9 @@ pub enum Platform {
#[clap(name = "desktop")]
#[serde(rename = "desktop")]
Desktop,
#[clap(name = "fullstack")]
#[serde(rename = "fullstack")]
Fullstack,
}
/// Config options for the bundling system.
@@ -129,4 +195,12 @@ pub struct ConfigOptsBundle {
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
+6
View File
@@ -28,6 +28,12 @@ impl Clean {
remove_dir_all(crate_config.crate_dir.join(&out_dir))?;
}
let fullstack_out_dir = crate_config.crate_dir.join(".dioxus");
if fullstack_out_dir.is_dir() {
remove_dir_all(fullstack_out_dir)?;
}
Ok(())
}
}
+21 -6
View File
@@ -12,6 +12,7 @@ pub struct Serve {
impl Serve {
pub async fn serve(self, bin: Option<PathBuf>) -> Result<()> {
let mut crate_config = crate::CrateConfig::new(bin)?;
let serve_cfg = self.serve.clone();
// change the relase state.
crate_config.with_hot_reload(self.serve.hot_reload);
@@ -34,6 +35,12 @@ impl Serve {
// Subdirectories don't work with the server
crate_config.dioxus_config.web.app.base_path = None;
if let Some(target) = self.serve.target {
crate_config.set_target(target);
}
crate_config.set_cargo_args(self.serve.cargo_args);
let platform = self
.serve
.platform
@@ -42,21 +49,29 @@ impl Serve {
match platform {
cfg::Platform::Web => {
// generate dev-index page
Serve::regen_dev_page(&crate_config)?;
Serve::regen_dev_page(&crate_config, self.serve.skip_assets)?;
// start the develop server
server::web::startup(self.serve.port, crate_config.clone(), self.serve.open)
.await?;
server::web::startup(
self.serve.port,
crate_config.clone(),
self.serve.open,
self.serve.skip_assets,
)
.await?;
}
cfg::Platform::Desktop => {
server::desktop::startup(crate_config.clone()).await?;
server::desktop::startup(crate_config.clone(), &serve_cfg).await?;
}
cfg::Platform::Fullstack => {
server::fullstack::startup(crate_config.clone(), &serve_cfg).await?;
}
}
Ok(())
}
pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> {
let serve_html = gen_page(&crate_config.dioxus_config, true);
pub fn regen_dev_page(crate_config: &CrateConfig, skip_assets: bool) -> Result<()> {
let serve_html = gen_page(crate_config, true, skip_assets);
let dist_path = crate_config.crate_dir.join(
crate_config
+27 -1
View File
@@ -1,4 +1,6 @@
use crate::{cfg::Platform, error::Result};
use manganis_cli_support::AssetManifest;
use manganis_cli_support::AssetManifestExt;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
@@ -105,7 +107,7 @@ impl Default for DioxusConfig {
},
proxy: Some(vec![]),
watcher: WebWatcherConfig {
watch_path: Some(vec![PathBuf::from("src")]),
watch_path: Some(vec![PathBuf::from("src"), PathBuf::from("examples")]),
reload_html: Some(false),
index_on_404: Some(true),
},
@@ -211,6 +213,8 @@ pub struct CrateConfig {
pub verbose: bool,
pub custom_profile: Option<String>,
pub features: Option<Vec<String>>,
pub target: Option<String>,
pub cargo_args: Vec<String>,
}
#[derive(Debug, Clone)]
@@ -278,6 +282,8 @@ impl CrateConfig {
let verbose = false;
let custom_profile = None;
let features = None;
let target = None;
let cargo_args = vec![];
Ok(Self {
out_dir,
@@ -294,9 +300,18 @@ impl CrateConfig {
custom_profile,
features,
verbose,
target,
cargo_args,
})
}
pub fn asset_manifest(&self) -> AssetManifest {
AssetManifest::load_from_path(
self.crate_dir.join("Cargo.toml"),
self.workspace_dir.join("Cargo.lock"),
)
}
pub fn as_example(&mut self, example_name: String) -> &mut Self {
self.executable = ExecutableType::Example(example_name);
self
@@ -331,6 +346,16 @@ impl CrateConfig {
self.features = Some(features);
self
}
pub fn set_target(&mut self, target: String) -> &mut Self {
self.target = Some(target);
self
}
pub fn set_cargo_args(&mut self, cargo_args: Vec<String>) -> &mut Self {
self.cargo_args = cargo_args;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -525,6 +550,7 @@ impl From<NsisSettings> for tauri_bundler::NsisSettings {
display_language_selector: val.display_language_selector,
custom_language_files: None,
template: None,
compression: None,
}
}
}
+3
View File
@@ -29,6 +29,9 @@ pub enum Error {
#[error("Cargo Error: {0}")]
CargoError(String),
#[error("Couldn't retrieve cargo metadata")]
CargoMetadata(#[source] cargo_metadata::Error),
#[error("{0}")]
CustomError(String),
+4
View File
@@ -1,3 +1,7 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
pub const DIOXUS_CLI_VERSION: &str = "0.4.1";
pub mod builder;
+13 -1
View File
@@ -28,7 +28,19 @@ pub fn set_up_logging() {
message = message,
));
})
.level(log::LevelFilter::Info)
.level(match std::env::var("DIOXUS_LOG") {
Ok(level) => match level.to_lowercase().as_str() {
"error" => log::LevelFilter::Error,
"warn" => log::LevelFilter::Warn,
"info" => log::LevelFilter::Info,
"debug" => log::LevelFilter::Debug,
"trace" => log::LevelFilter::Trace,
_ => {
panic!("Invalid log level: {}", level)
}
},
Err(_) => log::LevelFilter::Info,
})
.chain(std::io::stdout())
.apply()
.unwrap();
+39 -47
View File
@@ -9,42 +9,31 @@ 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.";
fn get_bin(bin: Option<String>) -> Result<PathBuf> {
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.map_err(Error::CargoMetadata)?;
let package = if let Some(bin) = bin {
metadata
.workspace_packages()
.into_iter()
.find(|p| p.name == bin)
.ok_or(format!("no such package: {}", bin))
.map_err(Error::CargoError)?
} else {
metadata
.root_package()
.ok_or("no root package?".into())
.map_err(Error::CargoError)?
};
if let Some(ref bin) = bin {
let manifest = cargo_toml::Manifest::from_path("./Cargo.toml")
.map_err(|_| Error::CargoError(ERR_MESSAGE.to_string()))?;
let crate_dir = package
.manifest_path
.parent()
.ok_or("couldn't take parent dir".into())
.map_err(Error::CargoError)?;
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)
Ok(crate_dir.into())
}
#[tokio::main]
@@ -53,34 +42,36 @@ async fn main() -> anyhow::Result<()> {
set_up_logging();
let bin = get_bin(args.bin)?;
let bin = get_bin(args.bin);
let _dioxus_config = DioxusConfig::load(bin.clone())
if let Ok(bin) = &bin {
let _dioxus_config = DioxusConfig::load(Some(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()
});
#[cfg(feature = "plugin")]
PluginManager::init(_dioxus_config.plugin)
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
#[cfg(feature = "plugin")]
PluginManager::init(_dioxus_config.plugin)
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
}
match args.action {
Translate(opts) => opts
.translate()
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
Build(opts) => opts
.build(bin.clone())
Build(opts) if bin.is_ok() => opts
.build(Some(bin.unwrap().clone()), None)
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
Clean(opts) => opts
.clean(bin.clone())
Clean(opts) if bin.is_ok() => opts
.clean(Some(bin.unwrap().clone()))
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
Serve(opts) => opts
.serve(bin.clone())
Serve(opts) if bin.is_ok() => opts
.serve(Some(bin.unwrap().clone()))
.await
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
@@ -92,8 +83,8 @@ async fn main() -> anyhow::Result<()> {
.config()
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
Bundle(opts) => opts
.bundle(bin.clone())
Bundle(opts) if bin.is_ok() => opts
.bundle(Some(bin.unwrap().clone()))
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
#[cfg(feature = "plugin")]
@@ -118,5 +109,6 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
_ => Err(anyhow::anyhow!(bin.unwrap_err())),
}
}
+115 -59
View File
@@ -1,11 +1,12 @@
use crate::server::Platform;
use crate::{
cfg::ConfigOptsServe,
server::{
output::{print_console_info, PrettierOptions},
setup_file_watcher,
},
BuildResult, CrateConfig, Result,
};
use dioxus_hot_reload::HotReloadMsg;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::*;
@@ -21,7 +22,14 @@ use plugin::PluginManager;
use super::HotReloadState;
pub async fn startup(config: CrateConfig) -> Result<()> {
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
startup_with_platform::<DesktopPlatform>(config, serve).await
}
pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
config: CrateConfig,
serve_cfg: &ConfigOptsServe,
) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
let _ = ctrlc::set_handler(move || {
@@ -43,8 +51,6 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
let hot_reload_tx = broadcast::channel(100).0;
clear_paths();
Some(HotReloadState {
messages: hot_reload_tx.clone(),
file_map: file_map.clone(),
@@ -53,15 +59,18 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
false => None,
};
serve(config, hot_reload_state).await?;
serve::<P>(config, serve_cfg, hot_reload_state).await?;
Ok(())
}
/// Start the server without hot reload
pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>) -> Result<()> {
let (child, first_build_result) = start_desktop(&config)?;
let currently_running_child: RwLock<Child> = RwLock::new(child);
async fn serve<P: Platform + Send + 'static>(
config: CrateConfig,
serve: &ConfigOptsServe,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let platform = RwLock::new(P::start(&config, serve)?);
log::info!("🚀 Starting development server...");
@@ -70,14 +79,7 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
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)
}
move || platform.write().unwrap().rebuild(&config)
},
&config,
None,
@@ -85,19 +87,9 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
)
.await?;
// Print serve info
print_console_info(
&config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
None,
);
match hot_reload_state {
Some(hot_reload_state) => {
// The open interprocess sockets
start_desktop_hot_reload(hot_reload_state).await?;
}
None => {
@@ -109,7 +101,14 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
}
async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
match LocalSocketListener::bind("@dioxusin") {
let metadata = cargo_metadata::MetadataCommand::new()
.no_deps()
.exec()
.unwrap();
let target_dir = metadata.target_directory.as_std_path();
let path = target_dir.join("dioxusin");
clear_paths(&path);
match LocalSocketListener::bind(path) {
Ok(local_socket_stream) => {
let aborted = Arc::new(Mutex::new(false));
// States
@@ -121,30 +120,41 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
let file_map = hot_reload_state.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;
//accept() will block the thread when local_socket_stream is in blocking mode (default)
match local_socket_stream.accept() {
Ok(mut connection) => {
// 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 🚀");
}
Err(err) => {
let error_string = err.to_string();
// Filter out any error messages about a operation that may block and an error message that triggers on some operating systems that says "Waiting for a process to open the other end of the pipe" without WouldBlock being set
let display_error = err.kind() != std::io::ErrorKind::WouldBlock
&& !error_string.contains("Waiting for a process");
if display_error {
println!("Error connecting to hot reloading: {} (Hot reloading is a feature of the dioxus-cli. If you are not using the CLI, this error can be ignored)", err);
}
}
channels.lock().unwrap().push(connection);
println!("Connected to hot reloading 🚀");
}
if *aborted.lock().unwrap() {
break;
@@ -174,17 +184,14 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
Ok(())
}
fn clear_paths() {
if cfg!(target_os = "macos") {
fn clear_paths(file_socket_path: &std::path::Path) {
if cfg!(unix) {
// 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);
}
if file_socket_path.exists() {
let _ = std::fs::remove_file(file_socket_path);
}
}
}
@@ -203,9 +210,9 @@ fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
}
}
pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
fn start_desktop(config: &CrateConfig, skip_assets: bool) -> Result<(RAIIChild, BuildResult)> {
// Run the desktop application
let result = crate::builder::build_desktop(config, true)?;
let result = crate::builder::build_desktop(config, true, skip_assets)?;
match &config.executable {
crate::ExecutableType::Binary(name)
@@ -215,9 +222,58 @@ pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
if cfg!(windows) {
file.set_extension("exe");
}
let child = Command::new(file.to_str().unwrap()).spawn()?;
let active = "DIOXUS_ACTIVE";
let child = RAIIChild(
Command::new(file.to_str().unwrap())
.env(active, "true")
.spawn()?,
);
Ok((child, result))
}
}
}
pub(crate) struct DesktopPlatform {
currently_running_child: RAIIChild,
skip_assets: bool,
}
impl Platform for DesktopPlatform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self> {
let (child, first_build_result) = start_desktop(config, serve.skip_assets)?;
log::info!("🚀 Starting development server...");
// Print serve info
print_console_info(
config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
None,
);
Ok(Self {
currently_running_child: child,
skip_assets: serve.skip_assets,
})
}
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult> {
self.currently_running_child.0.kill()?;
let (child, result) = start_desktop(config, self.skip_assets)?;
self.currently_running_child = child;
Ok(result)
}
}
struct RAIIChild(Child);
impl Drop for RAIIChild {
fn drop(&mut self) {
let _ = self.0.kill();
}
}
+161
View File
@@ -0,0 +1,161 @@
use crate::{
cfg::{ConfigOptsBuild, ConfigOptsServe},
CrateConfig, Result, WebAssetConfigDropGuard,
};
use super::{desktop, Platform};
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
desktop::startup_with_platform::<FullstackPlatform>(config, serve).await
}
fn start_web_build_thread(
config: &CrateConfig,
serve: &ConfigOptsServe,
) -> std::thread::JoinHandle<Result<()>> {
let serve = serve.clone();
let target_directory = config.crate_dir.join(".dioxus").join("web");
std::fs::create_dir_all(&target_directory).unwrap();
std::thread::spawn(move || build_web(serve, &target_directory))
}
struct FullstackPlatform {
serve: ConfigOptsServe,
desktop: desktop::DesktopPlatform,
_config: WebAssetConfigDropGuard,
}
impl Platform for FullstackPlatform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
where
Self: Sized,
{
let thread_handle = start_web_build_thread(config, serve);
let mut desktop_config = config.clone();
let desktop_feature = serve.server_feature.clone();
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let config = WebAssetConfigDropGuard::new();
let desktop = desktop::DesktopPlatform::start(&desktop_config, serve)?;
thread_handle
.join()
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
Ok(Self {
desktop,
serve: serve.clone(),
_config: config,
})
}
fn rebuild(&mut self, crate_config: &CrateConfig) -> Result<crate::BuildResult> {
let thread_handle = start_web_build_thread(crate_config, &self.serve);
let result = {
let mut desktop_config = crate_config.clone();
let desktop_feature = self.serve.server_feature.clone();
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let _gaurd = FullstackServerEnvGuard::new(self.serve.force_debug, self.serve.release);
self.desktop.rebuild(&desktop_config)
};
thread_handle
.join()
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
result
}
}
fn build_web(serve: ConfigOptsServe, target_directory: &std::path::Path) -> Result<()> {
let mut web_config: ConfigOptsBuild = serve.into();
let web_feature = web_config.client_feature.clone();
let features = &mut web_config.features;
match features {
Some(features) => {
features.push(web_feature);
}
None => web_config.features = Some(vec![web_feature]),
};
web_config.platform = Some(crate::cfg::Platform::Web);
let _gaurd = FullstackWebEnvGuard::new(&web_config);
crate::cli::build::Build { build: web_config }.build(None, Some(target_directory))
}
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
// This reduces a hello world from ~40MB to ~2MB
pub(crate) struct FullstackWebEnvGuard {
old_rustflags: Option<String>,
}
impl FullstackWebEnvGuard {
pub fn new(serve: &ConfigOptsBuild) -> Self {
Self {
old_rustflags: (!serve.force_debug).then(|| {
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let debug_assertions = if serve.release {
""
} else {
" -C debug-assertions"
};
std::env::set_var(
"RUSTFLAGS",
format!(
"{old_rustflags} -C debuginfo=none -C strip=debuginfo{debug_assertions}"
),
);
old_rustflags
}),
}
}
}
impl Drop for FullstackWebEnvGuard {
fn drop(&mut self) {
if let Some(old_rustflags) = self.old_rustflags.take() {
std::env::set_var("RUSTFLAGS", old_rustflags);
}
}
}
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
// This reduces a hello world from ~40MB to ~2MB
pub(crate) struct FullstackServerEnvGuard {
old_rustflags: Option<String>,
}
impl FullstackServerEnvGuard {
pub fn new(debug: bool, release: bool) -> Self {
Self {
old_rustflags: (!debug).then(|| {
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let debug_assertions = if release { "" } else { " -C debug-assertions" };
std::env::set_var(
"RUSTFLAGS",
format!("{old_rustflags} -C opt-level=2 {debug_assertions}"),
);
old_rustflags
}),
}
}
}
impl Drop for FullstackServerEnvGuard {
fn drop(&mut self) {
if let Some(old_rustflags) = self.old_rustflags.take() {
std::env::set_var("RUSTFLAGS", old_rustflags);
}
}
}
+26 -8
View File
@@ -1,4 +1,4 @@
use crate::{BuildResult, CrateConfig, Result};
use crate::{cfg::ConfigOptsServe, BuildResult, CrateConfig, Result};
use cargo_metadata::diagnostic::Diagnostic;
use dioxus_core::Template;
@@ -14,6 +14,7 @@ use tokio::sync::broadcast::{self};
mod output;
use output::*;
pub mod desktop;
pub mod fullstack;
pub mod web;
/// Sets up a file watcher
@@ -32,7 +33,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
.watcher
.watch_path
.clone()
.unwrap_or_else(|| vec![PathBuf::from("src")]);
.unwrap_or_else(|| vec![PathBuf::from("src"), PathBuf::from("examples")]);
let watcher_config = config.clone();
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
@@ -55,6 +56,16 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
break;
}
// Workaround for notify and vscode-like editor:
// when edit & save a file in vscode, there will be two notifications,
// the first one is a file with empty content.
// filter the empty file notification to avoid false rebuild during hot-reload
if let Ok(metadata) = fs::metadata(path) {
if metadata.len() == 0 {
continue;
}
}
match rsx_file_map.update_rsx(path, &config.crate_dir) {
Ok(UpdateResult::UpdatedRsx(msgs)) => {
messages.extend(msgs);
@@ -121,16 +132,23 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
.unwrap();
for sub_path in allow_watch_path {
watcher
.watch(
&config.crate_dir.join(sub_path),
notify::RecursiveMode::Recursive,
)
.unwrap();
if let Err(err) = watcher.watch(
&config.crate_dir.join(sub_path),
notify::RecursiveMode::Recursive,
) {
log::error!("Failed to watch path: {}", err);
}
}
Ok(watcher)
}
pub(crate) trait Platform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
where
Self: Sized;
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult>;
}
#[derive(Clone)]
pub struct HotReloadState {
pub messages: broadcast::Sender<Template<'static>>,
+15 -12
View File
@@ -22,17 +22,20 @@ pub fn print_console_info(
options: PrettierOptions,
web_info: Option<WebServerInfo>,
) {
if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") {
"cls"
} else {
"clear"
})
.output()
{
print!("{}", String::from_utf8_lossy(&native_clearseq.stdout));
} else {
// Try ANSI-Escape characters
print!("\x1b[2J\x1b[H");
// Don't clear the screen if the user has set the DIOXUS_LOG environment variable to "trace" so that we can see the logs
if Some("trace") != std::env::var("DIOXUS_LOG").ok().as_deref() {
if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") {
"cls"
} else {
"clear"
})
.output()
{
print!("{}", String::from_utf8_lossy(&native_clearseq.stdout));
} else {
// Try ANSI-Escape characters
print!("\x1b[2J\x1b[H");
}
}
let mut profile = if config.release { "Release" } else { "Debug" }.to_string();
@@ -129,7 +132,7 @@ pub fn print_console_info(
log::warn!(
"{}",
format!(
"There were {} warning messages during the build.",
"There were {} warning messages during the build. Run `cargo check` to see them.",
options.warnings.len() - 1
)
.yellow()
+30 -8
View File
@@ -11,6 +11,7 @@ use axum::{
body::{Full, HttpBody},
extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade},
http::{
self,
header::{HeaderName, HeaderValue},
Method, Response, StatusCode,
},
@@ -47,7 +48,12 @@ struct WsReloadState {
update: broadcast::Sender<()>,
}
pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Result<()> {
pub async fn startup(
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
let _ = ctrlc::set_handler(move || {
@@ -79,7 +85,15 @@ pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Res
false => None,
};
serve(ip, port, config, start_browser, hot_reload_state).await?;
serve(
ip,
port,
config,
start_browser,
skip_assets,
hot_reload_state,
)
.await?;
Ok(())
}
@@ -90,9 +104,10 @@ pub async fn serve(
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, true)?;
let first_build_result = crate::builder::build(&config, false, skip_assets)?;
log::info!("🚀 Starting development server...");
@@ -105,7 +120,7 @@ pub async fn serve(
{
let config = config.clone();
let reload_tx = reload_tx.clone();
move || build(&config, &reload_tx)
move || build(&config, &reload_tx, skip_assets)
},
&config,
Some(WebServerInfo {
@@ -262,7 +277,7 @@ async fn setup_router(
.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
let mut response = if file_service_config
.dioxus_config
.web
.watcher
@@ -290,6 +305,13 @@ async fn setup_router(
} else {
response.map(|body| body.boxed())
};
let headers = response.headers_mut();
headers.insert(
http::header::CACHE_CONTROL,
HeaderValue::from_static("no-cache"),
);
headers.insert(http::header::PRAGMA, HeaderValue::from_static("no-cache"));
headers.insert(http::header::EXPIRES, HeaderValue::from_static("0"));
Ok(response)
},
)
@@ -412,8 +434,8 @@ async fn ws_handler(
})
}
fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
let result = builder::build(config, true)?;
fn build(config: &CrateConfig, reload_tx: &Sender<()>, skip_assets: bool) -> Result<BuildResult> {
let result = builder::build(config, true, skip_assets)?;
// change the websocket reload state to true;
// the page will auto-reload.
if config
@@ -423,7 +445,7 @@ fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
.reload_html
.unwrap_or(false)
{
let _ = Serve::regen_dev_page(config);
let _ = Serve::regen_dev_page(config, skip_assets);
}
let _ = reload_tx.send(());
Ok(result)
+3 -1
View File
@@ -15,10 +15,12 @@ proc-macro = true
[dependencies]
proc-macro2 = { version = "1.0" }
quote = "1.0"
syn = { version = "2.0", features = ["full", "extra-traits"] }
syn = { version = "2.0", features = ["full", "extra-traits", "visit"] }
dioxus-rsx = { workspace = true }
dioxus-core = { workspace = true }
constcat = "0.3.0"
convert_case = "^0.6.0"
prettyplease = "0.2.15"
# testing
[dev-dependencies]
+6 -3
View File
@@ -23,9 +23,12 @@
`dioxus-core-macro` provides a handful of helpful macros used by the `dioxus` crate. These include:
- The `rsx!` macro that underpins templates and node creation
- The `inline_props` macro transforms function arguments into an auto-derived struct
- The `format_args_f` macro which allows f-string formatting with support for expressions
- The `rsx!` macro that underpins templates and node creation.
- The `component` attribute macro denotes a function as a Dioxus component. Currently, this:
- Transforms function arguments into an auto-derived struct.
- Ensures that your component name uses PascalCase.
- Probably more stuff in the future. This macro allows us to have a way of distinguishing functions and components, which can be quite handy.
- The `format_args_f` macro which allows f-string formatting with support for expressions.
## Contributing
@@ -31,6 +31,7 @@ fn get_out_comp_fn(orig_comp_fn: &ItemFn, cx_pat: &Pat) -> ItemFn {
block: parse_quote! {
{
#[warn(non_snake_case)]
#[allow(clippy::inline_always)]
#[inline(always)]
#inner_comp_fn
#inner_comp_ident (#cx_pat)
@@ -57,8 +58,11 @@ impl ToTokens for ComponentDeserializerOutput {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let comp_fn = &self.comp_fn;
let props_struct = &self.props_struct;
let fn_ident = &comp_fn.sig.ident;
let doc = format!("Properties for the [`{fn_ident}`] component.");
tokens.append_all(quote! {
#[doc = #doc]
#props_struct
#[allow(non_snake_case)]
#comp_fn
@@ -30,166 +30,312 @@ impl ToTokens for InlinePropsDeserializerOutput {
impl DeserializerArgs<InlinePropsDeserializerOutput> for InlinePropsDeserializerArgs {
fn to_output(&self, component_body: &ComponentBody) -> Result<InlinePropsDeserializerOutput> {
Ok(InlinePropsDeserializerOutput {
comp_fn: Self::get_function(component_body),
props_struct: Self::get_props_struct(component_body),
comp_fn: get_function(component_body),
props_struct: get_props_struct(component_body),
})
}
}
impl InlinePropsDeserializerArgs {
fn get_props_struct(component_body: &ComponentBody) -> ItemStruct {
let ComponentBody { item_fn, .. } = component_body;
let ItemFn { vis, sig, .. } = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
..
} = sig;
fn get_props_struct(component_body: &ComponentBody) -> ItemStruct {
let ComponentBody { item_fn, .. } = component_body;
let ItemFn { vis, sig, .. } = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
..
} = sig;
// Skip first arg since that's the context
let struct_fields = inputs.iter().skip(1).map(move |f| {
match f {
FnArg::Receiver(_) => unreachable!(), // Unreachable because of ComponentBody parsing
FnArg::Typed(pt) => {
let arg_pat = &pt.pat; // Pattern (identifier)
let arg_colon = &pt.colon_token;
let arg_ty = &pt.ty; // Type
let arg_attrs = &pt.attrs; // Attributes
// Skip first arg since that's the context
let struct_fields = inputs.iter().skip(1).map(move |f| {
match f {
FnArg::Receiver(_) => unreachable!(), // Unreachable because of ComponentBody parsing
FnArg::Typed(pt) => {
let arg_pat = &pt.pat; // Pattern (identifier)
let arg_colon = &pt.colon_token;
let arg_ty = &pt.ty; // Type
let arg_attrs = &pt.attrs; // Attributes
quote! {
#(#arg_attrs)
*
#vis #arg_pat #arg_colon #arg_ty
}
quote! {
#(#arg_attrs)
*
#vis #arg_pat #arg_colon #arg_ty
}
}
});
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let struct_attrs = if first_lifetime.is_some() {
quote! { #[derive(Props)] }
} else {
quote! { #[derive(Props, PartialEq)] }
};
let struct_generics = if first_lifetime.is_some() {
let struct_generics: Punctuated<GenericParam, Comma> = component_body
.item_fn
.sig
.generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.push(parse_quote!( 'a ));
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
quote! { <#struct_generics> }
} else {
quote! { #generics }
};
parse_quote! {
#struct_attrs
#[allow(non_camel_case_types)]
#vis struct #struct_ident #struct_generics
{
#(#struct_fields),*
}
}
}
});
fn get_function(component_body: &ComponentBody) -> ItemFn {
let ComponentBody {
item_fn,
cx_pat_type,
..
} = component_body;
let ItemFn {
attrs: fn_attrs,
vis,
sig,
block: fn_block,
} = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
output: fn_output,
asyncness,
..
} = sig;
let Generics { where_clause, .. } = generics;
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
let cx_pat = &cx_pat_type.pat;
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
// Skip first arg since that's the context
let struct_field_names = inputs.iter().skip(1).filter_map(|f| match f {
FnArg::Receiver(_) => unreachable!(), // ComponentBody prohibits receiver parameters.
FnArg::Typed(t) => Some(&t.pat),
});
let struct_attrs = if first_lifetime.is_some() {
quote! { #[derive(Props)] }
} else {
quote! { #[derive(Props, PartialEq)] }
};
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let struct_generics = if first_lifetime.is_some() {
let struct_generics: Punctuated<GenericParam, Comma> = component_body
.item_fn
.sig
.generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.push(parse_quote!( 'a ));
let (scope_lifetime, fn_generics) = if let Some(lt) = first_lifetime {
(quote! { #lt, }, generics.clone())
} else {
let lifetime: LifetimeParam = parse_quote! { 'a };
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
let mut fn_generics = generics.clone();
fn_generics
.params
.insert(0, GenericParam::Lifetime(lifetime.clone()));
quote! { <#struct_generics> }
} else {
quote! { #generics }
};
(quote! { #lifetime, }, fn_generics)
};
let generics_no_bounds = {
let mut generics = generics.clone();
generics.params = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.clear();
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
generics
};
parse_quote! {
#(#fn_attrs)*
#asyncness #vis fn #fn_ident #fn_generics (#cx_pat: Scope<#scope_lifetime #struct_ident #generics_no_bounds>) #fn_output
#where_clause
{
let #struct_ident { #(#struct_field_names),* } = &#cx_pat.props;
#fn_block
}
parse_quote! {
#struct_attrs
#[allow(non_camel_case_types)]
#vis struct #struct_ident #struct_generics
{
#(#struct_fields),*
}
}
}
fn get_props_docs(fn_ident: &Ident, inputs: Vec<&FnArg>) -> Vec<Attribute> {
if inputs.len() <= 1 {
return Vec::new();
}
let arg_docs = inputs
.iter()
.filter_map(|f| match f {
FnArg::Receiver(_) => unreachable!(), // ComponentBody prohibits receiver parameters.
FnArg::Typed(pt) => {
let arg_doc = pt
.attrs
.iter()
.filter_map(|attr| {
// TODO: Error reporting
// Check if the path of the attribute is "doc"
if !is_attr_doc(attr) {
return None;
};
let Meta::NameValue(meta_name_value) = &attr.meta else {
return None;
};
let Expr::Lit(doc_lit) = &meta_name_value.value else {
return None;
};
let Lit::Str(doc_lit_str) = &doc_lit.lit else {
return None;
};
Some(doc_lit_str.value())
})
.fold(String::new(), |mut doc, next_doc_line| {
doc.push('\n');
doc.push_str(&next_doc_line);
doc
});
Some((
&pt.pat,
&pt.ty,
pt.attrs.iter().find_map(|attr| {
if attr.path() != &parse_quote!(deprecated) {
return None;
}
let res = crate::utils::DeprecatedAttribute::from_meta(&attr.meta);
match res {
Err(e) => panic!("{}", e.to_string()),
Ok(v) => Some(v),
}
}),
arg_doc,
))
}
})
.collect::<Vec<_>>();
let mut props_docs = Vec::with_capacity(5);
let props_def_link = fn_ident.to_string() + "Props";
let header =
format!("# Props\n*For details, see the [props struct definition]({props_def_link}).*");
props_docs.push(parse_quote! {
#[doc = #header]
});
for (arg_name, arg_type, deprecation, input_arg_doc) in arg_docs {
let arg_name = arg_name.into_token_stream().to_string();
let arg_type = crate::utils::format_type_string(arg_type);
let input_arg_doc = keep_up_to_n_consecutive_chars(input_arg_doc.trim(), 2, '\n')
.replace("\n\n", "</p><p>");
let prop_def_link = format!("{props_def_link}::{arg_name}");
let mut arg_doc = format!("- [`{arg_name}`]({prop_def_link}) : `{arg_type}`");
if let Some(deprecation) = deprecation {
arg_doc.push_str("<p>👎 Deprecated");
if let Some(since) = deprecation.since {
arg_doc.push_str(&format!(" since {since}"));
}
if let Some(note) = deprecation.note {
let note = keep_up_to_n_consecutive_chars(&note, 1, '\n').replace('\n', " ");
let note = keep_up_to_n_consecutive_chars(&note, 1, '\t').replace('\t', " ");
arg_doc.push_str(&format!(": {note}"));
}
arg_doc.push_str("</p>");
if !input_arg_doc.is_empty() {
arg_doc.push_str("<hr/>");
}
}
if !input_arg_doc.is_empty() {
arg_doc.push_str(&format!("<p>{input_arg_doc}</p>"));
}
props_docs.push(parse_quote! {
#[doc = #arg_doc]
});
}
props_docs
}
fn get_function(component_body: &ComponentBody) -> ItemFn {
let ComponentBody {
item_fn,
cx_pat_type,
..
} = component_body;
let ItemFn {
attrs: fn_attrs,
vis,
sig,
block: fn_block,
} = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
output: fn_output,
asyncness,
..
} = sig;
let Generics { where_clause, .. } = generics;
let cx_pat = &cx_pat_type.pat;
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
// Skip first arg since that's the context
let struct_field_names = inputs.iter().skip(1).filter_map(|f| match f {
FnArg::Receiver(_) => unreachable!(), // ComponentBody prohibits receiver parameters.
FnArg::Typed(pt) => Some(&pt.pat),
});
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let (scope_lifetime, fn_generics) = if let Some(lt) = first_lifetime {
(quote! { #lt, }, generics.clone())
} else {
let lifetime: LifetimeParam = parse_quote! { 'a };
let mut fn_generics = generics.clone();
fn_generics
.params
.insert(0, GenericParam::Lifetime(lifetime.clone()));
(quote! { #lifetime, }, fn_generics)
};
let generics_no_bounds = {
let mut generics = generics.clone();
generics.params = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.clear();
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
generics
};
let props_docs = get_props_docs(fn_ident, inputs.iter().skip(1).collect());
parse_quote! {
#(#fn_attrs)*
#(#props_docs)*
#asyncness #vis fn #fn_ident #fn_generics (#cx_pat: Scope<#scope_lifetime #struct_ident #generics_no_bounds>) #fn_output
#where_clause
{
let #struct_ident { #(#struct_field_names),* } = &#cx_pat.props;
#fn_block
}
}
}
/// Checks if the attribute is a `#[doc]` attribute.
fn is_attr_doc(attr: &Attribute) -> bool {
attr.path() == &parse_quote!(doc)
}
fn keep_up_to_n_consecutive_chars(
input: &str,
n_of_consecutive_chars_allowed: usize,
target_char: char,
) -> String {
let mut output = String::new();
let mut prev_char: Option<char> = None;
let mut consecutive_count = 0;
for c in input.chars() {
match prev_char {
Some(prev) if c == target_char && prev == target_char => {
if consecutive_count < n_of_consecutive_chars_allowed {
output.push(c);
consecutive_count += 1;
}
}
_ => {
output.push(c);
prev_char = Some(c);
consecutive_count = 1;
}
}
}
output
}
+5
View File
@@ -1,3 +1,7 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
use proc_macro::TokenStream;
use quote::ToTokens;
use rsx::RenderCallBody;
@@ -8,6 +12,7 @@ use syn::{parse_macro_input, Path, Token};
mod component_body;
mod component_body_deserializers;
mod props;
mod utils;
// mod rsx;
use crate::component_body::ComponentBody;
+293 -56
View File
@@ -24,6 +24,10 @@ pub fn impl_my_derive(ast: &syn::DeriveInput) -> Result<TokenStream, Error> {
.included_fields()
.map(|f| struct_info.field_impl(f))
.collect::<Result<Vec<_>, _>>()?;
let extends = struct_info
.extend_fields()
.map(|f| struct_info.extends_impl(f))
.collect::<Result<Vec<_>, _>>()?;
let fields = quote!(#(#fields)*).into_iter();
let required_fields = struct_info
.included_fields()
@@ -36,6 +40,7 @@ pub fn impl_my_derive(ast: &syn::DeriveInput) -> Result<TokenStream, Error> {
#builder_creation
#conversion_helper
#( #fields )*
#( #extends )*
#( #required_fields )*
#build_method
}
@@ -167,8 +172,8 @@ mod field_info {
use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use syn::Expr;
use syn::{parse::Error, punctuated::Punctuated};
use syn::{Expr, Path};
use super::util::{
expr_to_single_string, ident_to_type, path_to_single_string, strip_raw_ident_prefix,
@@ -199,6 +204,13 @@ mod field_info {
);
}
// extended field is automatically empty
if !builder_attr.extends.is_empty() {
builder_attr.default = Some(
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
);
}
// auto detect optional
let strip_option_auto = builder_attr.strip_option
|| !builder_attr.ignore_option
@@ -243,10 +255,6 @@ mod field_info {
}
.into()
}
pub fn type_from_inside_option(&self, check_option_name: bool) -> Option<&syn::Type> {
type_from_inside_option(self.ty, check_option_name)
}
}
#[derive(Debug, Default, Clone)]
@@ -257,6 +265,7 @@ mod field_info {
pub auto_into: bool,
pub strip_option: bool,
pub ignore_option: bool,
pub extends: Vec<Path>,
}
impl FieldBuilderAttr {
@@ -309,6 +318,17 @@ mod field_info {
let name = expr_to_single_string(&assign.left)
.ok_or_else(|| Error::new_spanned(&assign.left, "Expected identifier"))?;
match name.as_str() {
"extends" => {
if let syn::Expr::Path(path) = *assign.right {
self.extends.push(path.path);
Ok(())
} else {
Err(Error::new_spanned(
assign.right,
"Expected simple identifier",
))
}
}
"default" => {
self.default = Some(*assign.right);
Ok(())
@@ -363,6 +383,11 @@ mod field_info {
Ok(())
}
"extend" => {
self.extends.push(path.path);
Ok(())
}
_ => {
macro_rules! handle_fields {
( $( $flag:expr, $field:ident, $already:expr; )* ) => {
@@ -466,11 +491,14 @@ fn type_from_inside_option(ty: &syn::Type, check_option_name: bool) -> Option<&s
}
mod struct_info {
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::Error;
use syn::punctuated::Punctuated;
use syn::Expr;
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::{parse_quote, Expr, Ident};
use super::field_info::{FieldBuilderAttr, FieldInfo};
use super::util::{
@@ -493,7 +521,46 @@ mod struct_info {
impl<'a> StructInfo<'a> {
pub fn included_fields(&self) -> impl Iterator<Item = &FieldInfo<'a>> {
self.fields.iter().filter(|f| !f.builder_attr.skip)
self.fields
.iter()
.filter(|f| !f.builder_attr.skip && f.builder_attr.extends.is_empty())
}
pub fn extend_fields(&self) -> impl Iterator<Item = &FieldInfo<'a>> {
self.fields
.iter()
.filter(|f| !f.builder_attr.extends.is_empty())
}
fn extend_lifetime(&self) -> syn::Result<Option<syn::Lifetime>> {
let first_extend = self.extend_fields().next();
match first_extend {
Some(f) => {
struct VisitFirstLifetime(Option<syn::Lifetime>);
impl Visit<'_> for VisitFirstLifetime {
fn visit_lifetime(&mut self, lifetime: &'_ syn::Lifetime) {
if self.0.is_none() {
self.0 = Some(lifetime.clone());
}
}
}
let name = f.name;
let mut visitor = VisitFirstLifetime(None);
visitor.visit_type(f.ty);
visitor.0.ok_or_else(|| {
syn::Error::new_spanned(
name,
"Unable to find lifetime for extended field. Please specify it manually",
)
}).map(Some)
}
None => Ok(None),
}
}
pub fn new(
@@ -540,7 +607,17 @@ mod struct_info {
// Therefore, we will generate code that shortcircuits the "comparison" in memoization
let are_there_generics = !self.generics.params.is_empty();
let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
let extend_lifetime = self.extend_lifetime()?;
let generics = self.generics.clone();
let (_, ty_generics, where_clause) = generics.split_for_impl();
let impl_generics = self.modify_generics(|g| {
if extend_lifetime.is_none() {
g.params.insert(0, parse_quote!('__bump));
}
});
let (impl_generics, _, _) = impl_generics.split_for_impl();
let (_, b_initial_generics, _) = self.generics.split_for_impl();
let all_fields_param = syn::GenericParam::Type(
syn::Ident::new("TypedBuilderFields", proc_macro2::Span::call_site()).into(),
);
@@ -548,21 +625,19 @@ mod struct_info {
g.params.insert(0, all_fields_param.clone());
});
let empties_tuple = type_tuple(self.included_fields().map(|_| empty_type()));
let generics_with_empty = modify_types_generics_hack(&ty_generics, |args| {
let generics_with_empty = modify_types_generics_hack(&b_initial_generics, |args| {
args.insert(0, syn::GenericArgument::Type(empties_tuple.clone().into()));
});
let phantom_generics = self.generics.params.iter().map(|param| match param {
let phantom_generics = self.generics.params.iter().filter_map(|param| match param {
syn::GenericParam::Lifetime(lifetime) => {
let lifetime = &lifetime.lifetime;
quote!(::core::marker::PhantomData<&#lifetime ()>)
Some(quote!(::core::marker::PhantomData<&#lifetime ()>))
}
syn::GenericParam::Type(ty) => {
let ty = &ty.ident;
quote!(::core::marker::PhantomData<#ty>)
}
syn::GenericParam::Const(_cnst) => {
quote!()
Some(quote!(::core::marker::PhantomData<#ty>))
}
syn::GenericParam::Const(_cnst) => None,
});
let builder_method_doc = match self.builder_attr.builder_method_doc {
Some(ref doc) => quote!(#doc),
@@ -609,8 +684,7 @@ Finally, call `.build()` to create the instance of `{name}`.
quote!(#[doc(hidden)])
};
let (b_generics_impl, b_generics_ty, b_generics_where_extras_predicates) =
b_generics.split_for_impl();
let (_, _, b_generics_where_extras_predicates) = b_generics.split_for_impl();
let mut b_generics_where: syn::WhereClause = syn::parse2(quote! {
where TypedBuilderFields: Clone
})?;
@@ -630,12 +704,39 @@ Finally, call `.build()` to create the instance of `{name}`.
false => quote! { true },
};
let extend_fields = self.extend_fields().map(|f| {
let name = f.name;
let ty = f.ty;
quote!(#name: #ty)
});
let extend_fields_value = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: Vec::new())
});
let has_extend_fields = self.extend_fields().next().is_some();
let take_bump = if has_extend_fields {
quote!(bump: _cx.bump(),)
} else {
quote!()
};
let bump_field = if has_extend_fields {
quote!(bump: & #extend_lifetime ::dioxus::core::exports::bumpalo::Bump,)
} else {
quote!()
};
let extend_lifetime = extend_lifetime.unwrap_or(syn::Lifetime::new(
"'__bump",
proc_macro2::Span::call_site(),
));
Ok(quote! {
impl #impl_generics #name #ty_generics #where_clause {
#[doc = #builder_method_doc]
#[allow(dead_code)]
#vis fn builder() -> #builder_name #generics_with_empty {
#[allow(dead_code, clippy::type_complexity)]
#vis fn builder(_cx: & #extend_lifetime ::dioxus::prelude::ScopeState) -> #builder_name #generics_with_empty {
#builder_name {
#(#extend_fields_value,)*
#take_bump
fields: #empties_tuple,
_phantom: ::core::default::Default::default(),
}
@@ -646,26 +747,19 @@ Finally, call `.build()` to create the instance of `{name}`.
#builder_type_doc
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#vis struct #builder_name #b_generics {
#(#extend_fields,)*
#bump_field
fields: #all_fields_param,
_phantom: (#( #phantom_generics ),*),
}
impl #b_generics_impl Clone for #builder_name #b_generics_ty #b_generics_where {
fn clone(&self) -> Self {
Self {
fields: self.fields.clone(),
_phantom: ::core::default::Default::default(),
}
}
}
impl #impl_generics ::dioxus::prelude::Properties for #name #ty_generics
impl #impl_generics ::dioxus::prelude::Properties<#extend_lifetime> for #name #ty_generics
#b_generics_where_extras_predicates
{
type Builder = #builder_name #generics_with_empty;
const IS_STATIC: bool = #is_static;
fn builder() -> Self::Builder {
#name::builder()
fn builder(_cx: &#extend_lifetime ::dioxus::prelude::ScopeState) -> Self::Builder {
#name::builder(_cx)
}
unsafe fn memoize(&self, other: &Self) -> bool {
#can_memoize
@@ -700,7 +794,147 @@ Finally, call `.build()` to create the instance of `{name}`.
})
}
pub fn extends_impl(&self, field: &FieldInfo) -> Result<TokenStream, Error> {
let StructInfo {
ref builder_name, ..
} = *self;
let field_name = field.name;
let descructuring = self.included_fields().map(|f| {
if f.ordinal == field.ordinal {
quote!(_)
} else {
let name = f.name;
quote!(#name)
}
});
let reconstructing = self.included_fields().map(|f| f.name);
// Add the bump lifetime to the generics
let mut ty_generics: Vec<syn::GenericArgument> = self
.generics
.params
.iter()
.map(|generic_param| match generic_param {
syn::GenericParam::Type(type_param) => {
let ident = type_param.ident.clone();
syn::parse(quote!(#ident).into()).unwrap()
}
syn::GenericParam::Lifetime(lifetime_def) => {
syn::GenericArgument::Lifetime(lifetime_def.lifetime.clone())
}
syn::GenericParam::Const(const_param) => {
let ident = const_param.ident.clone();
syn::parse(quote!(#ident).into()).unwrap()
}
})
.collect();
let mut target_generics_tuple = empty_type_tuple();
let mut ty_generics_tuple = empty_type_tuple();
let generics = self.modify_generics(|g| {
let index_after_lifetime_in_generics = g
.params
.iter()
.filter(|arg| matches!(arg, syn::GenericParam::Lifetime(_)))
.count();
for f in self.included_fields() {
if f.ordinal == field.ordinal {
ty_generics_tuple.elems.push_value(empty_type());
target_generics_tuple
.elems
.push_value(f.tuplized_type_ty_param());
} else {
g.params
.insert(index_after_lifetime_in_generics, f.generic_ty_param());
let generic_argument: syn::Type = f.type_ident();
ty_generics_tuple.elems.push_value(generic_argument.clone());
target_generics_tuple.elems.push_value(generic_argument);
}
ty_generics_tuple.elems.push_punct(Default::default());
target_generics_tuple.elems.push_punct(Default::default());
}
});
let mut target_generics = ty_generics.clone();
let index_after_lifetime_in_generics = target_generics
.iter()
.filter(|arg| matches!(arg, syn::GenericArgument::Lifetime(_)))
.count();
target_generics.insert(
index_after_lifetime_in_generics,
syn::GenericArgument::Type(target_generics_tuple.into()),
);
ty_generics.insert(
index_after_lifetime_in_generics,
syn::GenericArgument::Type(ty_generics_tuple.into()),
);
let (impl_generics, _, where_clause) = generics.split_for_impl();
let forward_extended_fields = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: self.#name)
});
let extend_lifetime = self.extend_lifetime()?.ok_or(Error::new_spanned(
field_name,
"Unable to find lifetime for extended field. Please specify it manually",
))?;
let extends_impl = field.builder_attr.extends.iter().map(|path| {
let name_str = path_to_single_string(path).unwrap();
let camel_name = name_str.to_case(Case::UpperCamel);
let marker_name = Ident::new(
format!("{}Extension", &camel_name).as_str(),
path.span(),
);
quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics dioxus_elements::extensions::#marker_name < #extend_lifetime > for #builder_name < #( #ty_generics ),* > #where_clause {}
}
});
Ok(quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics ::dioxus::prelude::HasAttributes<#extend_lifetime> for #builder_name < #( #ty_generics ),* > #where_clause {
fn push_attribute(
mut self,
name: &#extend_lifetime str,
ns: Option<&'static str>,
attr: impl ::dioxus::prelude::IntoAttributeValue<#extend_lifetime>,
volatile: bool
) -> Self {
let ( #(#descructuring,)* ) = self.fields;
self.#field_name.push(
::dioxus::core::Attribute::new(
name,
{
use ::dioxus::prelude::IntoAttributeValue;
attr.into_value(self.bump)
},
ns,
volatile,
)
);
#builder_name {
#(#forward_extended_fields,)*
bump: self.bump,
fields: ( #(#reconstructing,)* ),
_phantom: self._phantom,
}
}
}
#(#extends_impl)*
})
}
pub fn field_impl(&self, field: &FieldInfo) -> Result<TokenStream, Error> {
let FieldInfo {
name: field_name, ..
} = field;
if *field_name == "key" {
return Err(Error::new_spanned(field_name, "Naming a prop `key` is not allowed because the name can conflict with the built in key attribute. See https://dioxuslabs.com/learn/0.4/reference/dynamic_rendering#rendering-lists for more information about keys"));
}
let StructInfo {
ref builder_name, ..
} = *self;
@@ -720,6 +954,7 @@ Finally, call `.build()` to create the instance of `{name}`.
ty: field_type,
..
} = field;
// Add the bump lifetime to the generics
let mut ty_generics: Vec<syn::GenericArgument> = self
.generics
.params
@@ -782,31 +1017,16 @@ Finally, call `.build()` to create the instance of `{name}`.
None => quote!(),
};
// NOTE: both auto_into and strip_option affect `arg_type` and `arg_expr`, but the order of
// nesting is different so we have to do this little dance.
let arg_type = if field.builder_attr.strip_option {
field.type_from_inside_option(false).ok_or_else(|| {
Error::new_spanned(
field_type,
"can't `strip_option` - field is not `Option<...>`",
let arg_type = field_type;
let (arg_type, arg_expr) =
if field.builder_attr.auto_into || field.builder_attr.strip_option {
(
quote!(impl ::core::convert::Into<#arg_type>),
quote!(#field_name.into()),
)
})?
} else {
field_type
};
let (arg_type, arg_expr) = if field.builder_attr.auto_into {
(
quote!(impl ::core::convert::Into<#arg_type>),
quote!(#field_name.into()),
)
} else {
(quote!(#arg_type), quote!(#field_name))
};
let arg_expr = if field.builder_attr.strip_option {
quote!(Some(#arg_expr))
} else {
arg_expr
};
} else {
(quote!(#arg_type), quote!(#field_name))
};
let repeated_fields_error_type_name = syn::Ident::new(
&format!(
@@ -818,14 +1038,27 @@ Finally, call `.build()` to create the instance of `{name}`.
);
let repeated_fields_error_message = format!("Repeated field {field_name}");
let forward_extended_fields = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: self.#name)
});
let forward_bump = if self.extend_fields().next().is_some() {
quote!(bump: self.bump,)
} else {
quote!()
};
Ok(quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics #builder_name < #( #ty_generics ),* > #where_clause {
#doc
#[allow(clippy::type_complexity)]
pub fn #field_name (self, #field_name: #arg_type) -> #builder_name < #( #target_generics ),* > {
let #field_name = (#arg_expr,);
let ( #(#descructuring,)* ) = self.fields;
#builder_name {
#(#forward_extended_fields,)*
#forward_bump
fields: ( #(#reconstructing,)* ),
_phantom: self._phantom,
}
@@ -840,6 +1073,7 @@ Finally, call `.build()` to create the instance of `{name}`.
#[deprecated(
note = #repeated_fields_error_message
)]
#[allow(clippy::type_complexity)]
pub fn #field_name (self, _: #repeated_fields_error_type_name) -> #builder_name < #( #target_generics ),* > {
self
}
@@ -858,6 +1092,7 @@ Finally, call `.build()` to create the instance of `{name}`.
name: ref field_name,
..
} = field;
// Add a bump lifetime to the generics
let mut builder_generics: Vec<syn::GenericArgument> = self
.generics
.params
@@ -1025,7 +1260,9 @@ Finally, call `.build()` to create the instance of `{name}`.
// reordering based on that, but for now this much simpler thing is a reasonable approach.
let assignments = self.fields.iter().map(|field| {
let name = &field.name;
if let Some(ref default) = field.builder_attr.default {
if !field.builder_attr.extends.is_empty() {
quote!(let #name = self.#name;)
} else if let Some(ref default) = field.builder_attr.default {
if field.builder_attr.skip {
quote!(let #name = #default;)
} else {
+129
View File
@@ -0,0 +1,129 @@
use quote::ToTokens;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{parse_quote, Expr, Lit, Meta, Token, Type};
const FORMATTED_TYPE_START: &str = "static TY_AFTER_HERE:";
const FORMATTED_TYPE_END: &str = "= todo!();";
/// Attempts to convert the given literal to a string.
/// Converts ints and floats to their base 10 counterparts.
///
/// Returns `None` if the literal is [`Lit::Verbatim`] or if the literal is [`Lit::ByteStr`]
/// and the byte string could not be converted to UTF-8.
pub fn lit_to_string(lit: Lit) -> Option<String> {
match lit {
Lit::Str(l) => Some(l.value()),
Lit::ByteStr(l) => String::from_utf8(l.value()).ok(),
Lit::Byte(l) => Some(String::from(l.value() as char)),
Lit::Char(l) => Some(l.value().to_string()),
Lit::Int(l) => Some(l.base10_digits().to_string()),
Lit::Float(l) => Some(l.base10_digits().to_string()),
Lit::Bool(l) => Some(l.value().to_string()),
Lit::Verbatim(_) => None,
_ => None,
}
}
pub fn format_type_string(ty: &Type) -> String {
let ty_unformatted = ty.into_token_stream().to_string();
let ty_unformatted = ty_unformatted.trim();
// This should always be valid syntax.
// Not Rust code, but syntax, which is the only thing that `syn` cares about.
let Ok(file_unformatted) = syn::parse_file(&format!(
"{FORMATTED_TYPE_START}{ty_unformatted}{FORMATTED_TYPE_END}"
)) else {
return ty_unformatted.to_string();
};
let file_formatted = prettyplease::unparse(&file_unformatted);
let file_trimmed = file_formatted.trim();
let start_removed = file_trimmed.trim_start_matches(FORMATTED_TYPE_START);
let end_removed = start_removed.trim_end_matches(FORMATTED_TYPE_END);
let ty_formatted = end_removed.trim();
ty_formatted.to_string()
}
/// Represents the `#[deprecated]` attribute.
///
/// You can use the [`DeprecatedAttribute::from_meta`] function to try to parse an attribute to this struct.
#[derive(Default)]
pub struct DeprecatedAttribute {
pub since: Option<String>,
pub note: Option<String>,
}
impl DeprecatedAttribute {
/// Returns `None` if the given attribute was not a valid form of the `#[deprecated]` attribute.
pub fn from_meta(meta: &Meta) -> syn::Result<Self> {
if meta.path() != &parse_quote!(deprecated) {
return Err(syn::Error::new(
meta.span(),
"attribute path is not `deprecated`",
));
}
match &meta {
Meta::Path(_) => Ok(Self::default()),
Meta::NameValue(name_value) => {
let Expr::Lit(expr_lit) = &name_value.value else {
return Err(syn::Error::new(
name_value.span(),
"literal in `deprecated` value must be a string",
));
};
Ok(Self {
since: None,
note: lit_to_string(expr_lit.lit.clone()).map(|s| s.trim().to_string()),
})
}
Meta::List(list) => {
let parsed = list.parse_args::<DeprecatedAttributeArgsParser>()?;
Ok(Self {
since: parsed.since.map(|s| s.trim().to_string()),
note: parsed.note.map(|s| s.trim().to_string()),
})
}
}
}
}
mod kw {
use syn::custom_keyword;
custom_keyword!(since);
custom_keyword!(note);
}
struct DeprecatedAttributeArgsParser {
since: Option<String>,
note: Option<String>,
}
impl Parse for DeprecatedAttributeArgsParser {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut since: Option<String> = None;
let mut note: Option<String> = None;
if input.peek(kw::since) {
input.parse::<kw::since>()?;
input.parse::<Token![=]>()?;
since = lit_to_string(input.parse()?);
}
if input.peek(Token![,]) && input.peek2(kw::note) {
input.parse::<Token![,]>()?;
input.parse::<kw::note>()?;
input.parse::<Token![=]>()?;
note = lit_to_string(input.parse()?);
}
Ok(Self { since, note })
}
}
+1
View File
@@ -36,6 +36,7 @@ serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
tokio = { workspace = true, features = ["full"] }
dioxus = { workspace = true }
dioxus-html = { workspace = true, features = ["serialize"] }
pretty_assertions = "1.3.0"
rand = "0.8.5"
dioxus-ssr = { workspace = true }
+65 -67
View File
@@ -13,62 +13,50 @@ use crate::{
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct ElementId(pub usize);
pub(crate) struct ElementRef {
/// An Element that can be bubbled to's unique identifier.
///
/// `BubbleId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
/// unmounted, then the `BubbleId` will be reused for a new component.
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct VNodeId(pub usize);
#[derive(Debug, Clone, Copy)]
pub struct ElementRef {
// the pathway of the real element inside the template
pub path: ElementPath,
pub(crate) path: ElementPath,
// The actual template
pub template: Option<NonNull<VNode<'static>>>,
pub(crate) template: VNodeId,
// The scope the element belongs to
pub scope: ScopeId,
pub(crate) scope: ScopeId,
}
#[derive(Clone, Copy, Debug)]
pub enum ElementPath {
Deep(&'static [u8]),
Root(usize),
}
impl ElementRef {
pub(crate) fn none() -> Self {
Self {
template: None,
path: ElementPath::Root(0),
scope: ScopeId::ROOT,
}
}
pub struct ElementPath {
pub(crate) path: &'static [u8],
}
impl VirtualDom {
pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
self.next_reference(template, ElementPath::Deep(path))
pub(crate) fn next_element(&mut self) -> ElementId {
ElementId(self.elements.insert(None))
}
pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
self.next_reference(template, ElementPath::Root(path))
}
pub(crate) fn next_vnode_ref(&mut self, vnode: &VNode) -> VNodeId {
let new_id = VNodeId(self.element_refs.insert(Some(unsafe {
std::mem::transmute::<NonNull<VNode>, _>(vnode.into())
})));
pub(crate) fn next_null(&mut self) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
// Set this id to be dropped when the scope is rerun
if let Some(scope) = self.runtime.current_scope_id() {
self.scopes[scope.0]
.element_refs_to_drop
.borrow_mut()
.push(new_id);
}
entry.insert(ElementRef::none());
ElementId(id)
}
fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
let scope = self.runtime.current_scope_id().unwrap_or(ScopeId::ROOT);
entry.insert(ElementRef {
// We know this is non-null because it comes from a reference
template: Some(unsafe { NonNull::new_unchecked(template as *const _ as *mut _) }),
path,
scope,
});
ElementId(id)
new_id
}
pub(crate) fn reclaim(&mut self, el: ElementId) {
@@ -76,7 +64,7 @@ impl VirtualDom {
.unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
}
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<()> {
if el.0 == 0 {
panic!(
"Cannot reclaim the root element - {:#?}",
@@ -84,12 +72,12 @@ impl VirtualDom {
);
}
self.elements.try_remove(el.0)
self.elements.try_remove(el.0).map(|_| ())
}
pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
let node: *const VNode = node as *const _;
self.elements[el.0].template = unsafe { std::mem::transmute(node) };
pub(crate) fn set_template(&mut self, id: VNodeId, vnode: &VNode) {
self.element_refs[id.0] =
Some(unsafe { std::mem::transmute::<NonNull<VNode>, _>(vnode.into()) });
}
// Drop a scope and all its children
@@ -101,6 +89,15 @@ impl VirtualDom {
id,
});
// Remove all VNode ids from the scope
for id in self.scopes[id.0]
.element_refs_to_drop
.borrow_mut()
.drain(..)
{
self.element_refs.try_remove(id.0);
}
self.ensure_drop_safety(id);
if recursive {
@@ -145,14 +142,25 @@ impl VirtualDom {
}
/// Descend through the tree, removing any borrowed props and listeners
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
pub(crate) fn ensure_drop_safety(&mut self, scope_id: ScopeId) {
let scope = &self.scopes[scope_id.0];
{
// Drop all element refs that could be invalidated when the component was rerun
let mut element_refs = self.scopes[scope_id.0].element_refs_to_drop.borrow_mut();
let element_refs_slab = &mut self.element_refs;
for element_ref in element_refs.drain(..) {
if let Some(element_ref) = element_refs_slab.get_mut(element_ref.0) {
*element_ref = None;
}
}
}
// 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)
// recursively call ensure_drop_safety on all children
let mut props = scope.borrowed_props.borrow_mut();
props.drain(..).for_each(|comp| {
let props = { scope.borrowed_props.borrow_mut().clone() };
for comp in props {
let comp = unsafe { &*comp };
match comp.scope.get() {
Some(child) if child != scope_id => self.ensure_drop_safety(child),
@@ -161,20 +169,16 @@ impl VirtualDom {
if let Ok(mut props) = comp.props.try_borrow_mut() {
*props = None;
}
});
}
let scope = &self.scopes[scope_id.0];
scope.borrowed_props.borrow_mut().clear();
// Now that all the references are gone, we can safely drop our own references in our listeners.
let mut listeners = scope.attributes_to_drop.borrow_mut();
let mut listeners = scope.attributes_to_drop_before_render.borrow_mut();
listeners.drain(..).for_each(|listener| {
let listener = unsafe { &*listener };
match &listener.value {
AttributeValue::Listener(l) => {
_ = l.take();
}
AttributeValue::Any(a) => {
_ = a.take();
}
_ => (),
if let AttributeValue::Listener(l) = &listener.value {
_ = l.take();
}
});
}
@@ -182,18 +186,12 @@ impl VirtualDom {
impl ElementPath {
pub(crate) fn is_decendant(&self, small: &&[u8]) -> bool {
match *self {
ElementPath::Deep(big) => small.len() <= big.len() && *small == &big[..small.len()],
ElementPath::Root(r) => small.len() == 1 && small[0] == r as u8,
}
small.len() <= self.path.len() && *small == &self.path[..small.len()]
}
}
impl PartialEq<&[u8]> for ElementPath {
fn eq(&self, other: &&[u8]) -> bool {
match *self {
ElementPath::Deep(deep) => deep.eq(*other),
ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
}
self.path.eq(*other)
}
}
+41 -3
View File
@@ -1,10 +1,16 @@
use crate::nodes::RenderReturn;
use crate::{Attribute, AttributeValue, VComponent};
use bumpalo::Bump;
use std::cell::RefCell;
use std::cell::{Cell, UnsafeCell};
pub(crate) struct BumpFrame {
pub bump: UnsafeCell<Bump>,
pub node: Cell<*const RenderReturn<'static>>,
// The bump allocator will not call the destructor of the objects it allocated. Attributes and props need to have there destructor called, so we keep a list of them to drop before the bump allocator is reset.
pub(crate) attributes_to_drop_before_reset: RefCell<Vec<*const Attribute<'static>>>,
pub(crate) props_to_drop_before_reset: RefCell<Vec<*const VComponent<'static>>>,
}
impl BumpFrame {
@@ -13,6 +19,8 @@ impl BumpFrame {
Self {
bump: UnsafeCell::new(bump),
node: Cell::new(std::ptr::null()),
attributes_to_drop_before_reset: Default::default(),
props_to_drop_before_reset: Default::default(),
}
}
@@ -31,8 +39,38 @@ impl BumpFrame {
unsafe { &*self.bump.get() }
}
#[allow(clippy::mut_from_ref)]
pub(crate) unsafe fn bump_mut(&self) -> &mut Bump {
unsafe { &mut *self.bump.get() }
pub(crate) fn add_attribute_to_drop(&self, attribute: *const Attribute<'static>) {
self.attributes_to_drop_before_reset
.borrow_mut()
.push(attribute);
}
/// Reset the bump allocator and drop all the attributes and props that were allocated in it.
///
/// # Safety
/// The caller must insure that no reference to anything allocated in the bump allocator is available after this function is called.
pub(crate) unsafe fn reset(&self) {
let mut attributes = self.attributes_to_drop_before_reset.borrow_mut();
attributes.drain(..).for_each(|attribute| {
let attribute = unsafe { &*attribute };
if let AttributeValue::Any(l) = &attribute.value {
_ = l.take();
}
});
let mut props = self.props_to_drop_before_reset.borrow_mut();
props.drain(..).for_each(|prop| {
let prop = unsafe { &*prop };
_ = prop.props.borrow_mut().take();
});
unsafe {
let bump = &mut *self.bump.get();
bump.reset();
}
}
}
impl Drop for BumpFrame {
fn drop(&mut self) {
unsafe { self.reset() }
}
}
+97 -45
View File
@@ -1,5 +1,8 @@
use crate::any_props::AnyProps;
use crate::innerlude::{BorrowedAttributeValue, VComponent, VPlaceholder, VText};
use crate::innerlude::{
AttributeType, BorrowedAttributeValue, ElementPath, ElementRef, MountedAttribute, VComponent,
VPlaceholder, VText,
};
use crate::mutations::Mutation;
use crate::mutations::Mutation::*;
use crate::nodes::VNode;
@@ -94,6 +97,9 @@ impl<'b> VirtualDom {
nodes_mut.resize(len, ElementId::default());
};
// Set this node id
node.stable_id.set(Some(self.next_vnode_ref(node)));
// The best renderers will have templates prehydrated and registered
// Just in case, let's create the template using instructions anyways
self.register_template(node.template.get());
@@ -181,15 +187,30 @@ impl<'b> VirtualDom {
use DynamicNode::*;
match &template.dynamic_nodes[idx] {
node @ Component { .. } | node @ Fragment(_) => {
self.create_dynamic_node(template, node, idx)
let template_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
self.create_dynamic_node(template_ref, node)
}
Placeholder(VPlaceholder { id }) => {
let id = self.set_slot(template, id, idx);
Placeholder(VPlaceholder { id, parent }) => {
let template_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
parent.set(Some(template_ref));
let id = self.set_slot(id);
self.mutations.push(CreatePlaceholder { id });
1
}
Text(VText { id, value }) => {
let id = self.set_slot(template, id, idx);
let id = self.set_slot(id);
self.create_static_text(value, id);
1
}
@@ -205,7 +226,7 @@ impl<'b> VirtualDom {
});
}
/// We write all the descndent data for this element
/// We write all the descendent data for this element
///
/// Elements can contain other nodes - and those nodes can be dynamic or static
///
@@ -265,7 +286,14 @@ impl<'b> VirtualDom {
.map(|sorted_index| dynamic_nodes[sorted_index].0);
for idx in reversed_iter {
let m = self.create_dynamic_node(template, &template.dynamic_nodes[idx], idx);
let boundary_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
let m = self.create_dynamic_node(boundary_ref, &template.dynamic_nodes[idx]);
if m > 0 {
// The path is one shorter because the top node is the root
let path = &template.template.get().node_paths[idx][1..];
@@ -279,15 +307,15 @@ impl<'b> VirtualDom {
attrs: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>,
root_idx: u8,
root: ElementId,
node: &VNode,
node: &'b VNode<'b>,
) {
while let Some((mut attr_id, path)) =
attrs.next_if(|(_, p)| p.first().copied() == Some(root_idx))
{
let id = self.assign_static_node_as_dynamic(path, root, node, attr_id);
let id = self.assign_static_node_as_dynamic(path, root);
loop {
self.write_attribute(&node.dynamic_attrs[attr_id], id);
self.write_attribute_type(node, &node.dynamic_attrs[attr_id], attr_id, id);
// Only push the dynamic attributes forward if they match the current path (same element)
match attrs.next_if(|(_, p)| *p == path) {
@@ -298,15 +326,44 @@ impl<'b> VirtualDom {
}
}
fn write_attribute(&mut self, attribute: &'b crate::Attribute<'b>, id: ElementId) {
fn write_attribute_type(
&mut self,
vnode: &'b VNode<'b>,
attribute: &'b MountedAttribute<'b>,
idx: usize,
id: ElementId,
) {
// Make sure we set the attribute's associated id
attribute.mounted_element.set(id);
match &attribute.ty {
AttributeType::Single(attribute) => self.write_attribute(vnode, attribute, idx, id),
AttributeType::Many(attribute) => {
for attribute in *attribute {
self.write_attribute(vnode, attribute, idx, id);
}
}
}
}
pub(crate) fn write_attribute(
&mut self,
vnode: &'b VNode<'b>,
attribute: &'b crate::Attribute<'b>,
idx: usize,
id: ElementId,
) {
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_name: &str = unsafe { std::mem::transmute(attribute.name) };
match &attribute.value {
AttributeValue::Listener(_) => {
let path = &vnode.template.get().attr_paths[idx];
let element_ref = ElementRef {
path: ElementPath { path },
template: vnode.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
self.elements[id.0] = Some(element_ref);
self.mutations.push(NewEventListener {
// all listeners start with "on"
name: &unbounded_name[2..],
@@ -330,7 +387,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);
let this_id = self.next_element();
template.root_ids.borrow_mut()[root_idx] = this_id;
self.mutations.push(LoadTemplate {
@@ -353,8 +410,6 @@ impl<'b> VirtualDom {
&mut self,
path: &'static [u8],
this_id: ElementId,
template: &VNode,
attr_id: usize,
) -> ElementId {
if path.len() == 1 {
return this_id;
@@ -362,7 +417,7 @@ impl<'b> VirtualDom {
// if attribute is on a root node, then we've already created the element
// Else, it's deep in the template and we should create a new id for it
let id = self.next_element(template, template.template.get().attr_paths[attr_id]);
let id = self.next_element();
self.mutations.push(Mutation::AssignId {
path: &path[1..],
@@ -405,6 +460,7 @@ impl<'b> VirtualDom {
#[allow(unused_mut)]
pub(crate) fn register_template(&mut self, mut template: Template<'static>) {
let (path, byte_index) = template.name.rsplit_once(':').unwrap();
let byte_index = byte_index.parse::<usize>().unwrap();
// First, check if we've already seen this template
if self
@@ -439,27 +495,21 @@ impl<'b> VirtualDom {
pub(crate) fn create_dynamic_node(
&mut self,
template: &'b VNode<'b>,
parent: ElementRef,
node: &'b DynamicNode<'b>,
idx: usize,
) -> usize {
use DynamicNode::*;
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),
Fragment(frag) => frag.iter().map(|child| self.create(child)).sum(),
Text(text) => self.create_dynamic_text(parent, text),
Placeholder(place) => self.create_placeholder(place, parent),
Component(component) => self.create_component_node(Some(parent), component),
Fragment(frag) => self.create_children(*frag, Some(parent)),
}
}
fn create_dynamic_text(
&mut self,
template: &'b VNode<'b>,
text: &'b VText<'b>,
idx: usize,
) -> usize {
fn create_dynamic_text(&mut self, parent: ElementRef, text: &'b VText<'b>) -> usize {
// Allocate a dynamic element reference for this text node
let new_id = self.next_element(template, template.template.get().node_paths[idx]);
let new_id = self.next_element();
// Make sure the text node is assigned to the correct element
text.id.set(Some(new_id));
@@ -470,7 +520,7 @@ impl<'b> VirtualDom {
// Add the mutation to the list
self.mutations.push(HydrateText {
id: new_id,
path: &template.template.get().node_paths[idx][1..],
path: &parent.path.path[1..],
value,
});
@@ -481,18 +531,20 @@ impl<'b> VirtualDom {
pub(crate) fn create_placeholder(
&mut self,
placeholder: &VPlaceholder,
template: &'b VNode<'b>,
idx: usize,
parent: ElementRef,
) -> usize {
// Allocate a dynamic element reference for this text node
let id = self.next_element(template, template.template.get().node_paths[idx]);
let id = self.next_element();
// Make sure the text node is assigned to the correct element
placeholder.id.set(Some(id));
// Assign the placeholder's parent
placeholder.parent.set(Some(parent));
// Assign the ID to the existing node in the template
self.mutations.push(AssignId {
path: &template.template.get().node_paths[idx][1..],
path: &parent.path.path[1..],
id,
});
@@ -502,7 +554,7 @@ impl<'b> VirtualDom {
pub(super) fn create_component_node(
&mut self,
template: &'b VNode<'b>,
parent: Option<ElementRef>,
component: &'b VComponent<'b>,
) -> usize {
use RenderReturn::*;
@@ -514,8 +566,11 @@ impl<'b> VirtualDom {
match unsafe { self.run_scope(scope).extend_lifetime_ref() } {
// Create the component's root element
Ready(t) => self.create_scope(scope, t),
Aborted(t) => self.mount_aborted(template, t),
Ready(t) => {
self.assign_boundary_ref(parent, t);
self.create_scope(scope, t)
}
Aborted(t) => self.mount_aborted(t, parent),
}
}
@@ -531,20 +586,17 @@ impl<'b> VirtualDom {
.unwrap_or_else(|| component.scope.get().unwrap())
}
fn mount_aborted(&mut self, parent: &'b VNode<'b>, placeholder: &VPlaceholder) -> usize {
let id = self.next_element(parent, &[]);
fn mount_aborted(&mut self, placeholder: &VPlaceholder, parent: Option<ElementRef>) -> usize {
let id = self.next_element();
self.mutations.push(Mutation::CreatePlaceholder { id });
placeholder.id.set(Some(id));
placeholder.parent.set(parent);
1
}
fn set_slot(
&mut self,
template: &'b VNode<'b>,
slot: &'b Cell<Option<ElementId>>,
id: usize,
) -> ElementId {
let id = self.next_element(template, template.template.get().node_paths[id]);
fn set_slot(&mut self, slot: &'b Cell<Option<ElementId>>) -> ElementId {
let id = self.next_element();
slot.set(Some(id));
id
}
+222 -69
View File
@@ -1,7 +1,10 @@
use crate::{
any_props::AnyProps,
arena::ElementId,
innerlude::{BorrowedAttributeValue, DirtyScope, VComponent, VPlaceholder, VText},
innerlude::{
AttributeType, BorrowedAttributeValue, DirtyScope, ElementPath, ElementRef, VComponent,
VPlaceholder, VText,
},
mutations::Mutation,
nodes::RenderReturn,
nodes::{DynamicNode, VNode},
@@ -39,19 +42,27 @@ impl<'b> VirtualDom {
(Ready(l), Aborted(p)) => self.diff_ok_to_err(l, p),
// Just move over the placeholder
(Aborted(l), Aborted(r)) => r.id.set(l.id.get()),
(Aborted(l), Aborted(r)) => {
r.id.set(l.id.get());
r.parent.set(l.parent.get())
}
// Placeholder becomes something
// We should also clear the error now
(Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
(Aborted(l), Ready(r)) => self.replace_placeholder(
l,
[r],
l.parent.get().expect("root node should not be none"),
),
};
}
self.runtime.scope_stack.borrow_mut().pop();
}
fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
let id = self.next_null();
let id = self.next_element();
p.id.set(Some(id));
p.parent.set(l.parent.get());
self.mutations.push(Mutation::CreatePlaceholder { id });
let pre_edits = self.mutations.edits.len();
@@ -81,12 +92,24 @@ impl<'b> VirtualDom {
if let Some(&template) = map.get(&byte_index) {
right_template.template.set(template);
if template != left_template.template.get() {
return self.replace(left_template, [right_template]);
let parent = left_template.parent.take();
return self.replace(left_template, [right_template], parent);
}
}
}
}
// Copy over the parent
{
right_template.parent.set(left_template.parent.get());
}
// Update the bubble id pointer
right_template.stable_id.set(left_template.stable_id.get());
if let Some(bubble_id) = right_template.stable_id.get() {
self.set_template(bubble_id, right_template);
}
// If the templates are the same, we don't need to do anything, nor do we want to
if templates_are_the_same(left_template, right_template) {
return;
@@ -103,18 +126,54 @@ impl<'b> VirtualDom {
.dynamic_attrs
.iter()
.zip(right_template.dynamic_attrs.iter())
.for_each(|(left_attr, right_attr)| {
.enumerate()
.for_each(|(idx, (left_attr, right_attr))| {
// Move over the ID from the old to the new
right_attr
.mounted_element
.set(left_attr.mounted_element.get());
let mounted_id = left_attr.mounted_element.get();
right_attr.mounted_element.set(mounted_id);
// We want to make sure anything that gets pulled is valid
self.update_template(left_attr.mounted_element.get(), right_template);
match (&left_attr.ty, &right_attr.ty) {
(AttributeType::Single(left), AttributeType::Single(right)) => {
self.diff_attribute(left, right, mounted_id)
}
(AttributeType::Many(left), AttributeType::Many(right)) => {
let mut left_iter = left.iter().peekable();
let mut right_iter = right.iter().peekable();
// If the attributes are different (or volatile), we need to update them
if left_attr.value != right_attr.value || left_attr.volatile {
self.update_attribute(right_attr, left_attr);
loop {
match (left_iter.peek(), right_iter.peek()) {
(Some(left), Some(right)) => {
// check which name is greater
match left.name.cmp(right.name) {
std::cmp::Ordering::Less => self.remove_attribute(
left.name,
left.namespace,
mounted_id,
),
std::cmp::Ordering::Greater => self.write_attribute(
right_template,
right,
idx,
mounted_id,
),
std::cmp::Ordering::Equal => {
self.diff_attribute(left, right, mounted_id)
}
}
}
(Some(_), None) => {
let left = left_iter.next().unwrap();
self.remove_attribute(left.name, left.namespace, mounted_id)
}
(None, Some(_)) => {
let right = right_iter.next().unwrap();
self.write_attribute(right_template, right, idx, mounted_id)
}
(None, None) => break,
}
}
}
_ => unreachable!("The macro should never generate this case"),
}
});
@@ -123,8 +182,16 @@ impl<'b> VirtualDom {
.dynamic_nodes
.iter()
.zip(right_template.dynamic_nodes.iter())
.for_each(|(left_node, right_node)| {
self.diff_dynamic_node(left_node, right_node, right_template);
.enumerate()
.for_each(|(dyn_node_idx, (left_node, right_node))| {
let current_ref = ElementRef {
template: right_template.stable_id().unwrap(),
path: ElementPath {
path: left_template.template.get().node_paths[dyn_node_idx],
},
scope: self.runtime.scope_stack.borrow().last().copied().unwrap(),
};
self.diff_dynamic_node(left_node, right_node, current_ref);
});
// Make sure the roots get transferred over while we're here
@@ -135,14 +202,17 @@ impl<'b> VirtualDom {
right.push(element);
}
}
}
let root_ids = right_template.root_ids.borrow();
// Update the node refs
for i in 0..root_ids.len() {
if let Some(root_id) = root_ids.get(i) {
self.update_template(*root_id, right_template);
}
fn diff_attribute(
&mut self,
left_attr: &'b Attribute<'b>,
right_attr: &'b Attribute<'b>,
id: ElementId,
) {
// If the attributes are different (or volatile), we need to update them
if left_attr.value != right_attr.value || left_attr.volatile {
self.update_attribute(right_attr, left_attr, id);
}
}
@@ -150,25 +220,45 @@ impl<'b> VirtualDom {
&mut self,
left_node: &'b DynamicNode<'b>,
right_node: &'b DynamicNode<'b>,
node: &'b VNode<'b>,
parent: ElementRef,
) {
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),
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right),
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right),
(Text(left), Text(right)) => self.diff_vtext(left, right),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right, parent),
(Placeholder(left), Placeholder(right)) => {
right.id.set(left.id.get());
right.parent.set(left.parent.get());
},
(Component(left), Component(right)) => self.diff_vcomponent(left, right, Some(parent)),
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right, parent),
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right, parent),
_ => todo!("This is an usual custom case for dynamic nodes. We don't know how to handle it yet."),
};
}
fn update_attribute(&mut self, right_attr: &'b Attribute<'b>, left_attr: &'b Attribute) {
fn remove_attribute(&mut self, name: &'b str, ns: Option<&'static str>, id: ElementId) {
let name = unsafe { std::mem::transmute(name) };
let value: BorrowedAttributeValue<'b> = BorrowedAttributeValue::None;
let value = unsafe { std::mem::transmute(value) };
self.mutations.push(Mutation::SetAttribute {
id,
ns,
name,
value,
});
}
fn update_attribute(
&mut self,
right_attr: &'b Attribute<'b>,
left_attr: &'b Attribute<'b>,
id: ElementId,
) {
let name = unsafe { std::mem::transmute(left_attr.name) };
let value: BorrowedAttributeValue<'b> = (&right_attr.value).into();
let value = unsafe { std::mem::transmute(value) };
self.mutations.push(Mutation::SetAttribute {
id: left_attr.mounted_element.get(),
id,
ns: right_attr.namespace,
name,
value,
@@ -179,7 +269,7 @@ impl<'b> VirtualDom {
&mut self,
left: &'b VComponent<'b>,
right: &'b VComponent<'b>,
right_template: &'b VNode<'b>,
parent: Option<ElementRef>,
) {
if std::ptr::eq(left, right) {
return;
@@ -187,7 +277,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, left);
return self.replace_vcomponent(right, left, parent);
}
// Make sure the new vcomponent has the right scopeid associated to it
@@ -228,11 +318,11 @@ impl<'b> VirtualDom {
fn replace_vcomponent(
&mut self,
right_template: &'b VNode<'b>,
right: &'b VComponent<'b>,
left: &'b VComponent<'b>,
parent: Option<ElementRef>,
) {
let m = self.create_component_node(right_template, right);
let m = self.create_component_node(parent, right);
let pre_edits = self.mutations.edits.len();
@@ -287,11 +377,12 @@ impl<'b> VirtualDom {
/// }
/// ```
fn light_diff_templates(&mut self, left: &'b VNode<'b>, right: &'b VNode<'b>) {
let parent = left.parent.take();
match matching_components(left, right) {
None => self.replace(left, [right]),
None => self.replace(left, [right], parent),
Some(components) => components
.into_iter()
.for_each(|(l, r)| self.diff_vcomponent(l, r, right)),
.for_each(|(l, r)| self.diff_vcomponent(l, r, parent)),
}
}
@@ -299,11 +390,8 @@ impl<'b> VirtualDom {
///
/// This just moves the ID of the old node over to the new node, and then sets the text of the new node if it's
/// different.
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>, node: &'b VNode<'b>) {
let id = left
.id
.get()
.unwrap_or_else(|| self.next_element(node, &[0]));
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>) {
let id = left.id.get().unwrap_or_else(|| self.next_element());
right.id.set(Some(id));
if left.value != right.value {
@@ -312,7 +400,12 @@ impl<'b> VirtualDom {
}
}
fn diff_non_empty_fragment(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_non_empty_fragment(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
let new_is_keyed = new[0].key.is_some();
let old_is_keyed = old[0].key.is_some();
debug_assert!(
@@ -325,9 +418,9 @@ impl<'b> VirtualDom {
);
if new_is_keyed && old_is_keyed {
self.diff_keyed_children(old, new);
self.diff_keyed_children(old, new, parent);
} else {
self.diff_non_keyed_children(old, new);
self.diff_non_keyed_children(old, new, parent);
}
}
@@ -339,7 +432,12 @@ impl<'b> VirtualDom {
// [... parent]
//
// the change list stack is in the same state when this function returns.
fn diff_non_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_non_keyed_children(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
use std::cmp::Ordering;
// Handled these cases in `diff_children` before calling this function.
@@ -348,7 +446,9 @@ impl<'b> VirtualDom {
match old.len().cmp(&new.len()) {
Ordering::Greater => self.remove_nodes(&old[new.len()..]),
Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
Ordering::Less => {
self.create_and_insert_after(&new[old.len()..], old.last().unwrap(), parent)
}
Ordering::Equal => {}
}
@@ -373,7 +473,12 @@ impl<'b> VirtualDom {
// https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
//
// The stack is empty upon entry.
fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_keyed_children(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
if cfg!(debug_assertions) {
let mut keys = rustc_hash::FxHashSet::default();
let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
@@ -401,7 +506,7 @@ impl<'b> VirtualDom {
//
// `shared_prefix_count` is the count of how many nodes at the start of
// `new` and `old` share the same keys.
let (left_offset, right_offset) = match self.diff_keyed_ends(old, new) {
let (left_offset, right_offset) = match self.diff_keyed_ends(old, new, parent) {
Some(count) => count,
None => return,
};
@@ -427,18 +532,18 @@ impl<'b> VirtualDom {
if left_offset == 0 {
// insert at the beginning of the old list
let foothold = &old[old.len() - right_offset];
self.create_and_insert_before(new_middle, foothold);
self.create_and_insert_before(new_middle, foothold, parent);
} else if right_offset == 0 {
// insert at the end the old list
let foothold = old.last().unwrap();
self.create_and_insert_after(new_middle, foothold);
self.create_and_insert_after(new_middle, foothold, parent);
} else {
// inserting in the middle
let foothold = &old[left_offset - 1];
self.create_and_insert_after(new_middle, foothold);
self.create_and_insert_after(new_middle, foothold, parent);
}
} else {
self.diff_keyed_middle(old_middle, new_middle);
self.diff_keyed_middle(old_middle, new_middle, parent);
}
}
@@ -451,6 +556,7 @@ impl<'b> VirtualDom {
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) -> Option<(usize, usize)> {
let mut left_offset = 0;
@@ -466,7 +572,7 @@ impl<'b> VirtualDom {
// If that was all of the old children, then create and append the remaining
// new children and we're finished.
if left_offset == old.len() {
self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
self.create_and_insert_after(&new[left_offset..], old.last().unwrap(), parent);
return None;
}
@@ -505,7 +611,12 @@ impl<'b> VirtualDom {
//
// Upon exit from this function, it will be restored to that same self.
#[allow(clippy::too_many_lines)]
fn diff_keyed_middle(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_keyed_middle(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
/*
1. Map the old keys into a numerical ordering based on indices.
2. Create a map of old key to its index
@@ -560,9 +671,9 @@ impl<'b> VirtualDom {
// If none of the old keys are reused by the new children, then we remove all the remaining old children and
// create the new children afresh.
if shared_keys.is_empty() {
if old.get(0).is_some() {
if !old.is_empty() {
self.remove_nodes(&old[1..]);
self.replace(&old[0], new);
self.replace(&old[0], new, Some(parent));
} else {
// I think this is wrong - why are we appending?
// only valid of the if there are no trailing elements
@@ -739,20 +850,38 @@ impl<'b> VirtualDom {
.sum()
}
fn create_children(&mut self, nodes: impl IntoIterator<Item = &'b VNode<'b>>) -> usize {
pub(crate) fn create_children(
&mut self,
nodes: impl IntoIterator<Item = &'b VNode<'b>>,
parent: Option<ElementRef>,
) -> usize {
nodes
.into_iter()
.fold(0, |acc, child| acc + self.create(child))
.map(|child| {
self.assign_boundary_ref(parent, child);
self.create(child)
})
.sum()
}
fn create_and_insert_before(&mut self, new: &'b [VNode<'b>], before: &'b VNode<'b>) {
let m = self.create_children(new);
fn create_and_insert_before(
&mut self,
new: &'b [VNode<'b>],
before: &'b VNode<'b>,
parent: ElementRef,
) {
let m = self.create_children(new, Some(parent));
let id = self.find_first_element(before);
self.mutations.push(Mutation::InsertBefore { id, m })
}
fn create_and_insert_after(&mut self, new: &'b [VNode<'b>], after: &'b VNode<'b>) {
let m = self.create_children(new);
fn create_and_insert_after(
&mut self,
new: &'b [VNode<'b>],
after: &'b VNode<'b>,
parent: ElementRef,
) {
let m = self.create_children(new, Some(parent));
let id = self.find_last_element(after);
self.mutations.push(Mutation::InsertAfter { id, m })
}
@@ -762,15 +891,21 @@ impl<'b> VirtualDom {
&mut self,
l: &'b VPlaceholder,
r: impl IntoIterator<Item = &'b VNode<'b>>,
parent: ElementRef,
) {
let m = self.create_children(r);
let m = self.create_children(r, Some(parent));
let id = l.id.get().unwrap();
self.mutations.push(Mutation::ReplaceWith { id, m });
self.reclaim(id);
}
fn replace(&mut self, left: &'b VNode<'b>, right: impl IntoIterator<Item = &'b VNode<'b>>) {
let m = self.create_children(right);
fn replace(
&mut self,
left: &'b VNode<'b>,
right: impl IntoIterator<Item = &'b VNode<'b>>,
parent: Option<ElementRef>,
) {
let m = self.create_children(right, parent);
let pre_edits = self.mutations.edits.len();
@@ -789,11 +924,12 @@ impl<'b> VirtualDom {
};
}
fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder) {
fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder, parent: ElementRef) {
// Create the placeholder first, ensuring we get a dedicated ID for the placeholder
let placeholder = self.next_element(&l[0], &[]);
let placeholder = self.next_element();
r.id.set(Some(placeholder));
r.parent.set(Some(parent));
self.mutations
.push(Mutation::CreatePlaceholder { id: placeholder });
@@ -831,6 +967,16 @@ impl<'b> VirtualDom {
// Clean up the roots, assuming we need to generate mutations for these
// This is done last in order to preserve Node ID reclaim order (reclaim in reverse order of claim)
self.reclaim_roots(node, gen_muts);
// Clean up the vnode id
self.reclaim_vnode_id(node);
}
fn reclaim_vnode_id(&mut self, node: &'b VNode<'b>) {
// Clean up the vnode id
if let Some(id) = node.stable_id() {
self.element_refs.remove(id.0);
}
}
fn reclaim_roots(&mut self, node: &VNode, gen_muts: bool) {
@@ -989,6 +1135,13 @@ impl<'b> VirtualDom {
}
}
}
pub(crate) fn assign_boundary_ref(&mut self, parent: Option<ElementRef>, child: &'b VNode<'b>) {
if let Some(parent) = parent {
// assign the parent of the child
child.parent.set(Some(parent));
}
}
}
/// Are the templates the same?
+351 -63
View File
@@ -1,25 +1,68 @@
use crate::{ScopeId, ScopeState};
use crate::{
scope_context::{consume_context, current_scope_id, schedule_update_any},
Element, IntoDynNode, LazyNodes, Properties, Scope, ScopeId, ScopeState, Template,
TemplateAttribute, TemplateNode, VNode,
};
use std::{
any::{Any, TypeId},
cell::RefCell,
fmt::Debug,
backtrace::Backtrace,
cell::{Cell, RefCell},
error::Error,
fmt::{Debug, Display},
rc::Rc,
sync::Arc,
};
/// A boundary that will capture any errors from child components
pub struct ErrorBoundary {
error: RefCell<Option<CapturedError>>,
_id: ScopeId,
/// Provide an error boundary to catch errors from child components
pub fn use_error_boundary(cx: &ScopeState) -> &ErrorBoundary {
cx.use_hook(|| cx.provide_context(ErrorBoundary::new()))
}
/// A boundary that will capture any errors from child components
#[derive(Debug, Clone, Default)]
pub struct ErrorBoundary {
inner: Rc<ErrorBoundaryInner>,
}
/// A boundary that will capture any errors from child components
pub struct ErrorBoundaryInner {
error: RefCell<Option<CapturedError>>,
_id: ScopeId,
rerun_boundary: Arc<dyn Fn(ScopeId) + Send + Sync>,
}
impl Debug for ErrorBoundaryInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ErrorBoundaryInner")
.field("error", &self.error)
.finish()
}
}
#[derive(Debug)]
/// An instance of an error captured by a descendant component.
pub struct CapturedError {
/// The error captured by the error boundary
pub error: Box<dyn Debug + 'static>,
/// The backtrace of the error
pub backtrace: Backtrace,
/// The scope that threw the error
pub scope: ScopeId,
}
impl Display for CapturedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"Encountered error: {:?}\nIn scope: {:?}\nBacktrace: {}",
self.error, self.scope, self.backtrace
))
}
}
impl Error for CapturedError {}
impl CapturedError {
/// Downcast the error type into a concrete error type
pub fn downcast<T: 'static>(&self) -> Option<&T> {
@@ -32,17 +75,56 @@ impl CapturedError {
}
}
impl ErrorBoundary {
pub fn new(id: ScopeId) -> Self {
impl Default for ErrorBoundaryInner {
fn default() -> Self {
Self {
error: RefCell::new(None),
_id: id,
_id: current_scope_id()
.expect("Cannot create an error boundary outside of a component's scope."),
rerun_boundary: schedule_update_any().unwrap(),
}
}
}
impl ErrorBoundary {
/// Create a new error boundary
pub fn new() -> Self {
Self::default()
}
/// Create a new error boundary in the current scope
pub(crate) fn new_in_scope(
scope: ScopeId,
rerun_boundary: Arc<dyn Fn(ScopeId) + Send + Sync>,
) -> Self {
Self {
inner: Rc::new(ErrorBoundaryInner {
error: RefCell::new(None),
_id: scope,
rerun_boundary,
}),
}
}
/// Push an error into this Error Boundary
pub fn insert_error(&self, scope: ScopeId, error: Box<dyn Debug + 'static>) {
self.error.replace(Some(CapturedError { error, scope }));
pub fn insert_error(
&self,
scope: ScopeId,
error: Box<dyn Debug + 'static>,
backtrace: Backtrace,
) {
println!("{:?} {:?}", error, self.inner._id);
self.inner.error.replace(Some(CapturedError {
error,
scope,
backtrace,
}));
(self.inner.rerun_boundary)(self.inner._id);
}
/// Take any error that has been captured by this error boundary
pub fn take_error(&self) -> Option<CapturedError> {
self.inner.error.take()
}
}
@@ -59,7 +141,7 @@ impl ErrorBoundary {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
@@ -84,14 +166,14 @@ pub trait Throw<S = ()>: Sized {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
/// })
/// }
/// ```
fn throw(self, cx: &ScopeState) -> Option<Self::Out>;
fn throw(self) -> Option<Self::Out>;
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
@@ -107,45 +189,46 @@ pub trait Throw<S = ()>: Sized {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
/// })
/// }
/// ```
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
e: impl FnOnce() -> D,
) -> Option<Self::Out>;
fn throw_with<D: Debug + 'static>(self, e: impl FnOnce() -> D) -> Option<Self::Out> {
self.throw().or_else(|| throw_error(e()))
}
}
fn throw_error<T>(e: impl Debug + 'static) -> Option<T> {
if let Some(cx) = consume_context::<ErrorBoundary>() {
match current_scope_id() {
Some(id) => cx.insert_error(id, Box::new(e), Backtrace::capture()),
None => {
tracing::error!("Cannot throw error outside of a component's scope.")
}
}
}
None
}
/// We call clone on any errors that can be owned out of a reference
impl<'a, T, O: Debug + 'static, E: ToOwned<Owned = O>> Throw for &'a Result<T, E> {
type Out = &'a T;
fn throw(self, cx: &ScopeState) -> Option<Self::Out> {
fn throw(self) -> Option<Self::Out> {
match self {
Ok(t) => Some(t),
Err(e) => {
cx.throw(e.to_owned());
None
}
Err(e) => throw_error(e.to_owned()),
}
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
err: impl FnOnce() -> D,
) -> Option<Self::Out> {
fn throw_with<D: Debug + 'static>(self, err: impl FnOnce() -> D) -> Option<Self::Out> {
match self {
Ok(t) => Some(t),
Err(_e) => {
cx.throw(err());
None
}
Err(_e) => throw_error(err()),
}
}
}
@@ -154,25 +237,15 @@ impl<'a, T, O: Debug + 'static, E: ToOwned<Owned = O>> Throw for &'a Result<T, E
impl<T, E: Debug + 'static> Throw for Result<T, E> {
type Out = T;
fn throw(self, cx: &ScopeState) -> Option<T> {
fn throw(self) -> Option<T> {
match self {
Ok(t) => Some(t),
Err(e) => {
cx.throw(e);
None
}
Err(e) => throw_error(e),
}
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
error: impl FnOnce() -> D,
) -> Option<Self::Out> {
self.ok().or_else(|| {
cx.throw(error());
None
})
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
self.ok().or_else(|| throw_error(error()))
}
}
@@ -180,21 +253,236 @@ impl<T, E: Debug + 'static> Throw for Result<T, E> {
impl<T> Throw for Option<T> {
type Out = T;
fn throw(self, cx: &ScopeState) -> Option<T> {
self.or_else(|| {
cx.throw("None error.");
None
})
fn throw(self) -> Option<T> {
self.or_else(|| throw_error("Attempted to unwrap a None value."))
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
error: impl FnOnce() -> D,
) -> Option<Self::Out> {
self.or_else(|| {
cx.throw(error());
None
})
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
self.or_else(|| throw_error(error()))
}
}
pub struct ErrorHandler<'a>(Box<dyn Fn(CapturedError) -> LazyNodes<'a, 'a> + 'a>);
impl<'a, F: Fn(CapturedError) -> LazyNodes<'a, 'a> + 'a> From<F> for ErrorHandler<'a> {
fn from(value: F) -> Self {
Self(Box::new(value))
}
}
fn default_handler<'a>(error: CapturedError) -> LazyNodes<'a, 'a> {
LazyNodes::new(move |__cx: &ScopeState| -> VNode {
static TEMPLATE: Template = Template {
name: "error_handle.rs:42:5:884",
roots: &[TemplateNode::Element {
tag: "pre",
namespace: None,
attrs: &[TemplateAttribute::Static {
name: "color",
namespace: Some("style"),
value: "red",
}],
children: &[TemplateNode::DynamicText { id: 0usize }],
}],
node_paths: &[&[0u8, 0u8]],
attr_paths: &[],
};
VNode {
parent: Default::default(),
stable_id: Default::default(),
key: None,
template: std::cell::Cell::new(TEMPLATE),
root_ids: bumpalo::collections::Vec::with_capacity_in(1usize, __cx.bump()).into(),
dynamic_nodes: __cx
.bump()
.alloc([__cx.text_node(format_args!("{0}", error))]),
dynamic_attrs: __cx.bump().alloc([]),
}
})
}
pub struct ErrorBoundaryProps<'a> {
children: Element<'a>,
handle_error: ErrorHandler<'a>,
}
impl<'a> ErrorBoundaryProps<'a> {
/**
Create a builder for building `ErrorBoundaryProps`.
On the builder, call `.children(...)`(optional), `.handle_error(...)`(optional) to set the values of the fields.
Finally, call `.build()` to create the instance of `ErrorBoundaryProps`.
*/
#[allow(dead_code)]
pub fn builder() -> ErrorBoundaryPropsBuilder<'a, ((), ())> {
ErrorBoundaryPropsBuilder {
fields: ((), ()),
_phantom: ::core::default::Default::default(),
}
}
}
#[must_use]
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub struct ErrorBoundaryPropsBuilder<'a, TypedBuilderFields> {
fields: TypedBuilderFields,
_phantom: ::core::marker::PhantomData<&'a ()>,
}
impl<'a, TypedBuilderFields> Clone for ErrorBoundaryPropsBuilder<'a, TypedBuilderFields>
where
TypedBuilderFields: Clone,
{
fn clone(&self) -> Self {
Self {
fields: self.fields.clone(),
_phantom: ::core::default::Default::default(),
}
}
}
impl<'a> Properties<'a> for ErrorBoundaryProps<'a> {
type Builder = ErrorBoundaryPropsBuilder<'a, ((), ())>;
const IS_STATIC: bool = false;
fn builder(_: &'a ScopeState) -> Self::Builder {
ErrorBoundaryProps::builder()
}
unsafe fn memoize(&self, _: &Self) -> bool {
false
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub trait ErrorBoundaryPropsBuilder_Optional<T> {
fn into_value<F: FnOnce() -> T>(self, default: F) -> T;
}
impl<T> ErrorBoundaryPropsBuilder_Optional<T> for () {
fn into_value<F: FnOnce() -> T>(self, default: F) -> T {
default()
}
}
impl<T> ErrorBoundaryPropsBuilder_Optional<T> for (T,) {
fn into_value<F: FnOnce() -> T>(self, _: F) -> T {
self.0
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __handle_error> ErrorBoundaryPropsBuilder<'a, ((), __handle_error)> {
pub fn children(
self,
children: Element<'a>,
) -> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
let children = (children,);
let (_, handle_error) = self.fields;
ErrorBoundaryPropsBuilder {
fields: (children, handle_error),
_phantom: self._phantom,
}
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_children {}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __handle_error> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
#[deprecated(note = "Repeated field children")]
pub fn children(
self,
_: ErrorBoundaryPropsBuilder_Error_Repeated_field_children,
) -> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
self
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __children> ErrorBoundaryPropsBuilder<'a, (__children, ())> {
pub fn handle_error(
self,
handle_error: impl ::core::convert::Into<ErrorHandler<'a>>,
) -> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
let handle_error = (handle_error.into(),);
let (children, _) = self.fields;
ErrorBoundaryPropsBuilder {
fields: (children, handle_error),
_phantom: self._phantom,
}
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error {}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __children> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
#[deprecated(note = "Repeated field handle_error")]
pub fn handle_error(
self,
_: ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error,
) -> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
self
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<
'a,
__handle_error: ErrorBoundaryPropsBuilder_Optional<ErrorHandler<'a>>,
__children: ErrorBoundaryPropsBuilder_Optional<Element<'a>>,
> ErrorBoundaryPropsBuilder<'a, (__children, __handle_error)>
{
pub fn build(self) -> ErrorBoundaryProps<'a> {
let (children, handle_error) = self.fields;
let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, || {
::core::default::Default::default()
});
let handle_error = ErrorBoundaryPropsBuilder_Optional::into_value(handle_error, || {
ErrorHandler(Box::new(default_handler))
});
ErrorBoundaryProps {
children,
handle_error,
}
}
}
/// Create a new error boundary component.
///
/// ## Details
///
/// Error boundaries handle errors within a specific part of your application. Any errors passed in a child with [`Throw`] will be caught by the nearest error boundary.
///
/// ## Example
///
/// ```rust, ignore
/// rsx!{
/// ErrorBoundary {
/// handle_error: |error| rsx! { "Oops, we encountered an error. Please report {error} to the developer of this application" }
/// ThrowsError {}
/// }
/// }
/// ```
///
/// ## Usage
///
/// Error boundaries are an easy way to handle errors in your application.
/// They are similar to `try/catch` in JavaScript, but they only catch errors in the tree below them.
/// Error boundaries are quick to implement, but it can be useful to individually handle errors in your components to provide a better user experience when you know that an error is likely to occur.
#[allow(non_upper_case_globals, non_snake_case)]
pub fn ErrorBoundary<'a>(cx: Scope<'a, ErrorBoundaryProps<'a>>) -> Element {
let error_boundary = use_error_boundary(cx);
match error_boundary.take_error() {
Some(error) => cx.render((cx.props.handle_error.0)(error)),
None => Some({
let __cx = cx;
static TEMPLATE: Template = Template {
name: "examples/error_handle.rs:81:17:2342",
roots: &[TemplateNode::Dynamic { id: 0usize }],
node_paths: &[&[0u8]],
attr_paths: &[],
};
VNode {
parent: Cell::new(None),
stable_id: Cell::new(None),
key: None,
template: std::cell::Cell::new(TEMPLATE),
root_ids: bumpalo::collections::Vec::with_capacity_in(1usize, __cx.bump()).into(),
dynamic_nodes: __cx.bump().alloc([{
let ___nodes = (&cx.props.children).into_dyn_node(__cx);
___nodes
}]),
dynamic_attrs: __cx.bump().alloc([]),
}
}),
}
}
+21 -2
View File
@@ -28,6 +28,27 @@ pub struct Event<T: 'static + ?Sized> {
}
impl<T> Event<T> {
/// Map the event data to a new type
///
/// # Example
///
/// ```rust, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<FormData>| {
/// let data = evt.map(|data| data.value());
/// assert_eq!(data.inner(), "hello world");
/// }
/// }
/// }
/// ```
pub fn map<U: 'static, F: FnOnce(&T) -> U>(&self, f: F) -> Event<U> {
Event {
data: Rc::new(f(&self.data)),
propagates: self.propagates.clone(),
}
}
/// Prevent this event from continuing to bubble up the tree to parent elements.
///
/// # Example
@@ -107,8 +128,6 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
}
}
#[doc(hidden)]
/// The callback type generated by the `rsx!` macro when an `on` field is specified for components.
///
/// This makes it possible to pass `move |evt| {}` style closures into components as property fields.
+4 -3
View File
@@ -30,7 +30,8 @@ pub fn Fragment<'a>(cx: Scope<'a, FragmentProps<'a>>) -> Element {
let children = cx.props.0.as_ref()?;
Some(VNode {
key: children.key,
parent: children.parent,
parent: children.parent.clone(),
stable_id: children.stable_id.clone(),
template: children.template.clone(),
root_ids: children.root_ids.clone(),
dynamic_nodes: children.dynamic_nodes,
@@ -91,10 +92,10 @@ impl<'a, const A: bool> FragmentBuilder<'a, A> {
/// })
/// }
/// ```
impl<'a> Properties for FragmentProps<'a> {
impl<'a> Properties<'_> for FragmentProps<'a> {
type Builder = FragmentBuilder<'a, false>;
const IS_STATIC: bool = false;
fn builder() -> Self::Builder {
fn builder(_cx: &ScopeState) -> Self::Builder {
FragmentBuilder(None)
}
unsafe fn memoize(&self, _other: &Self) -> bool {
+32 -3
View File
@@ -18,13 +18,42 @@ use crate::{innerlude::VNode, ScopeState};
/// A concrete type provider for closures that build [`VNode`] structures.
///
/// This struct wraps lazy structs that build [`VNode`] trees Normally, we cannot perform a blanket implementation over
/// This struct wraps lazy structs that build [`VNode`] trees. Normally, we cannot perform a blanket implementation over
/// closures, but if we wrap the closure in a concrete type, we can use it for different branches in matching.
///
///
/// ```rust, ignore
/// LazyNodes::new(|f| f.element("div", [], [], [] None))
/// LazyNodes::new(|f| {
/// static TEMPLATE: dioxus::core::Template = dioxus::core::Template {
/// name: "main.rs:5:5:20", // Source location of the template for hot reloading
/// roots: &[
/// dioxus::core::TemplateNode::Element {
/// tag: dioxus_elements::div::TAG_NAME,
/// namespace: dioxus_elements::div::NAME_SPACE,
/// attrs: &[],
/// children: &[],
/// },
/// ],
/// node_paths: &[],
/// attr_paths: &[],
/// };
/// dioxus::core::VNode {
/// parent: None,
/// key: None,
/// template: std::cell::Cell::new(TEMPLATE),
/// root_ids: dioxus::core::exports::bumpalo::collections::Vec::with_capacity_in(
/// 1usize,
/// f.bump(),
/// )
/// .into(),
/// dynamic_nodes: f.bump().alloc([]),
/// dynamic_attrs: f.bump().alloc([]),
/// })
/// }
/// ```
///
/// Find more information about how to construct [`VNode`] at <https://dioxuslabs.com/learn/0.4/contributing/walkthrough_readme#the-rsx-macro>
pub struct LazyNodes<'a, 'b> {
#[cfg(not(miri))]
inner: SmallBox<dyn FnMut(&'a ScopeState) -> VNode<'a> + 'b, S16>,
@@ -61,7 +90,7 @@ impl<'a, 'b> LazyNodes<'a, 'b> {
/// Call the closure with the given factory to produce real [`VNode`].
///
/// ```rust, ignore
/// let f = LazyNodes::new(move |f| f.element("div", [], [], [] None));
/// let f = LazyNodes::new(/* Closure for creating VNodes */);
///
/// let node = f.call(cac);
/// ```
+14 -11
View File
@@ -1,4 +1,6 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
#![warn(missing_docs)]
mod any_props;
@@ -32,7 +34,7 @@ pub(crate) mod innerlude {
pub use crate::nodes::RenderReturn;
pub use crate::nodes::*;
pub use crate::properties::*;
pub use crate::runtime::{in_runtime, override_runtime, Runtime};
pub use crate::runtime::{Runtime, RuntimeGuard};
pub use crate::scheduler::*;
pub use crate::scope_context::*;
pub use crate::scopes::*;
@@ -74,11 +76,11 @@ pub(crate) mod innerlude {
}
pub use crate::innerlude::{
fc_to_builder, vdom_is_rendering, AnyValue, Attribute, AttributeValue, BorrowedAttributeValue,
CapturedError, Component, DynamicNode, Element, ElementId, Event, Fragment, IntoDynNode,
LazyNodes, Mutation, Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText,
VirtualDom,
fc_to_builder, vdom_is_rendering, AnyValue, Attribute, AttributeType, AttributeValue,
BorrowedAttributeValue, CapturedError, Component, DynamicNode, Element, ElementId, Event,
Fragment, HasAttributes, IntoDynNode, LazyNodes, MountedAttribute, Mutation, 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
@@ -87,11 +89,12 @@ pub use crate::innerlude::{
pub mod prelude {
pub use crate::innerlude::{
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context,
in_runtime, override_runtime, provide_context, provide_context_to_scope,
provide_root_context, push_future, remove_future, schedule_update_any, spawn,
spawn_forever, suspend, throw, AnyValue, Component, Element, Event, EventHandler, Fragment,
IntoAttributeValue, LazyNodes, Properties, Runtime, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
provide_context, provide_context_to_scope, provide_root_context, push_future,
remove_future, schedule_update_any, spawn, spawn_forever, suspend, use_error_boundary,
AnyValue, Attribute, AttributeType, Component, Element, ErrorBoundary, Event, EventHandler,
Fragment, HasAttributes, IntoAttributeValue, IntoDynNode, LazyNodes, MountedAttribute,
Properties, Runtime, RuntimeGuard, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
};
}
+2 -2
View File
@@ -26,7 +26,7 @@ pub struct Mutations<'a> {
/// Any templates encountered while diffing the DOM.
///
/// These must be loaded into a cache before applying the edits
pub templates: Vec<Template<'a>>,
pub templates: Vec<Template<'static>>,
/// Any mutations required to patch the renderer to match the layout of the VirtualDom
pub edits: Vec<Mutation<'a>>,
@@ -91,7 +91,7 @@ pub enum Mutation<'a> {
id: ElementId,
},
/// Create an placeholder int he DOM that we will use later.
/// Create a placeholder in the DOM that we will use later.
///
/// Dioxus currently requires the use of placeholders to maintain a re-entrance point for things like list diffing
CreatePlaceholder {
+157 -38
View File
@@ -1,3 +1,4 @@
use crate::innerlude::{ElementRef, VNodeId};
use crate::{
any_props::AnyProps, arena::ElementId, Element, Event, LazyNodes, ScopeId, ScopeState,
};
@@ -47,7 +48,10 @@ pub struct VNode<'a> {
pub key: Option<&'a str>,
/// When rendered, this template will be linked to its parent manually
pub parent: Option<ElementId>,
pub(crate) parent: Cell<Option<ElementRef>>,
/// The bubble id assigned to the child that we need to update and drop when diffing happens
pub(crate) stable_id: Cell<Option<VNodeId>>,
/// The static nodes and static descriptor of the template
pub template: Cell<Template<'static>>,
@@ -60,7 +64,7 @@ pub struct VNode<'a> {
pub dynamic_nodes: &'a [DynamicNode<'a>],
/// The dynamic parts of the template
pub dynamic_attrs: &'a [Attribute<'a>],
pub dynamic_attrs: &'a [MountedAttribute<'a>],
}
impl<'a> VNode<'a> {
@@ -68,7 +72,8 @@ impl<'a> VNode<'a> {
pub fn empty(cx: &'a ScopeState) -> Element<'a> {
Some(VNode {
key: None,
parent: None,
parent: Default::default(),
stable_id: Default::default(),
root_ids: RefCell::new(bumpalo::collections::Vec::new_in(cx.bump())),
dynamic_nodes: &[],
dynamic_attrs: &[],
@@ -81,6 +86,30 @@ impl<'a> VNode<'a> {
})
}
/// Create a new VNode
pub fn new(
key: Option<&'a str>,
template: Template<'static>,
root_ids: bumpalo::collections::Vec<'a, ElementId>,
dynamic_nodes: &'a [DynamicNode<'a>],
dynamic_attrs: &'a [MountedAttribute<'a>],
) -> Self {
Self {
key,
parent: Cell::new(None),
stable_id: Cell::new(None),
template: Cell::new(template),
root_ids: RefCell::new(root_ids),
dynamic_nodes,
dynamic_attrs,
}
}
/// Get the stable id of this node used for bubbling events
pub(crate) fn stable_id(&self) -> Option<VNodeId> {
self.stable_id.get()
}
/// Load a dynamic root at the given index
///
/// Returns [`None`] if the root is actually a static node (Element/Text)
@@ -319,7 +348,7 @@ pub struct VComponent<'a> {
/// The function pointer of the component, known at compile time
///
/// It is possible that components get folded at comppile time, so these shouldn't be really used as a key
/// It is possible that components get folded at compile time, so these shouldn't be really used as a key
pub(crate) render_fn: *const (),
pub(crate) props: RefCell<Option<Box<dyn AnyProps<'a> + 'a>>>,
@@ -372,6 +401,8 @@ impl<'a> VText<'a> {
pub struct VPlaceholder {
/// The ID of this node in the real DOM
pub(crate) id: Cell<Option<ElementId>>,
/// The parent of this node
pub(crate) parent: Cell<Option<ElementRef>>,
}
impl VPlaceholder {
@@ -414,6 +445,51 @@ pub enum TemplateAttribute<'a> {
},
}
/// An attribute with information about its position in the DOM and the element it was mounted to
#[derive(Debug)]
pub struct MountedAttribute<'a> {
pub(crate) ty: AttributeType<'a>,
/// The element in the DOM that this attribute belongs to
pub(crate) mounted_element: Cell<ElementId>,
}
impl<'a> From<Attribute<'a>> for MountedAttribute<'a> {
fn from(attr: Attribute<'a>) -> Self {
Self {
ty: AttributeType::Single(attr),
mounted_element: Default::default(),
}
}
}
impl<'a> From<&'a [Attribute<'a>]> for MountedAttribute<'a> {
fn from(attr: &'a [Attribute<'a>]) -> Self {
Self {
ty: AttributeType::Many(attr),
mounted_element: Default::default(),
}
}
}
impl<'a> From<&'a Vec<Attribute<'a>>> for MountedAttribute<'a> {
fn from(attr: &'a Vec<Attribute<'a>>) -> Self {
attr.as_slice().into()
}
}
impl<'a> MountedAttribute<'a> {
/// Get the type of this attribute
pub fn attribute_type(&self) -> &AttributeType<'a> {
&self.ty
}
/// Get the element that this attribute is mounted to
pub fn mounted_element(&self) -> ElementId {
self.mounted_element.get()
}
}
/// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"`
#[derive(Debug)]
pub struct Attribute<'a> {
@@ -430,9 +506,6 @@ pub struct Attribute<'a> {
/// An indication of we should always try and set the attribute. Used in controlled components to ensure changes are propagated
pub volatile: bool,
/// The element in the DOM that this attribute belongs to
pub(crate) mounted_element: Cell<ElementId>,
}
impl<'a> Attribute<'a> {
@@ -448,13 +521,40 @@ impl<'a> Attribute<'a> {
value,
namespace,
volatile,
mounted_element: Cell::new(ElementId::default()),
}
}
}
/// The type of an attribute
#[derive(Debug)]
pub enum AttributeType<'a> {
/// A single attribute
Single(Attribute<'a>),
/// Many different attributes sorted by name
Many(&'a [Attribute<'a>]),
}
impl<'a> AttributeType<'a> {
/// Call the given function on each attribute
pub fn for_each<'b, F>(&'b self, mut f: F)
where
F: FnMut(&'b Attribute<'a>),
{
match self {
Self::Single(attr) => f(attr),
Self::Many(attrs) => attrs.iter().for_each(f),
}
}
/// Get the element that this attribute is mounted to
pub fn mounted_element(&self) -> ElementId {
self.mounted_element.get()
/// Try to call the given function on each attribute
pub fn try_for_each<'b, F, E>(&'b self, mut f: F) -> Result<(), E>
where
F: FnMut(&'b Attribute<'a>) -> Result<(), E>,
{
match self {
Self::Single(attr) => f(attr),
Self::Many(attrs) => attrs.iter().try_for_each(f),
}
}
}
@@ -651,52 +751,52 @@ pub trait IntoDynNode<'a, A = ()> {
/// Consume this item along with a scopestate and produce a DynamicNode
///
/// You can use the bump alloactor of the scopestate to creat the dynamic node
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a>;
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a>;
}
impl<'a> IntoDynNode<'a> for () {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::default()
}
}
impl<'a> IntoDynNode<'a> for VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(_cx.bump().alloc([self]))
}
}
impl<'a> IntoDynNode<'a> for DynamicNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
self
}
}
impl<'a, T: IntoDynNode<'a>> IntoDynNode<'a> for Option<T> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
match self {
Some(val) => val.into_vnode(_cx),
Some(val) => val.into_dyn_node(_cx),
None => DynamicNode::default(),
}
}
}
impl<'a> IntoDynNode<'a> for &Element<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
match self.as_ref() {
Some(val) => val.clone().into_vnode(_cx),
Some(val) => val.clone().into_dyn_node(_cx),
_ => DynamicNode::default(),
}
}
}
impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(cx.bump().alloc([cx.render(self).unwrap()]))
}
}
impl<'a, 'b> IntoDynNode<'b> for &'a str {
fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
fn into_dyn_node(self, cx: &'b ScopeState) -> DynamicNode<'b> {
DynamicNode::Text(VText {
value: cx.bump().alloc_str(self),
id: Default::default(),
@@ -705,24 +805,25 @@ impl<'a, 'b> IntoDynNode<'b> for &'a str {
}
impl IntoDynNode<'_> for String {
fn into_vnode(self, cx: &ScopeState) -> DynamicNode {
fn into_dyn_node(self, cx: &ScopeState) -> DynamicNode {
DynamicNode::Text(VText {
value: cx.bump().alloc(self),
value: cx.bump().alloc_str(&self),
id: Default::default(),
})
}
}
impl<'b> IntoDynNode<'b> for Arguments<'_> {
fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
fn into_dyn_node(self, cx: &'b ScopeState) -> DynamicNode<'b> {
cx.text_node(self)
}
}
impl<'a> IntoDynNode<'a> for &'a VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(_cx.bump().alloc([VNode {
parent: self.parent,
parent: self.parent.clone(),
stable_id: self.stable_id.clone(),
template: self.template.clone(),
root_ids: self.root_ids.clone(),
key: self.key,
@@ -732,24 +833,24 @@ impl<'a> IntoDynNode<'a> for &'a VNode<'a> {
}
}
pub trait IntoTemplate<'a> {
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a>;
pub trait IntoVNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> VNode<'a>;
}
impl<'a> IntoTemplate<'a> for VNode<'a> {
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
impl<'a> IntoVNode<'a> for VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> VNode<'a> {
self
}
}
impl<'a> IntoTemplate<'a> for Element<'a> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
impl<'a> IntoVNode<'a> for Element<'a> {
fn into_vnode(self, cx: &'a ScopeState) -> VNode<'a> {
match self {
Some(val) => val.into_template(cx),
Some(val) => val.into_vnode(cx),
_ => VNode::empty(cx).unwrap(),
}
}
}
impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> VNode<'a> {
cx.render(self).unwrap()
}
}
@@ -759,12 +860,12 @@ pub struct FromNodeIterator;
impl<'a, T, I> IntoDynNode<'a, FromNodeIterator> for T
where
T: Iterator<Item = I>,
I: IntoTemplate<'a>,
I: IntoVNode<'a>,
{
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a> {
let mut nodes = bumpalo::collections::Vec::new_in(cx.bump());
nodes.extend(self.into_iter().map(|node| node.into_template(cx)));
nodes.extend(self.into_iter().map(|node| node.into_vnode(cx)));
match nodes.into_bump_slice() {
children if children.is_empty() => DynamicNode::default(),
@@ -791,6 +892,12 @@ impl<'a> IntoAttributeValue<'a> for &'a str {
}
}
impl<'a> IntoAttributeValue<'a> for String {
fn into_value(self, cx: &'a Bump) -> AttributeValue<'a> {
AttributeValue::Text(cx.alloc_str(&self))
}
}
impl<'a> IntoAttributeValue<'a> for f64 {
fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
AttributeValue::Float(self)
@@ -832,3 +939,15 @@ impl<'a, T: IntoAttributeValue<'a>> IntoAttributeValue<'a> for Option<T> {
}
}
}
/// A trait for anything that has a dynamic list of attributes
pub trait HasAttributes<'a> {
/// Push an attribute onto the list of attributes
fn push_attribute(
self,
name: &'a str,
ns: Option<&'static str>,
attr: impl IntoAttributeValue<'a>,
volatile: bool,
) -> Self;
}
+9 -6
View File
@@ -32,7 +32,7 @@ use crate::innerlude::*;
/// data: &'a str
/// }
/// ```
pub trait Properties: Sized {
pub trait Properties<'a>: Sized {
/// The type of the builder for this component.
/// Used to create "in-progress" versions of the props.
type Builder;
@@ -41,7 +41,7 @@ pub trait Properties: Sized {
const IS_STATIC: bool;
/// Create a builder for this component.
fn builder() -> Self::Builder;
fn builder(cx: &'a ScopeState) -> Self::Builder;
/// Memoization can only happen if the props are valid for the 'static lifetime
///
@@ -51,10 +51,10 @@ pub trait Properties: Sized {
unsafe fn memoize(&self, other: &Self) -> bool;
}
impl Properties for () {
impl Properties<'_> for () {
type Builder = EmptyBuilder;
const IS_STATIC: bool = true;
fn builder() -> Self::Builder {
fn builder(_cx: &ScopeState) -> Self::Builder {
EmptyBuilder {}
}
unsafe fn memoize(&self, _other: &Self) -> bool {
@@ -70,8 +70,11 @@ 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, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>) -> T::Builder {
T::builder()
pub fn fc_to_builder<'a, T: Properties<'a> + 'a>(
cx: &'a ScopeState,
_: fn(Scope<'a, T>) -> Element<'a>,
) -> T::Builder {
T::builder(cx)
}
#[cfg(not(miri))]
+55 -47
View File
@@ -7,51 +7,6 @@ thread_local! {
static RUNTIMES: RefCell<Vec<Rc<Runtime>>> = RefCell::new(vec![]);
}
/// Run some code within a runtime
pub fn in_runtime<R>(runtime: Rc<Runtime>, f: impl FnOnce() -> R) -> R {
let _guard = RuntimeGuard::new(runtime);
f()
}
/// Override the current runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn main() {
/// let virtual_dom = VirtualDom::new(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!{ Component { runtime: Runtime::current().unwrap() } }
/// }
///
/// // In a dynamic library
/// #[derive(Props)]
/// struct ComponentProps {
/// runtime: std::rc::Rc<Runtime>,
/// }
///
/// impl PartialEq for ComponentProps {
/// fn eq(&self, _other: &Self) -> bool {
/// true
/// }
/// }
///
/// fn Component(cx: Scope<ComponentProps>) -> Element {
/// cx.use_hook(|| override_runtime(cx.props.runtime.clone()));
///
/// render! { div {} }
/// }
/// ```
pub fn override_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| {
let mut stack = stack.borrow_mut();
stack.pop();
stack.push(runtime);
});
}
/// Pushes a new scope onto the stack
pub(crate) fn push_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| stack.borrow_mut().push(runtime));
@@ -132,6 +87,16 @@ impl Runtime {
self.scope_stack.borrow().last().copied()
}
/// Call this function with the current scope set to the given scope
///
/// Useful in a limited number of scenarios, not public.
pub(crate) fn with_scope<O>(&self, id: ScopeId, f: impl FnOnce() -> O) -> O {
self.scope_stack.borrow_mut().push(id);
let o = f();
self.scope_stack.borrow_mut().pop();
o
}
/// Get the context for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
@@ -143,13 +108,56 @@ impl Runtime {
}
}
pub(crate) struct RuntimeGuard(Rc<Runtime>);
/// A guard for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn main() {
/// let virtual_dom = VirtualDom::new(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!{ Component { runtime: Runtime::current().unwrap() } }
/// }
///
/// // In a dynamic library
/// #[derive(Props)]
/// struct ComponentProps {
/// runtime: std::rc::Rc<Runtime>,
/// }
///
/// impl PartialEq for ComponentProps {
/// fn eq(&self, _other: &Self) -> bool {
/// true
/// }
/// }
///
/// fn Component(cx: Scope<ComponentProps>) -> Element {
/// cx.use_hook(|| RuntimeGuard::new(cx.props.runtime.clone()));
///
/// render! { div {} }
/// }
/// ```
pub struct RuntimeGuard(Rc<Runtime>);
impl RuntimeGuard {
pub(crate) fn new(runtime: Rc<Runtime>) -> Self {
/// Create a new runtime guard that sets the current Dioxus runtime. The runtime will be reset when the guard is dropped
pub fn new(runtime: Rc<Runtime>) -> Self {
push_runtime(runtime.clone());
Self(runtime)
}
/// Run a function with a given runtime and scope in context
pub fn with<O>(runtime: Rc<Runtime>, scope: Option<ScopeId>, f: impl FnOnce() -> O) -> O {
let guard = Self::new(runtime.clone());
let o = match scope {
Some(scope) => Runtime::with_scope(&runtime, scope, f),
None => f(),
};
drop(guard);
o
}
}
impl Drop for RuntimeGuard {
+11 -7
View File
@@ -19,7 +19,7 @@ pub struct TaskId(pub usize);
/// the task itself is the waker
pub(crate) struct LocalTask {
pub scope: ScopeId,
pub(super) task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>,
pub task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>,
pub waker: Waker,
}
@@ -48,11 +48,15 @@ impl Scheduler {
})),
};
entry.insert(task);
let mut cx = std::task::Context::from_waker(&task.waker);
self.sender
.unbounded_send(SchedulerMsg::TaskNotified(task_id))
.expect("Scheduler should exist");
if !task.task.borrow_mut().as_mut().poll(&mut cx).is_ready() {
self.sender
.unbounded_send(SchedulerMsg::TaskNotified(task_id))
.expect("Scheduler should exist");
}
entry.insert(task);
task_id
}
@@ -60,8 +64,8 @@ impl Scheduler {
/// Drop the future with the given TaskId
///
/// This does not abort the task, so you'll want to wrap it in an aborthandle if that's important to you
pub fn remove(&self, id: TaskId) {
self.tasks.borrow_mut().try_remove(id.0);
pub fn remove(&self, id: TaskId) -> Option<LocalTask> {
self.tasks.borrow_mut().try_remove(id.0)
}
}
+3 -2
View File
@@ -35,7 +35,8 @@ impl VirtualDom {
hook_idx: Default::default(),
borrowed_props: Default::default(),
attributes_to_drop: Default::default(),
attributes_to_drop_before_render: Default::default(),
element_refs_to_drop: Default::default(),
}));
let context =
@@ -54,7 +55,7 @@ impl VirtualDom {
let new_nodes = unsafe {
let scope = &self.scopes[scope_id.0];
scope.previous_frame().bump_mut().reset();
scope.previous_frame().reset();
scope.context().suspended.set(false);
+8 -32
View File
@@ -1,5 +1,5 @@
use crate::{
innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
innerlude::{Scheduler, SchedulerMsg},
runtime::{with_current_scope, with_runtime},
Element, ScopeId, TaskId,
};
@@ -7,7 +7,6 @@ use rustc_hash::FxHashSet;
use std::{
any::Any,
cell::{Cell, RefCell},
fmt::Debug,
future::Future,
rc::Rc,
sync::Arc,
@@ -230,17 +229,7 @@ impl ScopeContext {
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
// The root scope will never be unmounted so we can just add the task at the top of the app
let id = self.tasks.spawn(ScopeId::ROOT, fut);
// wake up the scheduler if it is sleeping
self.tasks
.sender
.unbounded_send(SchedulerMsg::TaskNotified(id))
.expect("Scheduler should exist");
self.spawned_tasks.borrow_mut().insert(id);
id
self.tasks.spawn(ScopeId::ROOT, fut)
}
/// Informs the scheduler that this task is no longer needed and should be removed.
@@ -250,19 +239,6 @@ impl ScopeContext {
self.tasks.remove(id);
}
/// Inject an error into the nearest error boundary and quit rendering
///
/// The error doesn't need to implement Error or any specific traits since the boundary
/// itself will downcast the error into a trait object.
pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
cx.insert_error(self.scope_id(), Box::new(error));
}
// Always return none during a throw
None
}
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
self.suspended.set(true);
@@ -332,11 +308,6 @@ pub fn suspend() -> Option<Element<'static>> {
None
}
/// Throw an error into the nearest error boundary
pub fn throw(error: impl Debug + 'static) -> Option<()> {
with_current_scope(|cx| cx.throw(error)).flatten()
}
/// Pushes the future onto the poll queue to be polled after the component renders.
pub fn push_future(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.push_future(fut))
@@ -347,11 +318,16 @@ pub fn spawn(fut: impl Future<Output = ()> + 'static) {
with_current_scope(|cx| cx.spawn(fut));
}
/// Spawn a future on a component given its [`ScopeId`].
pub fn spawn_at(fut: impl Future<Output = ()> + 'static, scope_id: ScopeId) -> Option<TaskId> {
with_runtime(|rt| rt.get_context(scope_id).unwrap().push_future(fut))
}
/// Spawn a future that Dioxus won't clean up when this component is unmounted
///
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.spawn_forever(fut))
spawn_at(fut, ScopeId(0))
}
/// Informs the scheduler that this task is no longer needed and should be removed.
+38 -35
View File
@@ -2,13 +2,13 @@ use crate::{
any_props::AnyProps,
any_props::VProps,
bump_frame::BumpFrame,
innerlude::ErrorBoundary,
innerlude::{DynamicNode, EventHandler, VComponent, VText},
innerlude::{DynamicNode, EventHandler, VComponent, VNodeId, VText},
lazynodes::LazyNodes,
nodes::{IntoAttributeValue, IntoDynNode, RenderReturn},
runtime::Runtime,
scope_context::ScopeContext,
AnyValue, Attribute, AttributeValue, Element, Event, Properties, TaskId,
AnyValue, Attribute, AttributeType, AttributeValue, Element, Event, MountedAttribute,
Properties, TaskId,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use std::{
@@ -94,7 +94,8 @@ pub struct ScopeState {
pub(crate) hook_idx: Cell<usize>,
pub(crate) borrowed_props: RefCell<Vec<*const VComponent<'static>>>,
pub(crate) attributes_to_drop: RefCell<Vec<*const Attribute<'static>>>,
pub(crate) element_refs_to_drop: RefCell<Vec<VNodeId>>,
pub(crate) attributes_to_drop_before_render: RefCell<Vec<*const Attribute<'static>>>,
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
}
@@ -348,25 +349,38 @@ impl<'src> ScopeState {
pub fn render(&'src self, rsx: LazyNodes<'src, '_>) -> Element<'src> {
let element = rsx.call(self);
let mut listeners = self.attributes_to_drop.borrow_mut();
let mut listeners = self.attributes_to_drop_before_render.borrow_mut();
for attr in element.dynamic_attrs {
match attr.value {
AttributeValue::Any(_) | AttributeValue::Listener(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
listeners.push(unbounded);
}
attr.ty.for_each(|attr| {
match attr.value {
// We need to drop listeners before the next render because they may borrow data from the borrowed props which will be dropped
AttributeValue::Listener(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
listeners.push(unbounded);
}
// We need to drop any values manually to make sure that their drop implementation is called before the next render
AttributeValue::Any(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
self.previous_frame().add_attribute_to_drop(unbounded);
}
_ => (),
}
_ => (),
}
})
}
let mut props = self.borrowed_props.borrow_mut();
let mut drop_props = self
.previous_frame()
.props_to_drop_before_reset
.borrow_mut();
for node in element.dynamic_nodes {
if let DynamicNode::Component(comp) = node {
let unbounded = unsafe { std::mem::transmute(comp as *const VComponent) };
if !comp.static_props {
let unbounded = unsafe { std::mem::transmute(comp as *const VComponent) };
props.push(unbounded);
}
drop_props.push(unbounded);
}
}
@@ -395,7 +409,7 @@ impl<'src> ScopeState {
/// Convert any item that implements [`IntoDynNode`] into a [`DynamicNode`] using the internal [`Bump`] allocator
pub fn make_node<'c, I>(&'src self, into: impl IntoDynNode<'src, I> + 'c) -> DynamicNode {
into.into_vnode(self)
into.into_dyn_node(self)
}
/// Create a new [`Attribute`] from a name, value, namespace, and volatile bool
@@ -408,13 +422,15 @@ impl<'src> ScopeState {
value: impl IntoAttributeValue<'src>,
namespace: Option<&'static str>,
volatile: bool,
) -> Attribute<'src> {
Attribute {
name,
namespace,
volatile,
) -> MountedAttribute<'src> {
MountedAttribute {
ty: AttributeType::Single(Attribute {
name,
namespace,
volatile,
value: value.into_value(self.bump()),
}),
mounted_element: Default::default(),
value: value.into_value(self.bump()),
}
}
@@ -440,7 +456,7 @@ impl<'src> ScopeState {
) -> DynamicNode<'src>
where
// The properties must be valid until the next bump frame
P: Properties + 'src,
P: Properties<'src> + 'src,
// The current bump allocator frame must outlive the child's borrowed props
'src: 'child,
{
@@ -455,7 +471,7 @@ impl<'src> ScopeState {
render_fn: component as *const (),
static_props: P::IS_STATIC,
props: RefCell::new(Some(extended)),
scope: Cell::new(None),
scope: Default::default(),
})
}
@@ -506,19 +522,6 @@ impl<'src> ScopeState {
AttributeValue::Any(RefCell::new(Some(boxed)))
}
/// Inject an error into the nearest error boundary and quit rendering
///
/// The error doesn't need to implement Error or any specific traits since the boundary
/// itself will downcast the error into a trait object.
pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
cx.insert_error(self.scope_id(), Box::new(error));
}
// Always return none during a throw
None
}
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
let cx = self.context();
+98 -74
View File
@@ -11,12 +11,14 @@ use crate::{
nodes::{Template, TemplateId},
runtime::{Runtime, RuntimeGuard},
scopes::{ScopeId, ScopeState},
AttributeValue, Element, Event, Scope,
AttributeValue, Element, Event, Scope, VNode,
};
use futures_util::{pin_mut, StreamExt};
use rustc_hash::{FxHashMap, FxHashSet};
use slab::Slab;
use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
use std::{
any::Any, cell::Cell, collections::BTreeSet, future::Future, ptr::NonNull, rc::Rc, sync::Arc,
};
/// A virtual node system that progresses user events and diffs UI trees.
///
@@ -186,7 +188,10 @@ pub struct VirtualDom {
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
// Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
pub(crate) elements: Slab<ElementRef>,
pub(crate) element_refs: Slab<Option<NonNull<VNode<'static>>>>,
// The element ids that are used in the renderer
pub(crate) elements: Slab<Option<ElementRef>>,
pub(crate) mutations: Mutations<'static>,
@@ -263,6 +268,7 @@ impl VirtualDom {
dirty_scopes: Default::default(),
templates: Default::default(),
elements: Default::default(),
element_refs: Default::default(),
mutations: Mutations::default(),
suspended_scopes: Default::default(),
};
@@ -273,10 +279,13 @@ impl VirtualDom {
);
// Unlike react, we provide a default error boundary that just renders the error as a string
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId::ROOT)));
root.provide_context(Rc::new(ErrorBoundary::new_in_scope(
ScopeId::ROOT,
Arc::new(|_| {}),
)));
// the root element is always given element ID 0 since it's the container for the entire tree
dom.elements.insert(ElementRef::none());
dom.elements.insert(None);
dom
}
@@ -314,9 +323,9 @@ impl VirtualDom {
}
}
/// Call a listener inside the VirtualDom with data from outside the VirtualDom.
/// Call a listener inside the VirtualDom with data from outside the VirtualDom. **The ElementId passed in must be the id of an dynamic element, not a static node or a text node.**
///
/// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
/// This method will identify the appropriate element. The data must match up with the listener declared. Note that
/// this method does not give any indication as to the success of the listener call. If the listener is not found,
/// nothing will happen.
///
@@ -353,8 +362,15 @@ impl VirtualDom {
| | | <-- no, broke early
| <-- no, broke early
*/
let mut parent_path = self.elements.get(element.0);
let mut listeners = vec![];
let parent_path = match self.elements.get(element.0) {
Some(Some(el)) => el,
_ => return,
};
let mut parent_node = self
.element_refs
.get(parent_path.template.0)
.cloned()
.map(|el| (*parent_path, el));
// We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
let uievent = Event {
@@ -365,82 +381,93 @@ impl VirtualDom {
// If the event bubbles, we traverse through the tree until we find the target element.
if bubbles {
// Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
while let Some(el_ref) = parent_path {
while let Some((path, el_ref)) = parent_node {
let mut listeners = vec![];
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
let template = unsafe { el_ref.unwrap().as_ref() };
let node_template = template.template.get();
let target_path = path.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
if attr.name.trim_start_matches("on") == name
&& target_path.is_decendant(&this_path)
{
listeners.push(&attr.value);
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == this_path {
break;
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
if target_path.is_decendant(&this_path) {
attr.ty.for_each(|attribute| {
if attribute.name.trim_start_matches("on") == name {
if let AttributeValue::Listener(listener) = &attribute.value {
listeners.push(listener);
}
}
});
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == this_path {
break;
}
}
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.drain(..).rev() {
if let AttributeValue::Listener(listener) = listener {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
if !uievent.propagates.get() {
return;
}
}
}
parent_path = template.parent.and_then(|id| self.elements.get(id.0));
} else {
break;
}
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.into_iter().rev() {
let origin = path.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
if !uievent.propagates.get() {
return;
}
}
parent_node = template.parent.get().and_then(|element_ref| {
self.element_refs
.get(element_ref.template.0)
.cloned()
.map(|el| (element_ref, el))
});
}
} else {
// Otherwise, we just call the listener on the target element
if let Some(el_ref) = parent_path {
if let Some((path, el_ref)) = parent_node {
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
let template = unsafe { el_ref.unwrap().as_ref() };
let node_template = template.template.get();
let target_path = path.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
// Only call the listener if this is the exact target element.
if attr.name.trim_start_matches("on") == name && target_path == this_path {
if let AttributeValue::Listener(listener) = &attr.value {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
// Only call the listener if this is the exact target element.
if target_path == this_path {
let mut should_stop = false;
attr.ty.for_each(|attribute| {
if attribute.name.trim_start_matches("on") == name {
if let AttributeValue::Listener(listener) = &attribute.value {
let origin = path.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
should_stop = true;
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
break;
}
});
if should_stop {
return;
}
}
}
@@ -563,7 +590,7 @@ impl VirtualDom {
// If an error occurs, we should try to render the default error component and context where the error occured
RenderReturn::Aborted(placeholder) => {
tracing::debug!("Ran into suspended or aborted scope during rebuild");
let id = self.next_null();
let id = self.next_element();
placeholder.id.set(Some(id));
self.mutations.push(Mutation::CreatePlaceholder { id });
}
@@ -595,15 +622,12 @@ impl VirtualDom {
/// 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();
}
}
+2 -2
View File
@@ -24,9 +24,9 @@ fn NoneChild(_cx: Scope) -> Element {
}
fn ThrowChild(cx: Scope) -> Element {
cx.throw(std::io::Error::new(std::io::ErrorKind::AddrInUse, "asd"))?;
Err(std::io::Error::new(std::io::ErrorKind::AddrInUse, "asd")).throw()?;
let _g: i32 = "123123".parse().throw(cx)?;
let _g: i32 = "123123".parse().throw()?;
cx.render(rsx! {
div {}
+82
View File
@@ -0,0 +1,82 @@
use dioxus::prelude::*;
use dioxus_core::ElementId;
use std::{rc::Rc, sync::Mutex};
static CLICKS: Mutex<usize> = Mutex::new(0);
#[test]
fn events_propagate() {
set_event_converter(Box::new(dioxus_html::SerializedHtmlEventConverter));
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
// Top-level click is registered
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(1),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 1);
// break reference....
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
_ = dom.render_immediate();
}
// Lower click is registered
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 3);
// break reference....
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
_ = dom.render_immediate();
}
// Stop propagation occurs
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 3);
}
fn app(cx: Scope) -> Element {
render! {
div { onclick: move |_| {
println!("top clicked");
*CLICKS.lock().unwrap() += 1;
},
vec![
render! {
problematic_child {}
}
].into_iter()
}
}
}
fn problematic_child(cx: Scope) -> Element {
render! {
button { onclick: move |evt| {
println!("bottom clicked");
let mut clicks = CLICKS.lock().unwrap();
if *clicks == 3 {
evt.stop_propagation();
} else {
*clicks += 1;
}
} }
}
}
+33 -33
View File
@@ -1,8 +1,8 @@
#![cfg(not(miri))]
use dioxus::prelude::Props;
use dioxus_core::*;
use std::{cell::Cell, collections::HashSet};
use dioxus_core::{MountedAttribute, *};
use std::{cfg, collections::HashSet};
fn random_ns() -> Option<&'static str> {
let namespace = rand::random::<u8>() % 2;
@@ -170,22 +170,23 @@ fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
let range = if depth > 5 { 1 } else { 4 };
match rand::random::<u8>() % range {
0 => DynamicNode::Placeholder(Default::default()),
1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| VNode {
key: None,
parent: Default::default(),
template: Cell::new(Template {
name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
roots: &[TemplateNode::Dynamic { id: 0 }],
node_paths: &[&[0]],
attr_paths: &[],
}),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
)]),
dynamic_attrs: &[],
1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| {
VNode::new(
None,
Template {
name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
roots: &[TemplateNode::Dynamic { id: 0 }],
node_paths: &[&[0]],
attr_paths: &[],
},
bumpalo::collections::Vec::new_in(cx.bump()),
cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
)]),
&[],
)
})),
2 => cx.component(
create_random_element,
@@ -205,7 +206,7 @@ fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
}
}
fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
fn create_random_dynamic_attr(cx: &ScopeState) -> MountedAttribute {
let value = match rand::random::<u8>() % 7 {
0 => AttributeValue::Text(Box::leak(
format!("{}", rand::random::<usize>()).into_boxed_str(),
@@ -217,7 +218,7 @@ fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
5 => AttributeValue::None,
6 => {
let value = cx.listener(|e: Event<String>| println!("{:?}", e));
return Attribute::new("ondata", value, None, false);
return Attribute::new("ondata", value, None, false).into();
}
_ => unreachable!(),
};
@@ -227,6 +228,7 @@ fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
random_ns(),
rand::random(),
)
.into()
}
static mut TEMPLATE_COUNT: usize = 0;
@@ -271,13 +273,11 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
)
.into_boxed_str(),
));
// println!("{template:#?}");
let node = VNode {
key: None,
parent: None,
template: Cell::new(template),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: {
let node = VNode::new(
None,
template,
bumpalo::collections::Vec::new_in(cx.bump()),
{
let dynamic_nodes: Vec<_> = dynamic_node_types
.iter()
.map(|ty| match ty {
@@ -291,12 +291,12 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
.collect();
cx.bump().alloc(dynamic_nodes)
},
dynamic_attrs: cx.bump().alloc(
cx.bump().alloc(
(0..template.attr_paths.len())
.map(|_| create_random_dynamic_attr(cx))
.collect::<Vec<_>>(),
),
};
);
Some(node)
}
_ => None,
@@ -306,10 +306,10 @@ 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 {
let repeat_count = if cfg!(miri) { 100 } else { 1000 };
for _ in 0..repeat_count {
let mut vdom =
VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
let _ = vdom.rebuild();
@@ -318,10 +318,10 @@ 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 {
let repeat_count = if cfg!(miri) { 100 } else { 1000 };
for _ in 0..repeat_count {
let mut vdom =
VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
let _ = vdom.rebuild();
+4 -1
View File
@@ -10,6 +10,8 @@ fn basic_syntax_is_a_template(cx: Scope) -> Element {
div { key: "12345",
class: "asd",
class: "{asd}",
class: if true { "{asd}" },
class: if false { "{asd}" },
onclick: move |_| {},
div { "{var}" }
div {
@@ -24,6 +26,7 @@ fn basic_syntax_is_a_template(cx: Scope) -> Element {
}
})
}
#[test]
fn dual_stream() {
let mut dom = VirtualDom::new(basic_syntax_is_a_template);
@@ -36,7 +39,7 @@ fn dual_stream() {
LoadTemplate { name: "template", index: 0, id: ElementId(1) },
SetAttribute {
name: "class",
value: (&*bump.alloc("123".into_value(&bump))).into(),
value: (&*bump.alloc("asd 123 123".into_value(&bump))).into(),
id: ElementId(1),
ns: None,
},
+8 -1
View File
@@ -4,6 +4,7 @@
//! Tests for the lifecycle of components.
use dioxus::core::{ElementId, Mutation::*};
use dioxus::prelude::*;
use dioxus_html::SerializedHtmlEventConverter;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
@@ -39,6 +40,7 @@ fn manual_diffing() {
#[test]
fn events_generate() {
set_event_converter(Box::new(SerializedHtmlEventConverter));
fn app(cx: Scope) -> Element {
let count = cx.use_hook(|| 0);
@@ -56,7 +58,12 @@ fn events_generate() {
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(1), true);
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(1),
true,
);
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate();
+9 -1
View File
@@ -1,15 +1,23 @@
use crate::dioxus_elements::SerializedMouseData;
use dioxus::prelude::*;
use dioxus_core::ElementId;
use dioxus_elements::SerializedHtmlEventConverter;
use std::rc::Rc;
#[test]
fn miri_rollover() {
set_event_converter(Box::new(SerializedHtmlEventConverter));
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
for _ in 0..3 {
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(2), true);
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
dom.process_events();
_ = dom.render_immediate();
}
+2 -2
View File
@@ -11,7 +11,7 @@ fn it_works() {
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
dom.wait_for_suspense().await;
let out = dioxus_ssr::pre_render(&dom);
let out = dioxus_ssr::render(&dom);
assert_eq!(out, "<div>Waiting for... child</div>");
@@ -36,7 +36,7 @@ fn suspended_child(cx: Scope) -> Element {
cx.spawn(async move {
val += 1;
});
return cx.suspend()?;
cx.suspend()?;
}
render!("child")
+25 -25
View File
@@ -1,13 +1,33 @@
//! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
use dioxus::prelude::*;
use std::{sync::atomic::AtomicUsize, time::Duration};
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
#[cfg(not(miri))]
#[tokio::test]
async fn it_works() {
use dioxus::prelude::*;
use std::{sync::atomic::AtomicUsize, time::Duration};
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
fn app(cx: Scope) -> Element {
cx.use_hook(|| {
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(50)).await;
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;
POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
}
});
});
cx.render(rsx!(()))
}
let mut dom = VirtualDom::new(app);
let _ = dom.rebuild();
@@ -24,23 +44,3 @@ async fn it_works() {
135
);
}
fn app(cx: Scope) -> Element {
cx.use_hook(|| {
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(50)).await;
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;
POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
}
});
});
cx.render(rsx!(()))
}
+1
View File
@@ -0,0 +1 @@
/src/minified.js
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff. Show more