Merge branch 'DioxusLabs:master' into fix-native-core-leak
This commit is contained in:
575 files changed
+6474
-20474
No files matched your search
@@ -1,6 +1,5 @@
|
||||
# dioxus-autofmt
|
||||
|
||||
|
||||
[![Crates.io][crates-badge]][crates-url]
|
||||
[![MIT licensed][mit-badge]][mit-url]
|
||||
[![Build Status][actions-badge]][actions-url]
|
||||
@@ -8,38 +7,33 @@
|
||||
|
||||
[crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg
|
||||
[crates-url]: https://crates.io/crates/dioxus-autofmt
|
||||
|
||||
[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
|
||||
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
|
||||
|
||||
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
|
||||
[discord-url]: https://discord.gg/XgGxMSkvUM
|
||||
|
||||
[Website](https://dioxuslabs.com) |
|
||||
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
|
||||
[Guides](https://dioxuslabs.com/learn/0.4/) |
|
||||
[API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) |
|
||||
[Chat](https://discord.gg/XgGxMSkvUM)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
`dioxus-autofmt` provides a pretty printer for the `rsx` syntax tree.
|
||||
|
||||
|
||||
This is done manually with a via set of formatting rules. The output is not guaranteed to be stable between minor versions of the crate as we might tweak the output.
|
||||
|
||||
`dioxus-autofmt` provides an API to perform precision edits as well as just spit out a block of formatted RSX from any RSX syntax tree. This is used by the `rsx-rosetta` crate which can accept various input languages and output valid RSX.
|
||||
|
||||
|
||||
## Contributing
|
||||
|
||||
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
|
||||
- Join the discord and ask questions!
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT license].
|
||||
|
||||
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -17,7 +17,15 @@ struct MacroCollector<'a, 'b> {
|
||||
|
||||
impl<'a, 'b> Visit<'b> for MacroCollector<'a, 'b> {
|
||||
fn visit_macro(&mut self, i: &'b Macro) {
|
||||
self.macros.push(i);
|
||||
if let Some("rsx" | "render") = i
|
||||
.path
|
||||
.segments
|
||||
.last()
|
||||
.map(|i| i.ident.to_string())
|
||||
.as_deref()
|
||||
{
|
||||
self.macros.push(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,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 +86,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;
|
||||
@@ -185,11 +185,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.out.indent -= 1;
|
||||
self.out.indent_level -= 1;
|
||||
|
||||
if !sameline {
|
||||
self.out.indented_tabbed_line()?;
|
||||
@@ -398,14 +398,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, " ")?
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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()
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[inline_props]
|
||||
#[component]
|
||||
pub fn Explainer<'a>(
|
||||
cx: Scope<'a>,
|
||||
invert: bool,
|
||||
|
||||
@@ -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)));
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,7 @@
|
||||
rsx! {
|
||||
div {
|
||||
// Comments
|
||||
class: "asdasd",
|
||||
"hello world"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
rsx! {
|
||||
div {
|
||||
// Comments
|
||||
class: "asdasd", "hello world" }
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -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" }
|
||||
})
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -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 }
|
||||
})
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -1,32 +1,27 @@
|
||||
# dioxus-check
|
||||
|
||||
|
||||
[![Crates.io][crates-badge]][crates-url]
|
||||
[![MIT licensed][mit-badge]][mit-url]
|
||||
[![Build Status][actions-badge]][actions-url]
|
||||
[![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
|
||||
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
|
||||
|
||||
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
|
||||
[discord-url]: https://discord.gg/XgGxMSkvUM
|
||||
|
||||
[Website](https://dioxuslabs.com) |
|
||||
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
|
||||
[API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) |
|
||||
[Guides](https://dioxuslabs.com/learn/0.4/) |
|
||||
[API Docs](https://docs.rs/dioxus-check) |
|
||||
[Chat](https://discord.gg/XgGxMSkvUM)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals).
|
||||
`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/learn/0.4/reference/hooks#rules-of-hooks).
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -34,6 +29,7 @@
|
||||
- Join the discord and ask questions!
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT license].
|
||||
|
||||
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
|
||||
|
||||
@@ -158,11 +158,11 @@ impl Display for IssueReport {
|
||||
#[allow(clippy::enum_variant_names)] // we'll add non-hook ones in the future
|
||||
/// Issues that might be found via static analysis of a Dioxus file.
|
||||
pub enum Issue {
|
||||
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals
|
||||
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-conditionals
|
||||
HookInsideConditional(HookInfo, ConditionalInfo),
|
||||
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-loops
|
||||
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-loops
|
||||
HookInsideLoop(HookInfo, AnyLoopInfo),
|
||||
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-closures
|
||||
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-closures
|
||||
HookInsideClosure(HookInfo, ClosureInfo),
|
||||
HookOutsideComponent(HookInfo),
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
on: [push, pull_request]
|
||||
|
||||
name: Rust CI
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
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
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: check
|
||||
|
||||
test:
|
||||
name: Test Suite
|
||||
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
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
|
||||
fmt:
|
||||
name: Rustfmt
|
||||
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 rustfmt
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --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
|
||||
Generated
-4778
File diff suppressed because it is too large.
Load diff
+12
-12
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "dioxus-cli"
|
||||
version = { workspace = true }
|
||||
version = "0.4.3"
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2021"
|
||||
description = "CLI tool for developing, testing, and publishing Dioxus apps"
|
||||
@@ -22,21 +22,18 @@ 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"
|
||||
hyper = "0.14.17"
|
||||
hyper-rustls = "0.23.2"
|
||||
indicatif = "0.17.0-rc.11"
|
||||
indicatif = "0.17.5"
|
||||
subprocess = "0.2.9"
|
||||
|
||||
axum = { version = "0.5.1", features = ["ws", "headers"] }
|
||||
@@ -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,15 +67,13 @@ 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"
|
||||
# dioxus-rsx = "0.0.1"
|
||||
|
||||
# bundling
|
||||
tauri-bundler = { version = "1.2", features = ["native-tls-vendored"] }
|
||||
tauri-utils = "1.3"
|
||||
tauri-bundler = { version = "=1.3.0", features = ["native-tls-vendored"] }
|
||||
tauri-utils = "=1.4.*"
|
||||
|
||||
dioxus-autofmt = { workspace = true }
|
||||
dioxus-check = { workspace = true }
|
||||
@@ -100,3 +94,9 @@ name = "dx"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.3"
|
||||
|
||||
[package.metadata.binstall]
|
||||
pkg-url = "{ repo }/releases/download/v{ version }/dx-{ target }{ archive-suffix }"
|
||||
|
||||
[package.metadata.binstall.overrides.x86_64-pc-windows-msvc]
|
||||
pkg-fmt = "zip"
|
||||
+21
-18
@@ -1,29 +1,31 @@
|
||||
[application]
|
||||
|
||||
# dioxus project name
|
||||
name = "dioxus-cli"
|
||||
# App name
|
||||
name = "project_name"
|
||||
|
||||
# default platfrom
|
||||
# you can also use `dx serve/build --platform XXX` to use other platform
|
||||
# value: web | desktop
|
||||
default_platform = "desktop"
|
||||
# The Dioxus platform to default to
|
||||
default_platform = "web"
|
||||
|
||||
# Web `build` & `serve` dist path
|
||||
# `build` & `serve` output path
|
||||
out_dir = "dist"
|
||||
|
||||
# resource (static) file folder
|
||||
# The static resource path
|
||||
asset_dir = "public"
|
||||
|
||||
[web.app]
|
||||
|
||||
# HTML title tag content
|
||||
title = "dioxus | ⛺"
|
||||
title = "project_name"
|
||||
|
||||
[web.watcher]
|
||||
|
||||
watch_path = ["src"]
|
||||
# When watcher is triggered, regenerate the `index.html`
|
||||
reload_html = true
|
||||
|
||||
# include `assets` in web platform
|
||||
# Which files or dirs will be monitored
|
||||
watch_path = ["src", "public"]
|
||||
|
||||
# Include style or script assets
|
||||
[web.resource]
|
||||
|
||||
# CSS style file
|
||||
@@ -34,12 +36,13 @@ script = []
|
||||
|
||||
[web.resource.dev]
|
||||
|
||||
# Javascript code file
|
||||
# serve: [dev-server] only
|
||||
# Same as [web.resource], but for development servers
|
||||
|
||||
# CSS style file
|
||||
style = []
|
||||
|
||||
# JavaScript files
|
||||
script = []
|
||||
|
||||
[application.tools]
|
||||
|
||||
# use binaryen.wasm-opt for output Wasm file
|
||||
# binaryen just will trigger in `web` platform
|
||||
binaryen = { wasm_opt = true }
|
||||
[[web.proxy]]
|
||||
backend = "http://localhost:8000/api/"
|
||||
+43
-15
@@ -1,43 +1,71 @@
|
||||
<div align="center">
|
||||
<h1>📦✨ Dioxus CLI </h1>
|
||||
<div style="text-align: center">
|
||||
<h1>📦✨ Dioxus CLI</h1>
|
||||
<p><strong>Tooling to supercharge Dioxus projects</strong></p>
|
||||
</div>
|
||||
**dioxus-cli** (inspired by wasm-pack and webpack) is a tool for getting Dioxus projects up and running.
|
||||
It handles all build, bundling, development and publishing to simplify web development.
|
||||
|
||||
The **dioxus-cli** (inspired by wasm-pack and webpack) is a tool for getting Dioxus projects up and running.
|
||||
It handles building, bundling, development and publishing to simplify development.
|
||||
|
||||
## Installation
|
||||
|
||||
### Install stable version
|
||||
### Install the stable version (recommended)
|
||||
|
||||
```
|
||||
cargo install dioxus-cli
|
||||
```
|
||||
### Install from git repository
|
||||
|
||||
### Install the latest development build through git
|
||||
|
||||
To get the latest bug fixes and features, you can install the development version from git.
|
||||
However, this is not fully tested.
|
||||
That means you're probably going to have more bugs despite having the latest bug fixes.
|
||||
|
||||
```
|
||||
cargo install --git https://github.com/DioxusLabs/dioxus dioxus-cli
|
||||
```
|
||||
|
||||
This will download the CLI from the master branch,
|
||||
and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
|
||||
|
||||
### Install from local folder
|
||||
|
||||
```
|
||||
cargo install --path . --debug
|
||||
```
|
||||
|
||||
## Get started
|
||||
|
||||
## Get Started
|
||||
|
||||
Use `dx create project-name` to initialize a new Dioxus project. <br>
|
||||
|
||||
Use `dx create project-name` to initialize a new Dioxus project.
|
||||
It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxus-template) repository.
|
||||
|
||||
<br>
|
||||
|
||||
Alternatively, you can specify the template path:
|
||||
|
||||
```
|
||||
dx create hello --template gh:dioxuslabs/dioxus-template
|
||||
```
|
||||
|
||||
## Dioxus Config File
|
||||
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.
|
||||
|
||||
Dioxus CLI will use `Dioxus.toml` file to Identify some project info and switch some cli feature.
|
||||
## Dioxus config file
|
||||
|
||||
You can get more configure information from [Dioxus CLI Document](https://dioxuslabs.com/cli/configure.html).
|
||||
You can use the `Dioxus.toml` file for further configuration.
|
||||
Some fields are mandatory, but the CLI tool will tell you which ones are missing.
|
||||
You can create a `Dioxus.toml` with all fields already set using `dx config init project-name`,
|
||||
or you can use this bare-bones template (only mandatory fields) to get started:
|
||||
|
||||
```toml
|
||||
[application]
|
||||
name = "project-name"
|
||||
# Currently supported platforms: web, desktop
|
||||
default_platform = "web"
|
||||
|
||||
[web.app]
|
||||
title = "Hello"
|
||||
|
||||
[web.watcher]
|
||||
|
||||
[web.resource.dev]
|
||||
```
|
||||
|
||||
The full anatomy of `Dioxus.toml` is shown on the [Dioxus website](https://dioxuslabs.com/learn/0.4/CLI/configure).
|
||||
@@ -1 +0,0 @@
|
||||
book
|
||||
@@ -1,6 +0,0 @@
|
||||
[book]
|
||||
authors = ["YuKun Liu"]
|
||||
language = "en"
|
||||
multilingual = false
|
||||
src = "src"
|
||||
title = "Dioxus Cli"
|
||||
@@ -1,18 +0,0 @@
|
||||
# Summary
|
||||
|
||||
- [Introduction](./introduction.md)
|
||||
- [Installation](./installation.md)
|
||||
- [Create a Project](./creating.md)
|
||||
- [Configure Project](./configure.md)
|
||||
- [Commands](./cmd/README.md)
|
||||
- [Build](./cmd/build.md)
|
||||
- [Serve](./cmd/serve.md)
|
||||
- [Clean](./cmd/clean.md)
|
||||
- [Translate](./cmd/translate.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)
|
||||
@@ -1,30 +0,0 @@
|
||||
# Commands
|
||||
|
||||
In this chapter we will introduce all `dioxus-cli` commands.
|
||||
|
||||
> You can also use `dx --help` to get cli help info.
|
||||
|
||||
```
|
||||
Build, Bundle & Ship Dioxus Apps
|
||||
|
||||
Usage: dx [OPTIONS] <COMMAND>
|
||||
|
||||
Commands:
|
||||
build Build the Rust WASM app and all of its assets
|
||||
translate Translate some source file into Dioxus code
|
||||
serve Build, watch & serve the Rust WASM app and all of its assets
|
||||
create Init a new project for Dioxus
|
||||
clean Clean output artifacts
|
||||
bundle Bundle the Rust desktop app and all of its assets
|
||||
version Print the version of this extension
|
||||
fmt Format some rsx
|
||||
check Check the Rust files in the project for issues
|
||||
config Dioxus config file controls
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
-v Enable verbose logging
|
||||
--bin <BIN> Specify bin target
|
||||
-h, --help Print help
|
||||
-V, --version Print version
|
||||
```
|
||||
@@ -1,56 +0,0 @@
|
||||
# Build
|
||||
|
||||
The `dx build` command can help you `pack & build` a dioxus project.
|
||||
|
||||
```
|
||||
dioxus-build
|
||||
Build the Rust WASM app and all of its assets
|
||||
|
||||
USAGE:
|
||||
dx build [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--example <EXAMPLE> [default: ""]
|
||||
--platform <PLATFORM> [default: "default_platform"]
|
||||
--release [default: false]
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
You can use this command to build a project:
|
||||
|
||||
```
|
||||
dx build --release
|
||||
```
|
||||
|
||||
## Target platform
|
||||
|
||||
Use the `platform` option to choose your target platform:
|
||||
|
||||
```
|
||||
# for desktop project
|
||||
dx build --platform desktop
|
||||
```
|
||||
|
||||
`platform` currently only supports `desktop` & `web`.
|
||||
|
||||
```
|
||||
# for web project
|
||||
dx build --platform web
|
||||
```
|
||||
|
||||
## Specify workspace bin
|
||||
|
||||
You can add the `--bin` option to select which crate you want Dioxus to build:
|
||||
|
||||
```
|
||||
dx build --bin app
|
||||
```
|
||||
|
||||
## Build Example
|
||||
|
||||
You can use the `example` option to select a example to build:
|
||||
|
||||
```
|
||||
# build the `test` example
|
||||
dx build --exmaple test
|
||||
```
|
||||
@@ -1,27 +0,0 @@
|
||||
# Clean
|
||||
|
||||
`dx clean` will clear the build artifacts (the out_dir and the cargo cache)
|
||||
|
||||
```
|
||||
dioxus-clean
|
||||
Clean build artifacts
|
||||
|
||||
USAGE:
|
||||
dx clean [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
```
|
||||
dx clean
|
||||
```
|
||||
|
||||
# Specify workspace bin
|
||||
You can add the `--bin` option to select which crate you want Dioxus to clean artifacts from:
|
||||
|
||||
```
|
||||
dx clean --bin app
|
||||
```
|
||||
@@ -1,70 +0,0 @@
|
||||
# Serve
|
||||
|
||||
The `dx serve` can start a dev server with hot-reloading
|
||||
|
||||
```
|
||||
dioxus-serve
|
||||
Build, watch & serve the Rust WASM app and all of its assets
|
||||
|
||||
USAGE:
|
||||
dx serve [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--example <EXAMPLE> [default: ""]
|
||||
--platform <PLATFORM> [default: "default_platform"]
|
||||
--release [default: false]
|
||||
--hot-reload [default: false]
|
||||
--bin [default: None]
|
||||
```
|
||||
|
||||
You can use this command to build project and start a dev server:
|
||||
|
||||
```
|
||||
dx serve
|
||||
```
|
||||
|
||||
## Serve Example
|
||||
|
||||
You can use the `example` option to serve a example:
|
||||
|
||||
```
|
||||
# serve the `test` example
|
||||
dx serve --exmaple test
|
||||
```
|
||||
|
||||
## Specify workspace bin
|
||||
|
||||
You can add the `--bin` option to select which crate you want Dioxus to build and serve:
|
||||
|
||||
```
|
||||
dx serve --bin app
|
||||
```
|
||||
|
||||
## Open Browser
|
||||
|
||||
You can add the `--open` option to open system default browser when server startup:
|
||||
|
||||
```
|
||||
dx serve --open
|
||||
```
|
||||
|
||||
## RSX Hot Reloading
|
||||
|
||||
You can add the `--hot-reload` flag to enable [rsx hot reloading](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/hot_reload.html). This will allow you to reload some rsx changes without a full recompile:
|
||||
|
||||
```
|
||||
dx serve --open
|
||||
```
|
||||
|
||||
## Cross Origin Policy
|
||||
|
||||
You can add the `cross-origin-policy` option to change cross-origin header to:
|
||||
|
||||
```
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
Cross-Origin-Embedder-Policy: require-corp
|
||||
```
|
||||
|
||||
```
|
||||
dx serve --corss-origin-policy
|
||||
```
|
||||
@@ -1,68 +0,0 @@
|
||||
# Translate
|
||||
|
||||
`dx translate` can translate some `html` file into a Dioxus compoent
|
||||
|
||||
```
|
||||
dioxus-translate
|
||||
Translate some source file into a Dioxus component
|
||||
|
||||
USAGE:
|
||||
dx translate [OPTIONS] [OUTPUT]
|
||||
|
||||
ARGS:
|
||||
<OUTPUT> Output file, defaults to stdout if not present
|
||||
|
||||
OPTIONS:
|
||||
-c, --component Activate debug mode
|
||||
-f, --file <FILE> Input file
|
||||
```
|
||||
|
||||
## Translate HTML to stdout
|
||||
|
||||
You can use the `file` option to set path to the `html` file to translate:
|
||||
|
||||
```
|
||||
dx transtale --file ./index.html
|
||||
```
|
||||
|
||||
## Output rsx to a file
|
||||
|
||||
You can pass a file to the traslate command to set the path to write the output of the command to:
|
||||
|
||||
```
|
||||
dx translate --file ./index.html component.rsx
|
||||
```
|
||||
|
||||
## Output rsx to a file
|
||||
|
||||
Setting the `component` option will create a compoent from the HTML:
|
||||
|
||||
```
|
||||
dx translate --file ./index.html --component
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
This HTML:
|
||||
```html
|
||||
<div>
|
||||
<h1> Hello World </h1>
|
||||
<a href="https://dioxuslabs.com/">Link</a>
|
||||
</div>
|
||||
```
|
||||
|
||||
Translates into this Dioxus component:
|
||||
|
||||
```rust
|
||||
fn component(cx: Scope) -> Element {
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
h1 { "Hello World" },
|
||||
a {
|
||||
href: "https://dioxuslabs.com/",
|
||||
"Link"
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
@@ -1,208 +0,0 @@
|
||||
# Configure Project
|
||||
|
||||
|
||||
This chapter will introduce you to how to configure the CLI with your `Dioxus.toml` file
|
||||
|
||||
Be aware that if the config file is present in the folder, some fields must be filled out, or the CLI tool will abort. The mandatory [table headers](https://toml.io/en/v1.0.0#table) and keys will have a '✍' sign beside it.
|
||||
|
||||
## Structure
|
||||
|
||||
The CLI uses a `Dioxus.toml` file in the root of your crate to define some configuration for your `dioxus` project.
|
||||
|
||||
### Application ✍
|
||||
|
||||
General application confiration:
|
||||
|
||||
```
|
||||
[application]
|
||||
# configuration
|
||||
```
|
||||
1. ***name*** ✍ - project name & title
|
||||
2. ***default_platform*** ✍ - which platform target for this project.
|
||||
|
||||
```
|
||||
name = "my-project"
|
||||
```
|
||||
2. ***default_platform*** - The platform this project targets
|
||||
```ß
|
||||
# current supported platforms: web, desktop
|
||||
# default: web
|
||||
default_platform = "web"
|
||||
```
|
||||
if you change this to `desktop`, the `dx build` will default building a desktop app
|
||||
3. ***out_dir*** - The directory to place the build artifacts from `dx build` or `dx service` into. This is also where the `assets` directory will be copied to
|
||||
```
|
||||
out_dir = "dist"
|
||||
```
|
||||
4. ***asset_dir*** - The directory with your static assets. The CLI will automatically copy these assets into the ***out_dir*** after a build/serve.
|
||||
```
|
||||
asset_dir = "public"
|
||||
```
|
||||
5. ***sub_package*** - The sub package in the workspace to build by default
|
||||
```
|
||||
sub_package = "my-crate"
|
||||
```
|
||||
|
||||
### Web.App ✍
|
||||
|
||||
Configeration specific to web applications:
|
||||
|
||||
```
|
||||
[web.app]
|
||||
# configuration
|
||||
```
|
||||
|
||||
1. ***title*** - The title of the web page
|
||||
```
|
||||
# HTML title tag content
|
||||
title = "dioxus app | ⛺"
|
||||
```
|
||||
2. ***base_path*** - The base path to build the appliation 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.
|
||||
```
|
||||
# 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 ✍
|
||||
|
||||
Configeration related to the development server:
|
||||
|
||||
```
|
||||
[web.watcher]
|
||||
# configuration
|
||||
```
|
||||
|
||||
1. ***reload_html*** - If this is true, the cli will rebuild the index.html file every time the application is rebuilt
|
||||
```
|
||||
reload_html = true
|
||||
```
|
||||
2. ***watch_path*** - The files & directories to moniter for changes
|
||||
```
|
||||
watch_path = ["src", "public"]
|
||||
```
|
||||
3. ***index_on_404*** - If enabled, Dioxus CLI will serve the root page when a route is not found. *This is needed when serving an application that uses the router*
|
||||
```
|
||||
index_on_404 = true
|
||||
```
|
||||
|
||||
### Web.Resource ✍
|
||||
|
||||
Configeration related to static resources your application uses:
|
||||
```
|
||||
[web.resource]
|
||||
# configuration
|
||||
```
|
||||
|
||||
1. ***style*** - The styles (`.css` files) to include in your application
|
||||
```
|
||||
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*** - The additional scripts (`.js` files) to include in your application
|
||||
```
|
||||
style = [
|
||||
# include from public_dir.
|
||||
"./assets/index.js",
|
||||
# or some asset from online cdn.
|
||||
"https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js"
|
||||
]
|
||||
```
|
||||
|
||||
### Web.Resource.Dev ✍
|
||||
|
||||
Configeration related to static resources your application uses in development:
|
||||
```
|
||||
[web.resource.dev]
|
||||
# configuration
|
||||
```
|
||||
|
||||
1. ***style*** - The styles (`.css` files) to include in your application
|
||||
```
|
||||
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*** - The additional scripts (`.js` files) to include in your application
|
||||
```
|
||||
style = [
|
||||
# include from public_dir.
|
||||
"./assets/index.js",
|
||||
# or some asset from online cdn.
|
||||
"https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js"
|
||||
]
|
||||
```
|
||||
|
||||
### Web.Proxy
|
||||
|
||||
Configeration related to any proxies your application requires durring development. Proxies will forward requests to a new service
|
||||
|
||||
```
|
||||
[[web.proxy]]
|
||||
# configuration
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
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 not currently supported).
|
||||
|
||||
## Config example
|
||||
|
||||
```toml
|
||||
[application]
|
||||
|
||||
# App (Project) 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 = "dioxus | ⛺"
|
||||
|
||||
[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 `assets` in web platform
|
||||
[web.resource]
|
||||
|
||||
# CSS style file
|
||||
style = []
|
||||
|
||||
# Javascript code file
|
||||
script = []
|
||||
|
||||
[web.resource.dev]
|
||||
|
||||
# serve: [dev-server] only
|
||||
|
||||
# CSS style file
|
||||
style = []
|
||||
|
||||
# Javascript code file
|
||||
script = []
|
||||
|
||||
[[web.proxy]]
|
||||
backend = "http://localhost:8000/api/"
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
# Create a Project
|
||||
|
||||
Once you have the Dioxus CLI tool installed, you can use it to create dioxus project.
|
||||
|
||||
## Initializing a default project
|
||||
|
||||
First, run the `dx create` command to create a new project ready to be used with Dioxus and the Dioxus CLI:
|
||||
|
||||
```
|
||||
dx create hello-dioxus
|
||||
```
|
||||
|
||||
> It will clone a default template from github template: [DioxusLabs/dioxus-template](https://github.com/DioxusLabs/dioxus-template)
|
||||
> This default template is use 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, move the current directory into your new project:
|
||||
|
||||
```
|
||||
cd hello-dioxus
|
||||
```
|
||||
|
||||
> Make sure `wasm32 target` is installed before running the Web project.
|
||||
> You can install the wasm target for rust using rustup:
|
||||
> ```
|
||||
> rustup target add wasm32-unknown-unknown
|
||||
> ```
|
||||
|
||||
Finally, create serve your project with the Dioxus CLI:
|
||||
|
||||
```
|
||||
dx serve
|
||||
```
|
||||
|
||||
By default, the CLI serve your site at: [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/)
|
||||
@@ -1,22 +0,0 @@
|
||||
# Installation
|
||||
|
||||
Choose any one of the methods below to install the Dioxus CLI:
|
||||
|
||||
## Install from latest git version
|
||||
|
||||
To get the most up to date bug fixes and features of the Dioxus CLI, you can install the development version from git.
|
||||
|
||||
```
|
||||
cargo install --git https://github.com/Dioxuslabs/cli
|
||||
```
|
||||
|
||||
This will automatically download `Dioxus-CLI` source from github master branch,
|
||||
and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
|
||||
|
||||
## Install from `crates.io` version
|
||||
|
||||
The published version of the Dioxus CLI is updated less often, but should be more stable than the git version of the Dioxus CLI.
|
||||
|
||||
```
|
||||
cargo install dioxus-cli
|
||||
```
|
||||
@@ -1,21 +0,0 @@
|
||||
# Introduction
|
||||
|
||||
📦✨ **Dioxus-Cli** is a tool to help get dioxus projects off the ground.
|
||||
|
||||

|
||||
|
||||
It includes `dev server`, `hot reload` and some `quick command` to help you use dioxus.
|
||||
|
||||
## Features
|
||||
|
||||
- [x] `html` to `rsx` conversion tool
|
||||
- [x] hot reload for `web` platform
|
||||
- [x] create dioxus project from `git` repo
|
||||
- [x] build & pack dioxus project
|
||||
- [ ] autoformat dioxus `rsx` code
|
||||
|
||||
## Contributors
|
||||
|
||||
Contributors to this guide:
|
||||
|
||||
- [mrxiaozhuox](https://github.com/mrxiaozhuox)
|
||||
@@ -1,79 +0,0 @@
|
||||
# CLI Plugin Development
|
||||
|
||||
> For Cli 0.2.0 we will add `plugin-develop` support.
|
||||
|
||||
Before the 0.2.0 we use `dx tool` to use & install some plugin, but we think that is not good for extend cli program, some people want tailwind support, some people want sass support, we can't add all this thing in to the cli source code and we don't have time to maintain a lot of tools that user request, so maybe user make plugin by themself is a good choice.
|
||||
|
||||
### Why Lua ?
|
||||
|
||||
We choose `Lua: 5.4` to be the plugin develop language, because cli plugin is not complex, just like a workflow, and user & developer can write some easy code for their plugin. We have **vendored** lua in cli program, and user don't need install lua runtime in their computer, and the lua parser & runtime doesn't take up much disk memory.
|
||||
|
||||
### Event Management
|
||||
|
||||
The plugin library have pre-define some important event you can control:
|
||||
|
||||
- `build.on_start`
|
||||
- `build.on_finished`
|
||||
- `serve.on_start`
|
||||
- `serve.on_rebuild`
|
||||
- `serve.on_shutdown`
|
||||
|
||||
### 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 some code & script
|
||||
|
||||
Type Define:
|
||||
```
|
||||
Stdio: "Inherit" | "Piped" | "Null"
|
||||
```
|
||||
|
||||
### `exec(commands: [string], stdout: Stdio, stderr: Stdio)`
|
||||
|
||||
you can use this function to run some command 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 don't have exception catch.
|
||||
@@ -1,35 +0,0 @@
|
||||
# Dirs Functions
|
||||
|
||||
> you can use Dirs functions to get some directory path
|
||||
|
||||
|
||||
### plugin_dir() -> string
|
||||
|
||||
You can get current plugin **root** directory path
|
||||
|
||||
```lua
|
||||
local path = plugin.dirs.plugin_dir()
|
||||
-- example: ~/Development/DioxusCli/plugin/test-plugin/
|
||||
```
|
||||
|
||||
### bin_dir() -> string
|
||||
|
||||
You can get plugin **bin** direcotry path
|
||||
|
||||
Sometime you need install some binary file like `tailwind-cli` & `sass-cli` to help your plugin work, then you should put binary file in this directory.
|
||||
|
||||
```lua
|
||||
local path = plugin.dirs.bin_dir()
|
||||
-- example: ~/Development/DioxusCli/plugin/test-plugin/bin/
|
||||
```
|
||||
|
||||
### temp_dir() -> string
|
||||
|
||||
You can get plugin **temp** direcotry path
|
||||
|
||||
Just put some temporary file in this directory.
|
||||
|
||||
```lua
|
||||
local path = plugin.dirs.bin_dir()
|
||||
-- example: ~/Development/DioxusCli/plugin/test-plugin/temp/
|
||||
```
|
||||
@@ -1,48 +0,0 @@
|
||||
# Log Functions
|
||||
|
||||
> You can use log function to print some useful log info
|
||||
|
||||
### 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,34 +0,0 @@
|
||||
# Network Functions
|
||||
|
||||
> you can use Network functions to download & read some data from internet
|
||||
|
||||
### download_file(url: string, path: string) -> boolean
|
||||
|
||||
This function can help you download some file from url, and it will return a *boolean* value to check the download status. (true: success | false: fail)
|
||||
|
||||
You need 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
|
||||
|
||||
This function can help you use `git clone` command (this system must have been installed git)
|
||||
|
||||
```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
|
||||
|
||||
> you can use OS functions to get some system information
|
||||
|
||||
### current_platform() -> string ("windows" | "macos" | "linux")
|
||||
|
||||
This function can help you get system & platform type:
|
||||
|
||||
```lua
|
||||
local platform = plugin.os.current_platform()
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
# Path Functions
|
||||
|
||||
> you can use path functions to operate valid path string
|
||||
|
||||
### join(path: string, extra: string) -> string
|
||||
|
||||
This function can help you extend a path, you can extend any path, dirname or filename.
|
||||
|
||||
```lua
|
||||
local current_path = "~/hello/dioxus"
|
||||
local new_path = plugin.path.join(current_path, "world")
|
||||
-- new_path = "~/hello/dioxus/world"
|
||||
```
|
||||
|
||||
### parent(path: string) -> string
|
||||
|
||||
This function will return `path` parent-path string, back to the parent.
|
||||
|
||||
```lua
|
||||
local current_path = "~/hello/dioxus"
|
||||
local new_path = plugin.path.parent(current_path)
|
||||
-- new_path = "~/hello/"
|
||||
```
|
||||
|
||||
### exists(path: string) -> boolean
|
||||
|
||||
This function can check some path (dir & file) is exists.
|
||||
|
||||
### is_file(path: string) -> boolean
|
||||
|
||||
This function can check some path is a exist file.
|
||||
|
||||
### is_dir(path: string) -> boolean
|
||||
|
||||
This function can check some path is a exist dir.
|
||||
@@ -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
|
||||
@@ -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]
|
||||
|
||||
+12
-45
@@ -22,6 +22,7 @@ pub struct BuildResult {
|
||||
pub elapsed_time: u128,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn build(config: &CrateConfig, quiet: 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
|
||||
@@ -63,11 +64,9 @@ 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 quiet { cmd.arg("--quiet") } else { cmd };
|
||||
|
||||
let cmd = if config.custom_profile.is_some() {
|
||||
let custom_profile = config.custom_profile.as_ref().unwrap();
|
||||
cmd.arg("--profile").arg(custom_profile)
|
||||
@@ -254,6 +253,7 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
|
||||
let mut cmd = subprocess::Exec::cmd("cargo")
|
||||
.cwd(&config.crate_dir)
|
||||
.arg("build")
|
||||
.arg("--quiet")
|
||||
.arg("--message-format=json");
|
||||
|
||||
if config.release {
|
||||
@@ -312,7 +312,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() {
|
||||
@@ -386,10 +386,9 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
}
|
||||
}
|
||||
|
||||
StopSpinOnDrop(pb.clone());
|
||||
|
||||
let stdout = cmd.detached().stream_stdout()?;
|
||||
let reader = std::io::BufReader::new(stdout);
|
||||
|
||||
for message in cargo_metadata::Message::parse_stream(reader) {
|
||||
match message.unwrap() {
|
||||
Message::CompilerMessage(msg) => {
|
||||
@@ -409,7 +408,7 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
|
||||
}
|
||||
}
|
||||
Message::CompilerArtifact(artifact) => {
|
||||
pb.set_message(format!("Compiling {} ", artifact.package_id));
|
||||
pb.set_message(format!("⚙️ Compiling {} ", artifact.package_id));
|
||||
pb.tick();
|
||||
}
|
||||
Message::BuildScriptExecuted(script) => {
|
||||
@@ -443,14 +442,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.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);
|
||||
}
|
||||
@@ -469,7 +468,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
|
||||
.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");
|
||||
}
|
||||
|
||||
replace_or_insert_before("{style_include}", &style_str, "</head", &mut html);
|
||||
@@ -689,35 +688,3 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// use binary_install::{Cache, Download};
|
||||
|
||||
// /// 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));
|
||||
|
||||
// match path.as_path().parent() {
|
||||
// Some(path) => return Ok(install::Status::Found(Download::at(path))),
|
||||
// None => {}
|
||||
// }
|
||||
// }
|
||||
|
||||
// let version = "version_78";
|
||||
// Ok(install::download_prebuilt(
|
||||
// &install::Tool::WasmOpt,
|
||||
// cache,
|
||||
// version,
|
||||
// install_permitted,
|
||||
// )?)
|
||||
// }
|
||||
@@ -1,3 +1,4 @@
|
||||
use dioxus_autofmt::{IndentOptions, IndentType};
|
||||
use futures::{stream::FuturesUnordered, StreamExt};
|
||||
use std::{fs, path::Path, process::exit};
|
||||
|
||||
@@ -35,7 +36,8 @@ impl Autoformat {
|
||||
}
|
||||
|
||||
if let Some(raw) = self.raw {
|
||||
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0) {
|
||||
let indent = indentation_for(".")?;
|
||||
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
|
||||
println!("{}", inner);
|
||||
} else {
|
||||
// exit process with error
|
||||
@@ -46,18 +48,32 @@ impl Autoformat {
|
||||
|
||||
// Format single file
|
||||
if let Some(file) = self.file {
|
||||
let file_content = fs::read_to_string(&file);
|
||||
let file_content;
|
||||
let indent;
|
||||
if file == "-" {
|
||||
indent = indentation_for(".")?;
|
||||
let mut contents = String::new();
|
||||
std::io::stdin().read_to_string(&mut contents)?;
|
||||
file_content = Ok(contents);
|
||||
} else {
|
||||
indent = indentation_for(".")?;
|
||||
file_content = fs::read_to_string(&file);
|
||||
};
|
||||
|
||||
match file_content {
|
||||
Ok(s) => {
|
||||
let edits = dioxus_autofmt::fmt_file(&s);
|
||||
let edits = dioxus_autofmt::fmt_file(&s, indent);
|
||||
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);
|
||||
if file == "-" {
|
||||
print!("{}", out);
|
||||
} else {
|
||||
match fs::write(&file, out) {
|
||||
Ok(_) => {
|
||||
println!("formatted {}", file);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("failed to write formatted content to file: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +99,12 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
let mut files_to_format = vec![];
|
||||
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
|
||||
|
||||
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| {
|
||||
@@ -94,10 +116,11 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
})
|
||||
.map(|path| async {
|
||||
let _path = path.clone();
|
||||
let _indent = indent.clone();
|
||||
let res = tokio::spawn(async move {
|
||||
let contents = tokio::fs::read_to_string(&path).await?;
|
||||
|
||||
let edits = dioxus_autofmt::fmt_file(&contents);
|
||||
let edits = dioxus_autofmt::fmt_file(&contents, _indent.clone());
|
||||
let len = edits.len();
|
||||
|
||||
if !edits.is_empty() {
|
||||
@@ -141,6 +164,49 @@ async fn autoformat_project(check: bool) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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: &Path, files: &mut Vec<PathBuf>) {
|
||||
let Ok(folder) = folder.read_dir() else {
|
||||
return;
|
||||
|
||||
@@ -42,7 +42,7 @@ impl Build {
|
||||
|
||||
match platform {
|
||||
Platform::Web => {
|
||||
crate::builder::build(&crate_config, false)?;
|
||||
crate::builder::build(&crate_config, true)?;
|
||||
}
|
||||
Platform::Desktop => {
|
||||
crate::builder::build_desktop(&crate_config, false)?;
|
||||
|
||||
@@ -132,10 +132,10 @@ impl Bundle {
|
||||
.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)
|
||||
|
||||
@@ -105,7 +105,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),
|
||||
},
|
||||
@@ -381,6 +381,7 @@ impl From<DebianSettings> for tauri_bundler::DebianSettings {
|
||||
tauri_bundler::DebianSettings {
|
||||
depends: val.depends,
|
||||
files: val.files,
|
||||
desktop_template: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -522,6 +523,8 @@ impl From<NsisSettings> for tauri_bundler::NsisSettings {
|
||||
install_mode: val.install_mode.into(),
|
||||
languages: val.languages,
|
||||
display_language_selector: val.display_language_selector,
|
||||
custom_language_files: None,
|
||||
template: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
pub const DIOXUS_CLI_VERSION: &str = "0.1.5";
|
||||
#![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;
|
||||
pub mod server;
|
||||
|
||||
@@ -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();
|
||||
|
||||
+28
-39
@@ -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]
|
||||
@@ -55,7 +44,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
let bin = get_bin(args.bin)?;
|
||||
|
||||
let _dioxus_config = DioxusConfig::load(bin.clone())
|
||||
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");
|
||||
@@ -72,15 +61,15 @@ async fn main() -> anyhow::Result<()> {
|
||||
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
|
||||
|
||||
Build(opts) => opts
|
||||
.build(bin.clone())
|
||||
.build(Some(bin.clone()))
|
||||
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
|
||||
|
||||
Clean(opts) => opts
|
||||
.clean(bin.clone())
|
||||
.clean(Some(bin.clone()))
|
||||
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
|
||||
|
||||
Serve(opts) => opts
|
||||
.serve(bin.clone())
|
||||
.serve(Some(bin.clone()))
|
||||
.await
|
||||
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
|
||||
|
||||
@@ -93,7 +82,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
|
||||
|
||||
Bundle(opts) => opts
|
||||
.bundle(bin.clone())
|
||||
.bundle(Some(bin.clone()))
|
||||
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
server::{
|
||||
output::{print_console_info, PrettierOptions},
|
||||
setup_file_watcher, setup_file_watcher_hot_reload,
|
||||
setup_file_watcher,
|
||||
},
|
||||
BuildResult, CrateConfig, Result,
|
||||
};
|
||||
@@ -19,6 +19,8 @@ use tokio::sync::broadcast::{self};
|
||||
#[cfg(feature = "plugin")]
|
||||
use plugin::PluginManager;
|
||||
|
||||
use super::HotReloadState;
|
||||
|
||||
pub async fn startup(config: CrateConfig) -> Result<()> {
|
||||
// ctrl-c shutdown checker
|
||||
let _crate_config = config.clone();
|
||||
@@ -28,16 +30,36 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
|
||||
std::process::exit(0);
|
||||
});
|
||||
|
||||
match config.hot_reload {
|
||||
true => serve_hot_reload(config).await?,
|
||||
false => serve_default(config).await?,
|
||||
}
|
||||
let hot_reload_state = match config.hot_reload {
|
||||
true => {
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let hot_reload_tx = broadcast::channel(100).0;
|
||||
|
||||
clear_paths();
|
||||
|
||||
Some(HotReloadState {
|
||||
messages: hot_reload_tx.clone(),
|
||||
file_map: file_map.clone(),
|
||||
})
|
||||
}
|
||||
false => None,
|
||||
};
|
||||
|
||||
serve(config, hot_reload_state).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve_default(config: CrateConfig) -> Result<()> {
|
||||
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);
|
||||
|
||||
@@ -51,6 +73,7 @@ pub async fn serve_default(config: CrateConfig) -> Result<()> {
|
||||
|
||||
move || {
|
||||
let mut current_child = currently_running_child.write().unwrap();
|
||||
log::trace!("Killing old process");
|
||||
current_child.kill()?;
|
||||
let (child, result) = start_desktop(&config)?;
|
||||
*current_child = child;
|
||||
@@ -59,6 +82,7 @@ pub async fn serve_default(config: CrateConfig) -> Result<()> {
|
||||
},
|
||||
&config,
|
||||
None,
|
||||
hot_reload_state.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -73,105 +97,62 @@ pub async fn serve_default(config: CrateConfig) -> Result<()> {
|
||||
None,
|
||||
);
|
||||
|
||||
std::future::pending::<()>().await;
|
||||
match hot_reload_state {
|
||||
Some(hot_reload_state) => {
|
||||
start_desktop_hot_reload(hot_reload_state).await?;
|
||||
}
|
||||
None => {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
|
||||
/// Start dx serve with hot reload
|
||||
pub async fn serve_hot_reload(config: CrateConfig) -> Result<()> {
|
||||
let (_, first_build_result) = start_desktop(&config)?;
|
||||
|
||||
println!("🚀 Starting development server...");
|
||||
|
||||
// Setup hot reload
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
println!("🚀 Starting development server...");
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let (hot_reload_tx, mut hot_reload_rx) = broadcast::channel(100);
|
||||
|
||||
// States
|
||||
// The open interprocess sockets
|
||||
let channels = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
// Setup file watcher
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise hot reload won't work.
|
||||
let _watcher = setup_file_watcher_hot_reload(
|
||||
&config,
|
||||
hot_reload_tx,
|
||||
file_map.clone(),
|
||||
{
|
||||
let config = config.clone();
|
||||
|
||||
let channels = channels.clone();
|
||||
move || {
|
||||
for channel in &mut *channels.lock().unwrap() {
|
||||
send_msg(HotReloadMsg::Shutdown, channel);
|
||||
}
|
||||
Ok(start_desktop(&config)?.1)
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
clear_paths();
|
||||
|
||||
async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
|
||||
match LocalSocketListener::bind("@dioxusin") {
|
||||
Ok(local_socket_stream) => {
|
||||
let aborted = Arc::new(Mutex::new(false));
|
||||
// States
|
||||
// The open interprocess sockets
|
||||
let channels = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
// listen for connections
|
||||
std::thread::spawn({
|
||||
let file_map = file_map.clone();
|
||||
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) => {
|
||||
if err.kind() != std::io::ErrorKind::WouldBlock {
|
||||
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;
|
||||
@@ -180,6 +161,8 @@ pub async fn serve_hot_reload(config: CrateConfig) -> Result<()> {
|
||||
}
|
||||
});
|
||||
|
||||
let mut hot_reload_rx = hot_reload_state.messages.subscribe();
|
||||
|
||||
while let Ok(template) = hot_reload_rx.recv().await {
|
||||
let channels = &mut *channels.lock().unwrap();
|
||||
let mut i = 0;
|
||||
@@ -230,6 +213,7 @@ fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
|
||||
|
||||
pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
|
||||
// Run the desktop application
|
||||
log::trace!("Building application");
|
||||
let result = crate::builder::build_desktop(config, true)?;
|
||||
|
||||
match &config.executable {
|
||||
@@ -240,6 +224,7 @@ pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
|
||||
if cfg!(windows) {
|
||||
file.set_extension("exe");
|
||||
}
|
||||
log::trace!("Running application from {:?}", file);
|
||||
let child = Command::new(file.to_str().unwrap()).spawn()?;
|
||||
|
||||
Ok((child, result))
|
||||
|
||||
+93
-127
@@ -9,7 +9,7 @@ use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::sync::broadcast::Sender;
|
||||
use tokio::sync::broadcast::{self};
|
||||
|
||||
mod output;
|
||||
use output::*;
|
||||
@@ -21,6 +21,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
build_with: F,
|
||||
config: &CrateConfig,
|
||||
web_info: Option<WebServerInfo>,
|
||||
hot_reload: Option<HotReloadState>,
|
||||
) -> Result<RecommendedWatcher> {
|
||||
let mut last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
@@ -31,152 +32,117 @@ 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>| {
|
||||
let config = watcher_config.clone();
|
||||
if let Ok(e) = info {
|
||||
if chrono::Local::now().timestamp() > last_update_time {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
last_update_time = chrono::Local::now().timestamp();
|
||||
let mut needs_full_rebuild;
|
||||
if let Some(hot_reload) = &hot_reload {
|
||||
// find changes to the rsx in the file
|
||||
let mut rsx_file_map = hot_reload.file_map.lock().unwrap();
|
||||
let mut messages: Vec<Template<'static>> = Vec::new();
|
||||
|
||||
#[allow(clippy::redundant_clone)]
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: e.paths.clone(),
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
// In hot reload mode, we only need to rebuild if non-rsx code is changed
|
||||
needs_full_rebuild = false;
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_serve_rebuild(
|
||||
chrono::Local::now().timestamp(),
|
||||
e.paths,
|
||||
);
|
||||
for path in &e.paths {
|
||||
// if this is not a rust file, rebuild the whole project
|
||||
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
|
||||
needs_full_rebuild = true;
|
||||
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);
|
||||
needs_full_rebuild = false;
|
||||
}
|
||||
Ok(UpdateResult::NeedsRebuild) => {
|
||||
needs_full_rebuild = true;
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if needs_full_rebuild {
|
||||
// Reset the file map to the new state of the project
|
||||
let FileMapBuildResult {
|
||||
map: new_file_map,
|
||||
errors,
|
||||
} = FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
*rsx_file_map = new_file_map;
|
||||
} else {
|
||||
for msg in messages {
|
||||
let _ = hot_reload.messages.send(msg);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
needs_full_rebuild = true;
|
||||
}
|
||||
|
||||
if needs_full_rebuild {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
#[allow(clippy::redundant_clone)]
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: e.paths.clone(),
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
|
||||
#[cfg(feature = "plugin")]
|
||||
let _ = PluginManager::on_serve_rebuild(
|
||||
chrono::Local::now().timestamp(),
|
||||
e.paths,
|
||||
);
|
||||
}
|
||||
Err(e) => log::error!("{}", e),
|
||||
}
|
||||
Err(e) => log::error!("{}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
for sub_path in allow_watch_path {
|
||||
watcher
|
||||
.watch(
|
||||
&config.crate_dir.join(sub_path),
|
||||
notify::RecursiveMode::Recursive,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
// Todo: reduce duplication and merge with setup_file_watcher()
|
||||
/// Sets up a file watcher with hot reload
|
||||
async fn setup_file_watcher_hot_reload<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
||||
config: &CrateConfig,
|
||||
hot_reload_tx: Sender<Template<'static>>,
|
||||
file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
|
||||
build_with: F,
|
||||
web_info: Option<WebServerInfo>,
|
||||
) -> Result<RecommendedWatcher> {
|
||||
// file watcher: check file change
|
||||
let allow_watch_path = config
|
||||
.dioxus_config
|
||||
.web
|
||||
.watcher
|
||||
.watch_path
|
||||
.clone()
|
||||
.unwrap_or_else(|| vec![PathBuf::from("src")]);
|
||||
|
||||
let watcher_config = config.clone();
|
||||
let mut last_update_time = chrono::Local::now().timestamp();
|
||||
|
||||
let mut watcher = RecommendedWatcher::new(
|
||||
move |evt: notify::Result<notify::Event>| {
|
||||
let config = watcher_config.clone();
|
||||
// Give time for the change to take effect before reading the file
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
if chrono::Local::now().timestamp() > last_update_time {
|
||||
if let Ok(evt) = evt {
|
||||
let mut messages: Vec<Template<'static>> = Vec::new();
|
||||
for path in evt.paths.clone() {
|
||||
// if this is not a rust file, rebuild the whole project
|
||||
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: evt.paths,
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// find changes to the rsx in the file
|
||||
let mut map = file_map.lock().unwrap();
|
||||
|
||||
match map.update_rsx(&path, &config.crate_dir) {
|
||||
Ok(UpdateResult::UpdatedRsx(msgs)) => {
|
||||
messages.extend(msgs);
|
||||
}
|
||||
Ok(UpdateResult::NeedsRebuild) => {
|
||||
match build_with() {
|
||||
Ok(res) => {
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: evt.paths,
|
||||
warnings: res.warnings,
|
||||
elapsed_time: res.elapsed_time,
|
||||
},
|
||||
web_info.clone(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
for msg in messages {
|
||||
let _ = hot_reload_tx.send(msg);
|
||||
}
|
||||
}
|
||||
last_update_time = chrono::Local::now().timestamp();
|
||||
}
|
||||
},
|
||||
notify::Config::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for sub_path in allow_watch_path {
|
||||
if let Err(err) = watcher.watch(
|
||||
&config.crate_dir.join(&sub_path),
|
||||
&config.crate_dir.join(sub_path),
|
||||
notify::RecursiveMode::Recursive,
|
||||
) {
|
||||
log::error!("error watching {sub_path:?}: \n{}", err);
|
||||
log::error!("Failed to watch path: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(watcher)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HotReloadState {
|
||||
pub messages: broadcast::Sender<Template<'static>>,
|
||||
pub file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::{
|
||||
extract::{ws::Message, WebSocketUpgrade},
|
||||
response::IntoResponse,
|
||||
Extension, TypedHeader,
|
||||
};
|
||||
use dioxus_core::Template;
|
||||
use dioxus_html::HtmlCtx;
|
||||
use dioxus_rsx::hot_reload::FileMap;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use crate::CrateConfig;
|
||||
|
||||
pub struct HotReloadState {
|
||||
pub messages: broadcast::Sender<Template<'static>>,
|
||||
pub file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
|
||||
pub watcher_config: CrateConfig,
|
||||
}
|
||||
use crate::server::HotReloadState;
|
||||
|
||||
pub async fn hot_reload_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
_: Option<TypedHeader<headers::UserAgent>>,
|
||||
Extension(state): Extension<Arc<HotReloadState>>,
|
||||
Extension(state): Extension<HotReloadState>,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(|mut socket| async move {
|
||||
log::info!("🔥 Hot Reload WebSocket connected");
|
||||
|
||||
@@ -3,9 +3,9 @@ use crate::{
|
||||
serve::Serve,
|
||||
server::{
|
||||
output::{print_console_info, PrettierOptions, WebServerInfo},
|
||||
setup_file_watcher, setup_file_watcher_hot_reload,
|
||||
setup_file_watcher, HotReloadState,
|
||||
},
|
||||
BuildResult, CrateConfig, Result,
|
||||
BuildResult, CrateConfig, Result, WebHttpsConfig,
|
||||
};
|
||||
use axum::{
|
||||
body::{Full, HttpBody},
|
||||
@@ -58,22 +58,41 @@ pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Res
|
||||
|
||||
let ip = get_ip().unwrap_or(String::from("0.0.0.0"));
|
||||
|
||||
match config.hot_reload {
|
||||
true => serve_hot_reload(ip, port, config, start_browser).await?,
|
||||
false => serve_default(ip, port, config, start_browser).await?,
|
||||
}
|
||||
let hot_reload_state = match config.hot_reload {
|
||||
true => {
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let hot_reload_tx = broadcast::channel(100).0;
|
||||
|
||||
Some(HotReloadState {
|
||||
messages: hot_reload_tx.clone(),
|
||||
file_map: file_map.clone(),
|
||||
})
|
||||
}
|
||||
false => None,
|
||||
};
|
||||
|
||||
serve(ip, port, config, start_browser, hot_reload_state).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the server without hot reload
|
||||
pub async fn serve_default(
|
||||
pub async fn serve(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
hot_reload_state: Option<HotReloadState>,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
let first_build_result = crate::builder::build(&config, true)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
@@ -93,6 +112,7 @@ pub async fn serve_default(
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
hot_reload_state.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -119,88 +139,7 @@ pub async fn serve_default(
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, None).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start dx serve with hot reload
|
||||
pub async fn serve_hot_reload(
|
||||
ip: String,
|
||||
port: u16,
|
||||
config: CrateConfig,
|
||||
start_browser: bool,
|
||||
) -> Result<()> {
|
||||
let first_build_result = crate::builder::build(&config, false)?;
|
||||
|
||||
log::info!("🚀 Starting development server...");
|
||||
|
||||
// Setup hot reload
|
||||
let (reload_tx, _) = broadcast::channel(100);
|
||||
let FileMapBuildResult { map, errors } =
|
||||
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
|
||||
|
||||
for err in errors {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let file_map = Arc::new(Mutex::new(map));
|
||||
|
||||
let hot_reload_tx = broadcast::channel(100).0;
|
||||
|
||||
// States
|
||||
let hot_reload_state = Arc::new(HotReloadState {
|
||||
messages: hot_reload_tx.clone(),
|
||||
file_map: file_map.clone(),
|
||||
watcher_config: config.clone(),
|
||||
});
|
||||
|
||||
let ws_reload_state = Arc::new(WsReloadState {
|
||||
update: reload_tx.clone(),
|
||||
});
|
||||
|
||||
// Setup file watcher
|
||||
// We got to own watcher so that it exists for the duration of serve
|
||||
// Otherwise hot reload won't work.
|
||||
let _watcher = setup_file_watcher_hot_reload(
|
||||
&config,
|
||||
hot_reload_tx,
|
||||
file_map,
|
||||
{
|
||||
let config = config.clone();
|
||||
let reload_tx = reload_tx.clone();
|
||||
move || build(&config, &reload_tx)
|
||||
},
|
||||
Some(WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// HTTPS
|
||||
// Before console info so it can stop if mkcert isn't installed or fails
|
||||
let rustls_config = get_rustls(&config).await?;
|
||||
|
||||
// Print serve info
|
||||
print_console_info(
|
||||
&config,
|
||||
PrettierOptions {
|
||||
changed: vec![],
|
||||
warnings: first_build_result.warnings,
|
||||
elapsed_time: first_build_result.elapsed_time,
|
||||
},
|
||||
Some(WebServerInfo {
|
||||
ip: ip.clone(),
|
||||
port,
|
||||
}),
|
||||
);
|
||||
|
||||
// Router
|
||||
let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?;
|
||||
let router = setup_router(config, ws_reload_state, hot_reload_state).await?;
|
||||
|
||||
// Start server
|
||||
start_server(port, router, start_browser, rustls_config).await?;
|
||||
@@ -218,67 +157,12 @@ async fn get_rustls(config: &CrateConfig) -> Result<Option<RustlsConfig>> {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let (cert_path, key_path) = match web_config.mkcert {
|
||||
let (cert_path, key_path) = if let Some(true) = web_config.mkcert {
|
||||
// mkcert, use it
|
||||
Some(true) => {
|
||||
// Get paths to store certs, otherwise use ssl/item.pem
|
||||
let key_path = web_config
|
||||
.key_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_KEY_PATH.to_string());
|
||||
|
||||
let cert_path = web_config
|
||||
.cert_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_CERT_PATH.to_string());
|
||||
|
||||
// Create ssl directory if using defaults
|
||||
if key_path == DEFAULT_KEY_PATH && cert_path == DEFAULT_CERT_PATH {
|
||||
_ = fs::create_dir("ssl");
|
||||
}
|
||||
|
||||
let cmd = Command::new("mkcert")
|
||||
.args([
|
||||
"-install",
|
||||
"-key-file",
|
||||
&key_path,
|
||||
"-cert-file",
|
||||
&cert_path,
|
||||
"localhost",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
])
|
||||
.spawn();
|
||||
|
||||
match cmd {
|
||||
Err(e) => {
|
||||
match e.kind() {
|
||||
io::ErrorKind::NotFound => log::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
|
||||
e => log::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
|
||||
};
|
||||
return Err("failed to generate mkcert certificates".into());
|
||||
}
|
||||
Ok(mut cmd) => {
|
||||
cmd.wait()?;
|
||||
}
|
||||
}
|
||||
|
||||
(cert_path, key_path)
|
||||
}
|
||||
// not mkcert
|
||||
Some(false) => {
|
||||
// get paths to cert & key
|
||||
if let (Some(key), Some(cert)) =
|
||||
(web_config.key_path.clone(), web_config.cert_path.clone())
|
||||
{
|
||||
(cert, key)
|
||||
} else {
|
||||
// missing cert or key
|
||||
return Err("https is enabled but cert or key path is missing".into());
|
||||
}
|
||||
}
|
||||
// other
|
||||
_ => return Ok(None),
|
||||
get_rustls_with_mkcert(web_config)?
|
||||
} else {
|
||||
// if mkcert not specified or false, don't use it
|
||||
get_rustls_without_mkcert(web_config)?
|
||||
};
|
||||
|
||||
Ok(Some(
|
||||
@@ -286,11 +170,67 @@ async fn get_rustls(config: &CrateConfig) -> Result<Option<RustlsConfig>> {
|
||||
))
|
||||
}
|
||||
|
||||
fn get_rustls_with_mkcert(web_config: &WebHttpsConfig) -> Result<(String, String)> {
|
||||
// Get paths to store certs, otherwise use ssl/item.pem
|
||||
let key_path = web_config
|
||||
.key_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_KEY_PATH.to_string());
|
||||
|
||||
let cert_path = web_config
|
||||
.cert_path
|
||||
.clone()
|
||||
.unwrap_or(DEFAULT_CERT_PATH.to_string());
|
||||
|
||||
// Create ssl directory if using defaults
|
||||
if key_path == DEFAULT_KEY_PATH && cert_path == DEFAULT_CERT_PATH {
|
||||
_ = fs::create_dir("ssl");
|
||||
}
|
||||
|
||||
let cmd = Command::new("mkcert")
|
||||
.args([
|
||||
"-install",
|
||||
"-key-file",
|
||||
&key_path,
|
||||
"-cert-file",
|
||||
&cert_path,
|
||||
"localhost",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
])
|
||||
.spawn();
|
||||
|
||||
match cmd {
|
||||
Err(e) => {
|
||||
match e.kind() {
|
||||
io::ErrorKind::NotFound => log::error!("mkcert is not installed. See https://github.com/FiloSottile/mkcert#installation for installation instructions."),
|
||||
e => log::error!("an error occured while generating mkcert certificates: {}", e.to_string()),
|
||||
};
|
||||
return Err("failed to generate mkcert certificates".into());
|
||||
}
|
||||
Ok(mut cmd) => {
|
||||
cmd.wait()?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((cert_path, key_path))
|
||||
}
|
||||
|
||||
fn get_rustls_without_mkcert(web_config: &WebHttpsConfig) -> Result<(String, String)> {
|
||||
// get paths to cert & key
|
||||
if let (Some(key), Some(cert)) = (web_config.key_path.clone(), web_config.cert_path.clone()) {
|
||||
Ok((cert, key))
|
||||
} else {
|
||||
// missing cert or key
|
||||
Err("https is enabled but cert or key path is missing".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets up and returns a router
|
||||
async fn setup_router(
|
||||
config: CrateConfig,
|
||||
ws_reload: Arc<WsReloadState>,
|
||||
hot_reload: Option<Arc<HotReloadState>>,
|
||||
hot_reload: Option<HotReloadState>,
|
||||
) -> Result<Router> {
|
||||
// Setup cors
|
||||
let cors = CorsLayer::new()
|
||||
|
||||
@@ -17,6 +17,9 @@ proc-macro2 = { version = "1.0" }
|
||||
quote = "1.0"
|
||||
syn = { version = "2.0", features = ["full", "extra-traits"] }
|
||||
dioxus-rsx = { workspace = true }
|
||||
dioxus-core = { workspace = true }
|
||||
constcat = "0.3.0"
|
||||
prettyplease = "0.2.15"
|
||||
|
||||
# testing
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# dioxus-core-macro
|
||||
|
||||
|
||||
[![Crates.io][crates-badge]][crates-url]
|
||||
[![MIT licensed][mit-badge]][mit-url]
|
||||
[![Build Status][actions-badge]][actions-url]
|
||||
@@ -8,30 +7,28 @@
|
||||
|
||||
[crates-badge]: https://img.shields.io/crates/v/dioxus-core-macro.svg
|
||||
[crates-url]: https://crates.io/crates/dioxus-core-macro
|
||||
|
||||
[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
|
||||
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
|
||||
|
||||
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
|
||||
[discord-url]: https://discord.gg/XgGxMSkvUM
|
||||
|
||||
[Website](https://dioxuslabs.com) |
|
||||
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
|
||||
[Guides](https://dioxuslabs.com/learn/0.4/) |
|
||||
[API Docs](https://docs.rs/dioxus-core-macro/latest/dioxus_core_macro) |
|
||||
[Chat](https://discord.gg/XgGxMSkvUM)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
`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
|
||||
|
||||
@@ -39,6 +36,7 @@
|
||||
- Join the discord and ask questions!
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT license].
|
||||
|
||||
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! This module is used for parsing a component function into a struct that is subsequently
|
||||
//! deserialized into something useful using deserializer arguments.
|
||||
//!
|
||||
//! Let's break that down with a term glossary and examples which show usage and implementing.
|
||||
//!
|
||||
//! # Glossary
|
||||
//! * `component body` - The [`ComponentBody`] struct. It's used to parse a component function [`proc_macro::TokenStream`]
|
||||
//! to a reusable struct that deserializers use to modify the token stream.
|
||||
//! * `deserializer` - A struct that deserializes the [`ComponentBody`] into a [`DeserializerOutput`].
|
||||
//! It implements the [`DeserializerArgs`] trait, but as you can see, it's called "DeserializerArgs",
|
||||
//! not "Deserializer". Why?
|
||||
//! Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which
|
||||
//! takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer.
|
||||
//! * `deserializer output` - A struct that implements the [`DeserializerOutput`] trait.
|
||||
//! This struct is what enables deserializers to use each other, since it contains the fields that
|
||||
//! a deserializer needs to turn a token stream to a different token stream.
|
||||
//! This means a deserializer can get the output of another deserializer, and use that output,
|
||||
//! thereby using the functionality of a different deserializer.
|
||||
//! This struct also implements [`ToTokens`], which means that this is the final stage of the whole process.
|
||||
//!
|
||||
//! # Examples
|
||||
//! *Not all imports might be included.*
|
||||
//!
|
||||
//! ## Usage in a procedural macro attribute
|
||||
//! ```rs,ignore
|
||||
//! use proc_macro::TokenStream;
|
||||
//!
|
||||
//! // Some documentation. You can reuse this in your deserializer structs.
|
||||
//! /// This attribute changes the name of a component function to whatever the first argument is.
|
||||
//! #[proc_macro_attribute]
|
||||
//! pub fn name_changer(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
//! // Parse the component body.
|
||||
//! let component_body = parse_macro_input!(input as ComponentBody);
|
||||
//!
|
||||
//! // Parse the first argument, which is going to be the components new name.
|
||||
//! let new_name: String = match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
|
||||
//! Err(e) => return e.to_compile_error().into(), // Convert to a compile error and return
|
||||
//! Ok(args) => {
|
||||
//! // If the argument exists, then convert it to a string
|
||||
//! if let Some(first) = args.first() {
|
||||
//! first.to_token_stream().to_string()
|
||||
//! } else {
|
||||
//! // If the argument doesn't exist, return an error with the appropriate message.
|
||||
//! // The "span" is the location of some code.
|
||||
//! // The error occurred in the "args" token stream, so point the error there.
|
||||
//! return Error::new(args.span(), "No new name provided").to_compile_error().into();
|
||||
//! }
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! let new_name = &*new_name;
|
||||
//!
|
||||
//! // Deserialize the component body to an output with the given args.
|
||||
//! let output = component_body.deserialize(NameChangerDeserializerArgs { new_name });
|
||||
//!
|
||||
//! // Error handling like before, except now you're ready to return the final value.
|
||||
//! match output {
|
||||
//! Err(e) => e.to_compile_error().into(),
|
||||
//! Ok(output) => output.to_token_stream().into(),
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//! ## Using the macro in Dioxus code:
|
||||
//! ```rs
|
||||
//! use your_proc_macro_library::name_changer;
|
||||
//! use dioxus::prelude::*;
|
||||
//!
|
||||
//! #[name_changer(CoolName)]
|
||||
//! pub fn LameName(cx: Scope) -> Element {
|
||||
//! render! { "I want a cool name!" }
|
||||
//! }
|
||||
//!
|
||||
//! pub fn App(cx: Scope) -> Element {
|
||||
//! render! { CoolName {} } // Renders: "I want a cool name!"
|
||||
//! }
|
||||
//! ```
|
||||
//! ## Implementing a component body deserializer
|
||||
//! ```rs
|
||||
//! use syn::{Result, ItemFn, Signature, Ident};
|
||||
//! use quote::quote;
|
||||
//!
|
||||
//! // Create a list of arguments.
|
||||
//! // If there was no args, just make it empty. The "args" struct is also the deserializer struct.
|
||||
//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path.
|
||||
//! // Although unfortunately, the link does not work
|
||||
//! // Just make sure that your macro is well documented.
|
||||
//! /// The args and deserializing implementation for the [`name_changer`] macro.
|
||||
//! #[derive(Clone)]
|
||||
//! pub struct NameChangerDeserializerArgs<'a> {
|
||||
//! pub new_name: &'a str,
|
||||
//! }
|
||||
//!
|
||||
//! // Create an output struct.
|
||||
//! // The ItemFn represents a modified component function.
|
||||
//! // To read what fields should be here, check out the `DeserializerOutput` struct docs.
|
||||
//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path.
|
||||
//! // Just make sure that your macro is well documented.
|
||||
//! /// The output fields and [`ToTokens`] implementation for the [`name_changer`] macro.
|
||||
//! #[derive(Clone)]
|
||||
//! pub struct NameChangerDeserializerOutput {
|
||||
//! pub comp_fn: ItemFn,
|
||||
//! }
|
||||
//!
|
||||
//! // Implement `ToTokens`, which is forced by `DeserializerOutput`.
|
||||
//! // This will usually be very simple like this, even for complex deserializers.
|
||||
//! // That's because of the way the `DeserializerOutput` is designed.
|
||||
//! impl ToTokens for NameChangerDeserializerOutput {
|
||||
//! fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
//! let comp_fn = &self.comp_fn;
|
||||
//!
|
||||
//! tokens.append_all(quote! {
|
||||
//! #comp_fn
|
||||
//! });
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! impl DeserializerOutput for NameChangerDeserializerOutput {}
|
||||
//!
|
||||
//! // Implement `DeserializerArgs`. This is the core part of deserializers.
|
||||
//! impl<'a> DeserializerArgs<NameChangerDeserializerOutput> for NameChangerDeserializerArgs<'a> {
|
||||
//! fn to_output(&self, component_body: &ComponentBody) -> Result<NameChangerDeserializerOutput> {
|
||||
//! let old_fn = &component_body.item_fn;
|
||||
//! let old_sig = &old_fn.sig;
|
||||
//!
|
||||
//! // For more complex uses, you will probably use `quote::parse_quote!` in combination with
|
||||
//! // creating the structs manually.
|
||||
//! // However, create the structs manually if you can.
|
||||
//! // It's more reliable, because you only modify a certain struct field
|
||||
//! // and set the others to be the clone of the original component body.
|
||||
//! // That ensures that no information will be accidentally removed.
|
||||
//! let new_sig = Signature {
|
||||
//! ident: Ident::new(self.new_name, old_sig.ident.span()),
|
||||
//! ..old_sig.clone()
|
||||
//! };
|
||||
//! let new_fn = ItemFn {
|
||||
//! sig: new_sig,
|
||||
//! ..old_fn.clone()
|
||||
//! };
|
||||
//!
|
||||
//! Ok(NameChangerDeserializerOutput {
|
||||
//! comp_fn: new_fn
|
||||
//! })
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub mod utils;
|
||||
|
||||
pub use utils::DeserializerArgs;
|
||||
pub use utils::DeserializerOutput;
|
||||
pub use utils::TypeHelper;
|
||||
|
||||
use dioxus_core::{Element, Scope};
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::*;
|
||||
|
||||
/// General struct for parsing a component body.
|
||||
/// However, because it's ambiguous, it does not implement [`ToTokens`](quote::to_tokens::ToTokens).
|
||||
///
|
||||
/// Refer to the [module documentation](crate::component_body) for more.
|
||||
pub struct ComponentBody {
|
||||
/// The component function definition. You can parse this back into a [`ComponentBody`].
|
||||
/// For example, you might modify it, parse it into a [`ComponentBody`], and deserialize that
|
||||
/// using some deserializer. This is how deserializers use other deserializers.
|
||||
///
|
||||
/// **`item_fn.sig.inputs` includes the context argument!**
|
||||
/// Keep this in mind when creating deserializers, because you often might want to ignore it.
|
||||
/// That might be annoying, but it would be bad design for this kind of struct to not be parsable from itself.
|
||||
pub item_fn: ItemFn,
|
||||
/// Parsing tries to ensure that this argument will be a [`Scope`].
|
||||
/// **However, macros have limitations that prevent this from always working,
|
||||
/// so don't take this for granted!**
|
||||
pub cx_arg: FnArg,
|
||||
/// The pattern (name) and type of the context argument.
|
||||
pub cx_pat_type: PatType,
|
||||
/// If the function has any arguments other than the context.
|
||||
pub has_extra_args: bool,
|
||||
}
|
||||
|
||||
impl ComponentBody {
|
||||
/// Deserializes the body into the [`TOutput`] with the specific [`TArgs`].
|
||||
/// Even if the args are empty, the [`TArg`] type still determines what [`TOutput`] will be generated.
|
||||
pub fn deserialize<TOutput, TArgs>(&self, args: TArgs) -> Result<TOutput>
|
||||
where
|
||||
TOutput: DeserializerOutput,
|
||||
TArgs: DeserializerArgs<TOutput>,
|
||||
{
|
||||
args.to_output(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for ComponentBody {
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
let item_fn: ItemFn = input.parse()?;
|
||||
let scope_type_path = Scope::get_path_string();
|
||||
|
||||
let (cx_arg, cx_pat_type) = if let Some(first_arg) = item_fn.sig.inputs.first() {
|
||||
let incorrect_first_arg_err = Err(Error::new(
|
||||
first_arg.span(),
|
||||
format!("First argument must be a <{}>", scope_type_path),
|
||||
));
|
||||
|
||||
match first_arg.to_owned() {
|
||||
FnArg::Receiver(_) => {
|
||||
return incorrect_first_arg_err;
|
||||
}
|
||||
FnArg::Typed(f) => (first_arg.to_owned(), f),
|
||||
}
|
||||
} else {
|
||||
return Err(Error::new(
|
||||
item_fn.sig.ident.span(), // Or maybe just item_f.sig.span()?
|
||||
format!(
|
||||
"Must have at least one argument that's a <{}>",
|
||||
scope_type_path
|
||||
),
|
||||
));
|
||||
};
|
||||
|
||||
let element_type_path = Element::get_path_string();
|
||||
|
||||
if item_fn.sig.output == ReturnType::Default {
|
||||
return Err(Error::new(
|
||||
item_fn.sig.output.span(),
|
||||
format!("Must return a <{}>", element_type_path),
|
||||
));
|
||||
}
|
||||
|
||||
let has_extra_args = item_fn.sig.inputs.len() > 1;
|
||||
|
||||
Ok(Self {
|
||||
item_fn,
|
||||
cx_arg,
|
||||
cx_pat_type,
|
||||
has_extra_args,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use crate::component_body::ComponentBody;
|
||||
use dioxus_core::{Element, Scope};
|
||||
use quote::ToTokens;
|
||||
use syn::{parse_quote, Path};
|
||||
|
||||
/// The output produced by a deserializer.
|
||||
///
|
||||
/// # For implementors
|
||||
/// Struct field guidelines:
|
||||
/// * Must be public, so that other deserializers can utilize them.
|
||||
/// * Should usually be [`Item`]s that you then simply combine in a [`quote!`]
|
||||
/// in the [`ComponentBodyDeserializer::output_to_token_stream2`] function.
|
||||
/// * If an [`Item`] might not be included, wrap it in an [`Option`].
|
||||
/// * Must be at the component function "level"/"context".
|
||||
/// For example, the [`InlinePropsDeserializer`](crate::component_body_deserializers::inline_props::InlinePropsDeserializer)
|
||||
/// produces two [`Item`]s; the function but with arguments turned into props, and the props struct.
|
||||
/// It does not return any [`Item`]s inside the struct or function.
|
||||
pub trait DeserializerOutput: ToTokens {}
|
||||
|
||||
impl<T: ToTokens> DeserializerOutput for T {}
|
||||
|
||||
/// The args passed to a [`ComponentBody`] when deserializing it.
|
||||
///
|
||||
/// It's also the struct that does the deserializing.
|
||||
/// It's called "DeserializerArgs", not "Deserializer". Why?
|
||||
/// Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which
|
||||
/// takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer.
|
||||
pub trait DeserializerArgs<TOutput>: Clone
|
||||
where
|
||||
TOutput: ToTokens,
|
||||
{
|
||||
// There's a lot of Results out there... let's make sure that this is a syn::Result.
|
||||
// Let's also make sure there's not a warning.
|
||||
/// Creates a [`ToTokens`] struct from the `self` args and a [`ComponentBody`].
|
||||
/// The [`ComponentBody::deserialize`] provides a cleaner way of calling this function.
|
||||
#[allow(unused_qualifications)]
|
||||
fn to_output(&self, component_body: &ComponentBody) -> syn::Result<TOutput>;
|
||||
}
|
||||
|
||||
pub trait TypeHelper {
|
||||
fn get_path() -> Path;
|
||||
fn get_path_string() -> String {
|
||||
Self::get_path().to_token_stream().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TypeHelper for Scope<'a> {
|
||||
fn get_path() -> Path {
|
||||
parse_quote!(::dioxus::core::Scope)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TypeHelper for Element<'a> {
|
||||
fn get_path() -> Path {
|
||||
parse_quote!(::dioxus::core::Element)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
use crate::component_body::{ComponentBody, DeserializerArgs};
|
||||
use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs;
|
||||
use constcat::concat;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{quote, ToTokens, TokenStreamExt};
|
||||
use syn::*;
|
||||
|
||||
pub(crate) const COMPONENT_ARG_CASE_CHECK_ERROR: &str = concat!(
|
||||
"This component does not use PascalCase. \
|
||||
To ignore this check, pass the \"",
|
||||
crate::COMPONENT_ARG_CASE_CHECK_OFF,
|
||||
"\" argument, like so: #[component(",
|
||||
crate::COMPONENT_ARG_CASE_CHECK_OFF,
|
||||
")]"
|
||||
);
|
||||
|
||||
const INNER_FN_NAME: &str = "__dx_inner_comp";
|
||||
|
||||
fn get_out_comp_fn(orig_comp_fn: &ItemFn, cx_pat: &Pat) -> ItemFn {
|
||||
let inner_comp_ident = Ident::new(INNER_FN_NAME, orig_comp_fn.sig.ident.span());
|
||||
|
||||
let inner_comp_fn = ItemFn {
|
||||
sig: Signature {
|
||||
ident: inner_comp_ident.clone(),
|
||||
..orig_comp_fn.sig.clone()
|
||||
},
|
||||
..orig_comp_fn.clone()
|
||||
};
|
||||
|
||||
ItemFn {
|
||||
block: parse_quote! {
|
||||
{
|
||||
#[warn(non_snake_case)]
|
||||
#[allow(clippy::inline_always)]
|
||||
#[inline(always)]
|
||||
#inner_comp_fn
|
||||
#inner_comp_ident (#cx_pat)
|
||||
}
|
||||
},
|
||||
..orig_comp_fn.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The args and deserializing implementation for the [`crate::component`] macro.
|
||||
#[derive(Clone)]
|
||||
pub struct ComponentDeserializerArgs {
|
||||
pub case_check: bool,
|
||||
}
|
||||
|
||||
/// The output fields and [`ToTokens`] implementation for the [`crate::component`] macro.
|
||||
#[derive(Clone)]
|
||||
pub struct ComponentDeserializerOutput {
|
||||
pub comp_fn: ItemFn,
|
||||
pub props_struct: Option<ItemStruct>,
|
||||
}
|
||||
|
||||
impl ToTokens for ComponentDeserializerOutput {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||
let comp_fn = &self.comp_fn;
|
||||
let props_struct = &self.props_struct;
|
||||
|
||||
tokens.append_all(quote! {
|
||||
#props_struct
|
||||
#[allow(non_snake_case)]
|
||||
#comp_fn
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializerArgs<ComponentDeserializerOutput> for ComponentDeserializerArgs {
|
||||
fn to_output(&self, component_body: &ComponentBody) -> Result<ComponentDeserializerOutput> {
|
||||
let Signature { ident, .. } = &component_body.item_fn.sig;
|
||||
|
||||
if self.case_check && !is_pascal_case(&ident.to_string()) {
|
||||
return Err(Error::new(ident.span(), COMPONENT_ARG_CASE_CHECK_ERROR));
|
||||
}
|
||||
|
||||
if component_body.has_extra_args {
|
||||
Self::deserialize_with_props(component_body)
|
||||
} else {
|
||||
Ok(Self::deserialize_no_props(component_body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ComponentDeserializerArgs {
|
||||
fn deserialize_no_props(component_body: &ComponentBody) -> ComponentDeserializerOutput {
|
||||
let ComponentBody {
|
||||
item_fn,
|
||||
cx_pat_type,
|
||||
..
|
||||
} = component_body;
|
||||
let cx_pat = &cx_pat_type.pat;
|
||||
|
||||
let comp_fn = get_out_comp_fn(item_fn, cx_pat);
|
||||
|
||||
ComponentDeserializerOutput {
|
||||
comp_fn,
|
||||
props_struct: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_with_props(
|
||||
component_body: &ComponentBody,
|
||||
) -> Result<ComponentDeserializerOutput> {
|
||||
let ComponentBody {
|
||||
item_fn,
|
||||
cx_pat_type,
|
||||
..
|
||||
} = component_body;
|
||||
let cx_pat = &cx_pat_type.pat;
|
||||
|
||||
let comp_parsed = match parse2::<ComponentBody>(quote!(#item_fn)) {
|
||||
Ok(comp_body) => comp_body,
|
||||
Err(e) => {
|
||||
return Err(Error::new(
|
||||
e.span(),
|
||||
format!(
|
||||
"This is probably a bug in our code, please report it! Error: {}",
|
||||
e
|
||||
),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let inlined_props_output = comp_parsed.deserialize(InlinePropsDeserializerArgs {})?;
|
||||
let props_struct = inlined_props_output.props_struct;
|
||||
let props_fn = inlined_props_output.comp_fn;
|
||||
|
||||
let comp_fn = get_out_comp_fn(&props_fn, cx_pat);
|
||||
|
||||
Ok(ComponentDeserializerOutput {
|
||||
comp_fn,
|
||||
props_struct: Some(props_struct),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn is_pascal_case(input: &str) -> bool {
|
||||
let mut is_next_lowercase = false;
|
||||
|
||||
for c in input.chars() {
|
||||
let is_upper = c.is_ascii_uppercase();
|
||||
|
||||
if (c == '_') || (is_upper && is_next_lowercase) {
|
||||
return false;
|
||||
}
|
||||
|
||||
is_next_lowercase = is_upper;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
use crate::component_body::{ComponentBody, DeserializerArgs};
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{quote, ToTokens, TokenStreamExt};
|
||||
use syn::token::Comma;
|
||||
use syn::{punctuated::Punctuated, *};
|
||||
|
||||
/// The args and deserializing implementation for the [`crate::inline_props`] macro.
|
||||
#[derive(Clone)]
|
||||
pub struct InlinePropsDeserializerArgs;
|
||||
|
||||
/// The output fields and [`ToTokens`] implementation for the [`crate::inline_props`] macro.
|
||||
#[derive(Clone)]
|
||||
pub struct InlinePropsDeserializerOutput {
|
||||
pub comp_fn: ItemFn,
|
||||
pub props_struct: ItemStruct,
|
||||
}
|
||||
|
||||
impl ToTokens for InlinePropsDeserializerOutput {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream2) {
|
||||
let function = &self.comp_fn;
|
||||
let props_struct = &self.props_struct;
|
||||
|
||||
tokens.append_all(quote! {
|
||||
#function
|
||||
#props_struct
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializerArgs<InlinePropsDeserializerOutput> for InlinePropsDeserializerArgs {
|
||||
fn to_output(&self, component_body: &ComponentBody) -> Result<InlinePropsDeserializerOutput> {
|
||||
Ok(InlinePropsDeserializerOutput {
|
||||
comp_fn: get_function(component_body),
|
||||
props_struct: get_props_struct(component_body),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
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_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(¬e, 1, '\n').replace('\n', " ");
|
||||
let note = keep_up_to_n_consecutive_chars(¬e, 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
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! This module contains all [`ComponentBody`](crate::component_body::ComponentBody) deserializers.
|
||||
|
||||
pub mod component;
|
||||
pub mod inline_props;
|
||||
@@ -1,185 +0,0 @@
|
||||
use proc_macro2::{Span, TokenStream as TokenStream2};
|
||||
use quote::{quote, ToTokens, TokenStreamExt};
|
||||
use syn::{
|
||||
parse::{Parse, ParseStream},
|
||||
punctuated::Punctuated,
|
||||
*,
|
||||
};
|
||||
|
||||
pub struct InlinePropsBody {
|
||||
pub attrs: Vec<Attribute>,
|
||||
pub vis: syn::Visibility,
|
||||
pub maybe_async: Option<Token![async]>,
|
||||
pub fn_token: Token![fn],
|
||||
pub ident: Ident,
|
||||
pub cx_token: Box<Pat>,
|
||||
pub generics: Generics,
|
||||
pub paren_token: token::Paren,
|
||||
pub inputs: Punctuated<FnArg, Token![,]>,
|
||||
// pub fields: FieldsNamed,
|
||||
pub output: ReturnType,
|
||||
pub where_clause: Option<WhereClause>,
|
||||
pub block: Box<Block>,
|
||||
}
|
||||
|
||||
/// The custom rusty variant of parsing rsx!
|
||||
impl Parse for InlinePropsBody {
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
let attrs: Vec<Attribute> = input.call(Attribute::parse_outer)?;
|
||||
let maybe_async: Option<Token![async]> = input.parse().ok();
|
||||
let vis: Visibility = input.parse()?;
|
||||
|
||||
let fn_token = input.parse()?;
|
||||
let ident = input.parse()?;
|
||||
let generics: Generics = input.parse()?;
|
||||
|
||||
let content;
|
||||
let paren_token = syn::parenthesized!(content in input);
|
||||
|
||||
let first_arg: FnArg = content.parse()?;
|
||||
let cx_token = {
|
||||
match first_arg {
|
||||
FnArg::Receiver(_) => panic!("first argument must not be a receiver argument"),
|
||||
FnArg::Typed(f) => f.pat,
|
||||
}
|
||||
};
|
||||
|
||||
let _: Result<Token![,]> = content.parse();
|
||||
|
||||
let inputs = syn::punctuated::Punctuated::parse_terminated(&content)?;
|
||||
|
||||
let output = input.parse()?;
|
||||
|
||||
let where_clause = input
|
||||
.peek(syn::token::Where)
|
||||
.then(|| input.parse())
|
||||
.transpose()?;
|
||||
|
||||
let block = input.parse()?;
|
||||
|
||||
Ok(Self {
|
||||
vis,
|
||||
maybe_async,
|
||||
fn_token,
|
||||
ident,
|
||||
generics,
|
||||
paren_token,
|
||||
inputs,
|
||||
output,
|
||||
where_clause,
|
||||
block,
|
||||
cx_token,
|
||||
attrs,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize the same way, regardless of flavor
|
||||
impl ToTokens for InlinePropsBody {
|
||||
fn to_tokens(&self, out_tokens: &mut TokenStream2) {
|
||||
let Self {
|
||||
vis,
|
||||
ident,
|
||||
generics,
|
||||
inputs,
|
||||
output,
|
||||
where_clause,
|
||||
block,
|
||||
cx_token,
|
||||
attrs,
|
||||
maybe_async,
|
||||
..
|
||||
} = self;
|
||||
|
||||
let fields = inputs.iter().map(|f| {
|
||||
quote! { #vis #f }
|
||||
});
|
||||
|
||||
let struct_name = Ident::new(&format!("{ident}Props"), Span::call_site());
|
||||
|
||||
let field_names = inputs.iter().filter_map(|f| match f {
|
||||
FnArg::Receiver(_) => todo!(),
|
||||
FnArg::Typed(t) => Some(&t.pat),
|
||||
});
|
||||
|
||||
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
|
||||
Some(lt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let modifiers = if first_lifetime.is_some() {
|
||||
quote! { #[derive(Props)] }
|
||||
} else {
|
||||
quote! { #[derive(Props, PartialEq)] }
|
||||
};
|
||||
|
||||
let (scope_lifetime, fn_generics, struct_generics) = if let Some(lt) = first_lifetime {
|
||||
let struct_generics: Punctuated<_, token::Comma> = generics
|
||||
.params
|
||||
.iter()
|
||||
.map(|it| match it {
|
||||
GenericParam::Type(tp) => {
|
||||
let mut tp = tp.clone();
|
||||
tp.bounds.push(parse_quote!( 'a ));
|
||||
|
||||
GenericParam::Type(tp)
|
||||
}
|
||||
_ => it.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
(
|
||||
quote! { #lt, },
|
||||
generics.clone(),
|
||||
quote! { <#struct_generics> },
|
||||
)
|
||||
} else {
|
||||
let lifetime: LifetimeParam = parse_quote! { 'a };
|
||||
|
||||
let mut fn_generics = generics.clone();
|
||||
fn_generics
|
||||
.params
|
||||
.insert(0, GenericParam::Lifetime(lifetime.clone()));
|
||||
|
||||
(quote! { #lifetime, }, fn_generics, quote! { #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
|
||||
};
|
||||
|
||||
out_tokens.append_all(quote! {
|
||||
#modifiers
|
||||
#[allow(non_camel_case_types)]
|
||||
#vis struct #struct_name #struct_generics
|
||||
#where_clause
|
||||
{
|
||||
#(#fields),*
|
||||
}
|
||||
|
||||
#(#attrs)*
|
||||
#maybe_async #vis fn #ident #fn_generics (#cx_token: Scope<#scope_lifetime #struct_name #generics_no_bounds>) #output
|
||||
#where_clause
|
||||
{
|
||||
let #struct_name { #(#field_names),* } = &#cx_token.props;
|
||||
#block
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,23 @@
|
||||
#![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;
|
||||
use syn::parse_macro_input;
|
||||
use syn::parse::Parser;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::{parse_macro_input, Path, Token};
|
||||
|
||||
mod inlineprops;
|
||||
mod component_body;
|
||||
mod component_body_deserializers;
|
||||
mod props;
|
||||
mod utils;
|
||||
|
||||
// mod rsx;
|
||||
use crate::component_body::ComponentBody;
|
||||
use crate::component_body_deserializers::component::ComponentDeserializerArgs;
|
||||
use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs;
|
||||
use dioxus_rsx as rsx;
|
||||
|
||||
#[proc_macro]
|
||||
@@ -18,7 +29,7 @@ pub fn format_args_f(input: TokenStream) -> TokenStream {
|
||||
}
|
||||
|
||||
#[proc_macro_derive(Props, attributes(props))]
|
||||
pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
pub fn derive_typed_builder(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as syn::DeriveInput);
|
||||
match props::impl_my_derive(&input) {
|
||||
Ok(output) => output.into(),
|
||||
@@ -37,7 +48,7 @@ pub fn rsx(s: TokenStream) -> TokenStream {
|
||||
|
||||
/// The render! macro makes it easy for developers to write jsx-style markup in their components.
|
||||
///
|
||||
/// The render macro automatically renders rsx - making it unhygenic.
|
||||
/// The render macro automatically renders rsx - making it unhygienic.
|
||||
#[proc_macro]
|
||||
pub fn render(s: TokenStream) -> TokenStream {
|
||||
match syn::parse::<rsx::CallBody>(s) {
|
||||
@@ -55,7 +66,7 @@ pub fn render(s: TokenStream) -> TokenStream {
|
||||
/// you would be repeating a lot of the usual Rust boilerplate.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// ```rust,ignore
|
||||
/// #[inline_props]
|
||||
/// fn app(cx: Scope, bob: String) -> Element {
|
||||
/// cx.render(rsx!("hello, {bob}"))
|
||||
@@ -73,9 +84,118 @@ pub fn render(s: TokenStream) -> TokenStream {
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_attribute]
|
||||
pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
match syn::parse::<inlineprops::InlinePropsBody>(s) {
|
||||
#[deprecated(note = "Use `#[component]` instead.")]
|
||||
pub fn inline_props(_args: TokenStream, s: TokenStream) -> TokenStream {
|
||||
let comp_body = parse_macro_input!(s as ComponentBody);
|
||||
|
||||
match comp_body.deserialize(InlinePropsDeserializerArgs {}) {
|
||||
Err(e) => e.to_compile_error().into(),
|
||||
Ok(s) => s.to_token_stream().into(),
|
||||
Ok(output) => output.to_token_stream().into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const COMPONENT_ARG_CASE_CHECK_OFF: &str = "no_case_check";
|
||||
|
||||
/// Streamlines component creation.
|
||||
/// This is the recommended way of creating components,
|
||||
/// though you might want lower-level control with more advanced uses.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `no_case_check` - Doesn't enforce `PascalCase` on your component names.
|
||||
/// **This will be removed/deprecated in a future update in favor of a more complete Clippy-backed linting system.**
|
||||
/// The reasoning behind this is that Clippy allows more robust and powerful lints, whereas
|
||||
/// macros are extremely limited.
|
||||
///
|
||||
/// # Features
|
||||
/// This attribute:
|
||||
/// * Enforces that your component uses `PascalCase`.
|
||||
/// No warnings are generated for the `PascalCase`
|
||||
/// function name, but everything else will still raise a warning if it's incorrectly `PascalCase`.
|
||||
/// Does not disable warnings anywhere else, so if you, for example,
|
||||
/// accidentally don't use `snake_case`
|
||||
/// for a variable name in the function, the compiler will still warn you.
|
||||
/// * Automatically uses `#[inline_props]` if there's more than 1 parameter in the function.
|
||||
/// * Verifies the validity of your component.
|
||||
/// E.g. if it has a [`Scope`](dioxus_core::Scope) argument.
|
||||
/// Notes:
|
||||
/// * This doesn't work 100% of the time, because of macro limitations.
|
||||
/// * Provides helpful messages if your component is not correct.
|
||||
/// Possible bugs (please, report these!):
|
||||
/// * There might be bugs where it incorrectly *denies* validity.
|
||||
/// This is bad as it means that you can't use the attribute or you have to change the component.
|
||||
/// * There might be bugs where it incorrectly *confirms* validity.
|
||||
/// You will still know if the component is invalid once you use it,
|
||||
/// but the error might be less helpful.
|
||||
///
|
||||
/// # Examples
|
||||
/// * Without props:
|
||||
/// ```rust,ignore
|
||||
/// #[component]
|
||||
/// fn GreetBob(cx: Scope) -> Element {
|
||||
/// render! { "hello, bob" }
|
||||
/// }
|
||||
///
|
||||
/// // is equivalent to
|
||||
///
|
||||
/// #[allow(non_snake_case)]
|
||||
/// fn GreetBob(cx: Scope) -> Element {
|
||||
/// #[warn(non_snake_case)]
|
||||
/// #[inline(always)]
|
||||
/// fn __dx_inner_comp(cx: Scope) -> Element {
|
||||
/// render! { "hello, bob" }
|
||||
/// }
|
||||
/// // There's no function call overhead since __dx_inner_comp has the #[inline(always)] attribute,
|
||||
/// // so don't worry about performance.
|
||||
/// __dx_inner_comp(cx)
|
||||
/// }
|
||||
/// ```
|
||||
/// * With props:
|
||||
/// ```rust,ignore
|
||||
/// #[component(no_case_check)]
|
||||
/// fn GreetPerson(cx: Scope, person: String) -> Element {
|
||||
/// render! { "hello, {person}" }
|
||||
/// }
|
||||
///
|
||||
/// // is equivalent to
|
||||
///
|
||||
/// #[derive(Props, PartialEq)]
|
||||
/// #[allow(non_camel_case_types)]
|
||||
/// struct GreetPersonProps {
|
||||
/// person: String,
|
||||
/// }
|
||||
///
|
||||
/// #[allow(non_snake_case)]
|
||||
/// fn GreetPerson<'a>(cx: Scope<'a, GreetPersonProps>) -> Element {
|
||||
/// #[warn(non_snake_case)]
|
||||
/// #[inline(always)]
|
||||
/// fn __dx_inner_comp<'a>(cx: Scope<'a, GreetPersonProps>e) -> Element {
|
||||
/// let GreetPersonProps { person } = &cx.props;
|
||||
/// {
|
||||
/// render! { "hello, {person}" }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// __dx_inner_comp(cx)
|
||||
/// }
|
||||
/// ```
|
||||
// TODO: Maybe add an option to input a custom component name through the args.
|
||||
// I think that's unnecessary, but there might be some scenario where it could be useful.
|
||||
#[proc_macro_attribute]
|
||||
pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let component_body = parse_macro_input!(input as ComponentBody);
|
||||
let case_check = match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
|
||||
Err(e) => return e.to_compile_error().into(),
|
||||
Ok(args) => {
|
||||
if let Some(first) = args.first() {
|
||||
!first.is_ident(COMPONENT_ARG_CASE_CHECK_OFF)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match component_body.deserialize(ComponentDeserializerArgs { case_check }) {
|
||||
Err(e) => e.to_compile_error().into(),
|
||||
Ok(output) => output.to_token_stream().into(),
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
//!
|
||||
//! However, it has been adopted to fit the Dioxus Props builder pattern.
|
||||
//!
|
||||
//! For dioxus, we make a few changes:
|
||||
//! - [ ] automatically implement Into<Option> on the setters (IE the strip setter option)
|
||||
//! - [ ] automatically implement a default of none for optional fields (those explicitly wrapped with Option<T>)
|
||||
//! For Dioxus, we make a few changes:
|
||||
//! - [ ] Automatically implement Into<Option> on the setters (IE the strip setter option)
|
||||
//! - [ ] Automatically implement a default of none for optional fields (those explicitly wrapped with Option<T>)
|
||||
|
||||
use proc_macro2::TokenStream;
|
||||
|
||||
@@ -194,8 +194,9 @@ mod field_info {
|
||||
|
||||
// children field is automatically defaulted to None
|
||||
if name == "children" {
|
||||
builder_attr.default =
|
||||
Some(syn::parse(quote!(Default::default()).into()).unwrap());
|
||||
builder_attr.default = Some(
|
||||
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
// auto detect optional
|
||||
@@ -204,8 +205,9 @@ mod field_info {
|
||||
&& type_from_inside_option(&field.ty, true).is_some();
|
||||
if !builder_attr.strip_option && strip_option_auto {
|
||||
builder_attr.strip_option = true;
|
||||
builder_attr.default =
|
||||
Some(syn::parse(quote!(Default::default()).into()).unwrap());
|
||||
builder_attr.default = Some(
|
||||
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(FieldInfo {
|
||||
@@ -213,7 +215,7 @@ mod field_info {
|
||||
name,
|
||||
generic_ident: syn::Ident::new(
|
||||
&format!("__{}", strip_raw_ident_prefix(name.to_string())),
|
||||
proc_macro2::Span::call_site(),
|
||||
name.span(),
|
||||
),
|
||||
ty: &field.ty,
|
||||
builder_attr,
|
||||
@@ -241,10 +243,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)]
|
||||
@@ -345,14 +343,18 @@ mod field_info {
|
||||
.ok_or_else(|| Error::new_spanned(&path, "Expected identifier"))?;
|
||||
match name.as_str() {
|
||||
"default" => {
|
||||
self.default =
|
||||
Some(syn::parse(quote!(Default::default()).into()).unwrap());
|
||||
self.default = Some(
|
||||
syn::parse(quote!(::core::default::Default::default()).into())
|
||||
.unwrap(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
"optional" => {
|
||||
self.default =
|
||||
Some(syn::parse(quote!(Default::default()).into()).unwrap());
|
||||
self.default = Some(
|
||||
syn::parse(quote!(::core::default::Default::default()).into())
|
||||
.unwrap(),
|
||||
);
|
||||
self.strip_option = true;
|
||||
Ok(())
|
||||
}
|
||||
@@ -505,15 +507,12 @@ mod struct_info {
|
||||
.map(|(i, f)| FieldInfo::new(i, f, builder_attr.field_defaults.clone()))
|
||||
.collect::<Result<_, _>>()?,
|
||||
builder_attr,
|
||||
builder_name: syn::Ident::new(&builder_name, proc_macro2::Span::call_site()),
|
||||
builder_name: syn::Ident::new(&builder_name, ast.ident.span()),
|
||||
conversion_helper_trait_name: syn::Ident::new(
|
||||
&format!("{builder_name}_Optional"),
|
||||
proc_macro2::Span::call_site(),
|
||||
),
|
||||
core: syn::Ident::new(
|
||||
&format!("{builder_name}_core"),
|
||||
proc_macro2::Span::call_site(),
|
||||
ast.ident.span(),
|
||||
),
|
||||
core: syn::Ident::new(&format!("{builder_name}_core"), ast.ident.span()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -548,18 +547,16 @@ mod struct_info {
|
||||
let generics_with_empty = modify_types_generics_hack(&ty_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),
|
||||
@@ -630,11 +627,11 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
Ok(quote! {
|
||||
impl #impl_generics #name #ty_generics #where_clause {
|
||||
#[doc = #builder_method_doc]
|
||||
#[allow(dead_code)]
|
||||
#[allow(dead_code, clippy::type_complexity)]
|
||||
#vis fn builder() -> #builder_name #generics_with_empty {
|
||||
#builder_name {
|
||||
fields: #empties_tuple,
|
||||
_phantom: core::default::Default::default(),
|
||||
_phantom: ::core::default::Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -651,12 +648,12 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
fields: self.fields.clone(),
|
||||
_phantom: Default::default(),
|
||||
_phantom: ::core::default::Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl #impl_generics dioxus::prelude::Properties for #name #ty_generics
|
||||
impl #impl_generics ::dioxus::prelude::Properties for #name #ty_generics
|
||||
#b_generics_where_extras_predicates
|
||||
{
|
||||
type Builder = #builder_name #generics_with_empty;
|
||||
@@ -698,6 +695,14 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
}
|
||||
|
||||
pub fn field_impl(&self, field: &FieldInfo) -> Result<TokenStream, Error> {
|
||||
let FieldInfo {
|
||||
name: field_name,
|
||||
ty: field_type,
|
||||
..
|
||||
} = 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;
|
||||
@@ -712,11 +717,6 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
});
|
||||
let reconstructing = self.included_fields().map(|f| f.name);
|
||||
|
||||
let FieldInfo {
|
||||
name: field_name,
|
||||
ty: field_type,
|
||||
..
|
||||
} = field;
|
||||
let mut ty_generics: Vec<syn::GenericArgument> = self
|
||||
.generics
|
||||
.params
|
||||
@@ -779,31 +779,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!(
|
||||
@@ -811,7 +796,7 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
builder_name,
|
||||
strip_raw_ident_prefix(field_name.to_string())
|
||||
),
|
||||
proc_macro2::Span::call_site(),
|
||||
builder_name.span(),
|
||||
);
|
||||
let repeated_fields_error_message = format!("Repeated field {field_name}");
|
||||
|
||||
@@ -819,6 +804,7 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
#[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;
|
||||
@@ -837,6 +823,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
|
||||
}
|
||||
@@ -930,7 +917,7 @@ Finally, call `.build()` to create the instance of `{name}`.
|
||||
builder_name,
|
||||
strip_raw_ident_prefix(field_name.to_string())
|
||||
),
|
||||
proc_macro2::Span::call_site(),
|
||||
builder_name.span(),
|
||||
);
|
||||
let early_build_error_message = format!("Missing required field {field_name}");
|
||||
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ slab = { workspace = true }
|
||||
futures-channel = { workspace = true }
|
||||
|
||||
smallbox = "0.8.1"
|
||||
log = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
|
||||
# Serialize the Edits for use in Webview/Liveview instances
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
fn main() {}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
let count = vec![1, 2, 3];
|
||||
|
||||
render! {
|
||||
unsafe_child_component {
|
||||
borrowed: &count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Props)]
|
||||
struct Testing<'a> {
|
||||
borrowed: &'a Vec<u32>,
|
||||
}
|
||||
|
||||
fn unsafe_child_component<'a>(cx: Scope<'a, Testing<'a>>) -> Element<'a> {
|
||||
cx.render(rsx! {
|
||||
div { "{cx.props.borrowed:?}" }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
error[E0515]: cannot return value referencing local variable `count`
|
||||
--> compile_tests/props_safety_temporary_values.rs:8:5
|
||||
|
|
||||
8 | / render! {
|
||||
9 | | unsafe_child_component {
|
||||
10 | | borrowed: &count
|
||||
| | ------ `count` is borrowed here
|
||||
11 | | }
|
||||
12 | | }
|
||||
| |_____^ returns a value referencing data owned by the current function
|
||||
|
|
||||
= note: this error originates in the macro `render` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
@@ -68,7 +68,7 @@ unsafe impl<'a, P> AnyProps<'a> for VProps<'a, P> {
|
||||
Ok(None) => RenderReturn::default(),
|
||||
Err(err) => {
|
||||
let component_name = cx.name();
|
||||
log::error!("Error while rendering component `{component_name}`: {err:?}");
|
||||
tracing::error!("Error while rendering component `{component_name}`: {err:?}");
|
||||
RenderReturn::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ impl ElementRef {
|
||||
Self {
|
||||
template: None,
|
||||
path: ElementPath::Root(0),
|
||||
scope: ScopeId(0),
|
||||
scope: ScopeId::ROOT,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ impl VirtualDom {
|
||||
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(0));
|
||||
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
|
||||
@@ -164,17 +164,11 @@ impl VirtualDom {
|
||||
});
|
||||
|
||||
// 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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
}
|
||||
@@ -87,8 +87,12 @@ impl<'b> VirtualDom {
|
||||
}
|
||||
}
|
||||
|
||||
// Intialize the root nodes slice
|
||||
*node.root_ids.borrow_mut() = vec![ElementId(0); node.template.get().roots.len()];
|
||||
// Initialize the root nodes slice
|
||||
{
|
||||
let mut nodes_mut = node.root_ids.borrow_mut();
|
||||
let len = node.template.get().roots.len();
|
||||
nodes_mut.resize(len, ElementId::default());
|
||||
};
|
||||
|
||||
// The best renderers will have templates prehydrated and registered
|
||||
// Just in case, let's create the template using instructions anyways
|
||||
|
||||
@@ -15,6 +15,7 @@ use DynamicNode::*;
|
||||
|
||||
impl<'b> VirtualDom {
|
||||
pub(super) fn diff_scope(&mut self, scope: ScopeId) {
|
||||
self.runtime.scope_stack.borrow_mut().push(scope);
|
||||
let scope_state = &mut self.get_scope(scope).unwrap();
|
||||
unsafe {
|
||||
// Load the old and new bump arenas
|
||||
@@ -45,6 +46,7 @@ impl<'b> VirtualDom {
|
||||
(Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
|
||||
};
|
||||
}
|
||||
self.runtime.scope_stack.borrow_mut().pop();
|
||||
}
|
||||
|
||||
fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
|
||||
@@ -126,7 +128,13 @@ impl<'b> VirtualDom {
|
||||
});
|
||||
|
||||
// Make sure the roots get transferred over while we're here
|
||||
*right_template.root_ids.borrow_mut() = left_template.root_ids.borrow().clone();
|
||||
{
|
||||
let mut right = right_template.root_ids.borrow_mut();
|
||||
right.clear();
|
||||
for &element in left_template.root_ids.borrow().iter() {
|
||||
right.push(element);
|
||||
}
|
||||
}
|
||||
|
||||
let root_ids = right_template.root_ids.borrow();
|
||||
|
||||
@@ -188,7 +196,8 @@ impl<'b> VirtualDom {
|
||||
right.scope.set(Some(scope_id));
|
||||
|
||||
// copy out the box for both
|
||||
let old = self.scopes[scope_id.0].props.as_ref();
|
||||
let old_scope = &self.scopes[scope_id.0];
|
||||
let old = old_scope.props.as_ref();
|
||||
let new: Box<dyn AnyProps> = right.props.take().unwrap();
|
||||
let new: Box<dyn AnyProps> = unsafe { std::mem::transmute(new) };
|
||||
|
||||
@@ -196,6 +205,11 @@ impl<'b> VirtualDom {
|
||||
// The target scopestate still has the reference to the old props, so there's no need to update anything
|
||||
// This also implicitly drops the new props since they're not used
|
||||
if left.static_props && unsafe { old.as_ref().unwrap().memoize(new.as_ref()) } {
|
||||
tracing::trace!(
|
||||
"Memoized props for component {:#?} ({})",
|
||||
scope_id,
|
||||
old_scope.context().name
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -569,8 +583,7 @@ impl<'b> VirtualDom {
|
||||
}
|
||||
|
||||
// 4. Compute the LIS of this list
|
||||
let mut lis_sequence = Vec::default();
|
||||
lis_sequence.reserve(new_index_to_old_index.len());
|
||||
let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
|
||||
|
||||
let mut predecessors = vec![0; new_index_to_old_index.len()];
|
||||
let mut starts = vec![0; new_index_to_old_index.len()];
|
||||
|
||||
@@ -49,17 +49,16 @@ impl ErrorBoundary {
|
||||
/// A trait to allow results to be thrown upwards to the nearest Error Boundary
|
||||
///
|
||||
/// The canonical way of using this trait is to throw results from hooks, aborting rendering
|
||||
/// through question mark synax. The throw method returns an option that evalutes to None
|
||||
/// through question mark syntax. The throw method returns an option that evaluates to None
|
||||
/// if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
/// ```rust, ignore
|
||||
///
|
||||
/// #[inline_props]
|
||||
/// fn app(cx: Scope, count: String) -> Element {
|
||||
/// #[component]
|
||||
/// fn App(cx: Scope, count: String) -> Element {
|
||||
/// let id: i32 = count.parse().throw(cx)?;
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
@@ -71,9 +70,9 @@ pub trait Throw<S = ()>: Sized {
|
||||
/// The value that will be returned in if the given value is `Ok`.
|
||||
type Out;
|
||||
|
||||
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
|
||||
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
@@ -83,9 +82,8 @@ pub trait Throw<S = ()>: Sized {
|
||||
///
|
||||
///
|
||||
/// ```rust, ignore
|
||||
///
|
||||
/// #[inline_props]
|
||||
/// fn app(cx: Scope, count: String) -> Element {
|
||||
/// #[component]
|
||||
/// fn App(cx: Scope, count: String) -> Element {
|
||||
/// let id: i32 = count.parse().throw(cx)?;
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
@@ -95,9 +93,9 @@ pub trait Throw<S = ()>: Sized {
|
||||
/// ```
|
||||
fn throw(self, cx: &ScopeState) -> Option<Self::Out>;
|
||||
|
||||
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
|
||||
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
|
||||
///
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
|
||||
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
|
||||
///
|
||||
/// The call stack is saved for this component and provided to the error boundary
|
||||
///
|
||||
@@ -107,9 +105,8 @@ pub trait Throw<S = ()>: Sized {
|
||||
///
|
||||
///
|
||||
/// ```rust, ignore
|
||||
///
|
||||
/// #[inline_props]
|
||||
/// fn app(cx: Scope, count: String) -> Element {
|
||||
/// #[component]
|
||||
/// fn App(cx: Scope, count: String) -> Element {
|
||||
/// let id: i32 = count.parse().throw(cx)?;
|
||||
///
|
||||
/// cx.render(rsx! {
|
||||
|
||||
@@ -107,8 +107,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.
|
||||
@@ -118,7 +116,7 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// rsx!{
|
||||
/// MyComponent { onclick: move |evt| log::info!("clicked") }
|
||||
/// MyComponent { onclick: move |evt| tracing::debug!("clicked") }
|
||||
/// }
|
||||
///
|
||||
/// #[derive(Props)]
|
||||
@@ -143,7 +141,7 @@ pub struct EventHandler<'bump, T = ()> {
|
||||
impl<T> Default for EventHandler<'_, T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
origin: ScopeId(0),
|
||||
origin: ScopeId::ROOT,
|
||||
callback: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,37 @@ use crate::{innerlude::VNode, ScopeState};
|
||||
///
|
||||
///
|
||||
/// ```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);
|
||||
/// ```
|
||||
|
||||
@@ -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,6 +34,7 @@ pub(crate) mod innerlude {
|
||||
pub use crate::nodes::RenderReturn;
|
||||
pub use crate::nodes::*;
|
||||
pub use crate::properties::*;
|
||||
pub use crate::runtime::{Runtime, RuntimeGuard};
|
||||
pub use crate::scheduler::*;
|
||||
pub use crate::scope_context::*;
|
||||
pub use crate::scopes::*;
|
||||
@@ -88,9 +91,9 @@ pub mod prelude {
|
||||
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context,
|
||||
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, Scope, ScopeId, ScopeState, Scoped, TaskId, Template, TemplateAttribute,
|
||||
TemplateNode, Throw, VNode, VirtualDom,
|
||||
Component, Element, Event, EventHandler, Fragment, IntoAttributeValue, IntoDynNode,
|
||||
LazyNodes, Properties, Runtime, RuntimeGuard, Scope, ScopeId, ScopeState, Scoped, TaskId,
|
||||
Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+16
-10
@@ -54,7 +54,7 @@ pub struct VNode<'a> {
|
||||
|
||||
/// The IDs for the roots of this template - to be used when moving the template around and removing it from
|
||||
/// the actual Dom
|
||||
pub root_ids: RefCell<Vec<ElementId>>,
|
||||
pub root_ids: RefCell<bumpalo::collections::Vec<'a, ElementId>>,
|
||||
|
||||
/// The dynamic parts of the template
|
||||
pub dynamic_nodes: &'a [DynamicNode<'a>],
|
||||
@@ -65,11 +65,11 @@ pub struct VNode<'a> {
|
||||
|
||||
impl<'a> VNode<'a> {
|
||||
/// Create a template with no nodes that will be skipped over during diffing
|
||||
pub fn empty() -> Element<'a> {
|
||||
pub fn empty(cx: &'a ScopeState) -> Element<'a> {
|
||||
Some(VNode {
|
||||
key: None,
|
||||
parent: None,
|
||||
root_ids: Default::default(),
|
||||
root_ids: RefCell::new(bumpalo::collections::Vec::new_in(cx.bump())),
|
||||
dynamic_nodes: &[],
|
||||
dynamic_attrs: &[],
|
||||
template: Cell::new(Template {
|
||||
@@ -691,14 +691,14 @@ impl<'a> IntoDynNode<'a> for &Element<'a> {
|
||||
|
||||
impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
|
||||
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
|
||||
DynamicNode::Fragment(cx.bump().alloc([self.call(cx)]))
|
||||
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> {
|
||||
DynamicNode::Text(VText {
|
||||
value: bumpalo::collections::String::from_str_in(self, cx.bump()).into_bump_str(),
|
||||
value: cx.bump().alloc_str(self),
|
||||
id: Default::default(),
|
||||
})
|
||||
}
|
||||
@@ -707,7 +707,7 @@ impl<'a, 'b> IntoDynNode<'b> for &'a str {
|
||||
impl IntoDynNode<'_> for String {
|
||||
fn into_vnode(self, cx: &ScopeState) -> DynamicNode {
|
||||
DynamicNode::Text(VText {
|
||||
value: cx.bump().alloc(self),
|
||||
value: cx.bump().alloc_str(&self),
|
||||
id: Default::default(),
|
||||
})
|
||||
}
|
||||
@@ -741,16 +741,16 @@ impl<'a> IntoTemplate<'a> for VNode<'a> {
|
||||
}
|
||||
}
|
||||
impl<'a> IntoTemplate<'a> for Element<'a> {
|
||||
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
|
||||
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
|
||||
match self {
|
||||
Some(val) => val.into_template(_cx),
|
||||
_ => VNode::empty().unwrap(),
|
||||
Some(val) => val.into_template(cx),
|
||||
_ => VNode::empty(cx).unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
|
||||
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
|
||||
self.call(cx)
|
||||
cx.render(self).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -791,6 +791,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)
|
||||
|
||||
@@ -79,4 +79,5 @@ pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>)
|
||||
fn unsafe_props_fail() {
|
||||
let t = trybuild::TestCases::new();
|
||||
t.compile_fail("compile_tests/props_safety.rs");
|
||||
t.compile_fail("compile_tests/props_safety_temporary_values.rs");
|
||||
}
|
||||
@@ -41,7 +41,8 @@ where
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(crate) struct Runtime {
|
||||
/// A global runtime that is shared across all scopes that provides the async runtime and context API
|
||||
pub struct Runtime {
|
||||
pub(crate) scope_contexts: RefCell<Vec<Option<ScopeContext>>>,
|
||||
pub(crate) scheduler: Rc<Scheduler>,
|
||||
|
||||
@@ -63,6 +64,11 @@ impl Runtime {
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the current runtime
|
||||
pub fn current() -> Option<Rc<Self>> {
|
||||
RUNTIMES.with(|stack| stack.borrow().last().cloned())
|
||||
}
|
||||
|
||||
/// Create a scope context. This slab is synchronized with the scope slab.
|
||||
pub(crate) fn create_context_at(&self, id: ScopeId, context: ScopeContext) {
|
||||
let mut contexts = self.scope_contexts.borrow_mut();
|
||||
@@ -77,14 +83,14 @@ impl Runtime {
|
||||
}
|
||||
|
||||
/// Get the current scope id
|
||||
pub fn current_scope_id(&self) -> Option<ScopeId> {
|
||||
pub(crate) fn current_scope_id(&self) -> Option<ScopeId> {
|
||||
self.scope_stack.borrow().last().copied()
|
||||
}
|
||||
|
||||
/// 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
|
||||
pub fn get_context(&self, id: ScopeId) -> Option<Ref<'_, ScopeContext>> {
|
||||
pub(crate) fn get_context(&self, id: ScopeId) -> Option<Ref<'_, ScopeContext>> {
|
||||
Ref::filter_map(self.scope_contexts.borrow(), |contexts| {
|
||||
contexts.get(id.0).and_then(|f| f.as_ref())
|
||||
})
|
||||
@@ -92,10 +98,42 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct RuntimeGuard(Rc<Runtime>);
|
||||
/// A gaurd 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)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ impl VirtualDom {
|
||||
hook_idx: Default::default(),
|
||||
|
||||
borrowed_props: Default::default(),
|
||||
attributes_to_drop: Default::default(),
|
||||
attributes_to_drop_before_render: Default::default(),
|
||||
}));
|
||||
|
||||
let context =
|
||||
@@ -54,7 +54,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);
|
||||
|
||||
@@ -64,6 +64,7 @@ impl VirtualDom {
|
||||
let props: &dyn AnyProps = scope.props.as_ref().unwrap().as_ref();
|
||||
let props: &dyn AnyProps = std::mem::transmute(props);
|
||||
|
||||
let _span = tracing::trace_span!("render", scope = %scope.context().name);
|
||||
props.render(scope).extend_lifetime()
|
||||
};
|
||||
|
||||
|
||||
@@ -107,20 +107,30 @@ impl ScopeContext {
|
||||
///
|
||||
/// Clones the state if it exists.
|
||||
pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
|
||||
tracing::trace!(
|
||||
"looking for context {} ({:?}) in {}",
|
||||
std::any::type_name::<T>(),
|
||||
std::any::TypeId::of::<T>(),
|
||||
self.name
|
||||
);
|
||||
if let Some(this_ctx) = self.has_context() {
|
||||
return Some(this_ctx);
|
||||
}
|
||||
|
||||
let mut search_parent = self.parent_id;
|
||||
with_runtime(|runtime| {
|
||||
match with_runtime(|runtime: &crate::runtime::Runtime| {
|
||||
while let Some(parent_id) = search_parent {
|
||||
let parent = runtime.get_context(parent_id).unwrap();
|
||||
if let Some(shared) = parent
|
||||
.shared_contexts
|
||||
.borrow()
|
||||
.iter()
|
||||
.find_map(|any| any.downcast_ref::<T>())
|
||||
{
|
||||
tracing::trace!(
|
||||
"looking for context {} ({:?}) in {}",
|
||||
std::any::type_name::<T>(),
|
||||
std::any::TypeId::of::<T>(),
|
||||
parent.name
|
||||
);
|
||||
if let Some(shared) = parent.shared_contexts.borrow().iter().find_map(|any| {
|
||||
tracing::trace!("found context {:?}", (**any).type_id());
|
||||
any.downcast_ref::<T>()
|
||||
}) {
|
||||
return Some(shared.clone());
|
||||
}
|
||||
search_parent = parent.parent_id;
|
||||
@@ -128,6 +138,17 @@ impl ScopeContext {
|
||||
None
|
||||
})
|
||||
.flatten()
|
||||
{
|
||||
Some(ctx) => Some(ctx),
|
||||
None => {
|
||||
tracing::trace!(
|
||||
"context {} ({:?}) not found",
|
||||
std::any::type_name::<T>(),
|
||||
std::any::TypeId::of::<T>()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
|
||||
@@ -152,6 +173,12 @@ impl ScopeContext {
|
||||
/// }
|
||||
/// ```
|
||||
pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
|
||||
tracing::trace!(
|
||||
"providing context {} ({:?}) in {}",
|
||||
std::any::type_name::<T>(),
|
||||
std::any::TypeId::of::<T>(),
|
||||
self.name
|
||||
);
|
||||
let mut contexts = self.shared_contexts.borrow_mut();
|
||||
|
||||
// If the context exists, swap it out for the new value
|
||||
@@ -179,7 +206,7 @@ impl ScopeContext {
|
||||
pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
|
||||
with_runtime(|runtime| {
|
||||
runtime
|
||||
.get_context(ScopeId(0))
|
||||
.get_context(ScopeId::ROOT)
|
||||
.unwrap()
|
||||
.provide_context(context)
|
||||
})
|
||||
@@ -203,7 +230,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(0), fut);
|
||||
let id = self.tasks.spawn(ScopeId::ROOT, fut);
|
||||
|
||||
// wake up the scheduler if it is sleeping
|
||||
self.tasks
|
||||
|
||||
@@ -63,6 +63,21 @@ impl<'a, T> std::ops::Deref for Scoped<'a, T> {
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
|
||||
pub struct ScopeId(pub usize);
|
||||
|
||||
impl ScopeId {
|
||||
/// The root ScopeId.
|
||||
///
|
||||
/// This scope will last for the entire duration of your app, making it convenient for long-lived state
|
||||
/// that is created dynamically somewhere down the component tree.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust, ignore
|
||||
/// use dioxus_signals::*;
|
||||
/// let my_persistent_state = Signal::new_in_scope(ScopeId::ROOT, String::new());
|
||||
/// ```
|
||||
pub const ROOT: ScopeId = ScopeId(0);
|
||||
}
|
||||
|
||||
/// A component's state separate from its props.
|
||||
///
|
||||
/// This struct exists to provide a common interface for all scopes without relying on generics.
|
||||
@@ -79,7 +94,7 @@ 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) attributes_to_drop_before_render: RefCell<Vec<*const Attribute<'static>>>,
|
||||
|
||||
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
|
||||
}
|
||||
@@ -333,25 +348,36 @@ 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(_) => {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,7 +450,9 @@ impl<'src> ScopeState {
|
||||
fn_name: &'static str,
|
||||
) -> DynamicNode<'src>
|
||||
where
|
||||
P: Properties + 'child,
|
||||
// The properties must be valid until the next bump frame
|
||||
P: Properties + 'src,
|
||||
// The current bump allocator frame must outlive the child's borrowed props
|
||||
'src: 'child,
|
||||
{
|
||||
let vcomp = VProps::new(component, P::memoize, props);
|
||||
|
||||
Loaded 100 of 575 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user