repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/tests/web-component.rs | packages/rsx-rosetta/tests/web-component.rs | use html_parser::Dom;
#[test]
fn web_components_translate() {
let html = r#"
<div>
<my-component></my-component>
</div>
"#
.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
let expected = r#"
div {
my-component {}
}"#;
pretty_assertions::assert_eq!(&out, &expected);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/tests/simple.rs | packages/rsx-rosetta/tests/simple.rs | use html_parser::Dom;
#[test]
fn simple_elements() {
let html = r#"
<div>
<div class="asd">hello world!</div>
<div id="asd">hello world!</div>
<div id="asd">hello world!</div>
<div for="asd">hello world!</div>
<div async="asd">hello world!</div>
</div>
"#
.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
let expected = r#"
div {
div { class: "asd", "hello world!" }
div { id: "asd", "hello world!" }
div { id: "asd", "hello world!" }
div { r#for: "asd", "hello world!" }
div { r#async: "asd", "hello world!" }
}"#;
pretty_assertions::assert_eq!(&out, &expected);
}
#[test]
fn deeply_nested() {
let html = r#"
<div>
<div class="asd">
<div class="asd">
<div class="asd">
<div class="asd">
</div>
</div>
</div>
</div>
</div>
"#
.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
let expected = r#"
div {
div { class: "asd",
div { class: "asd",
div { class: "asd",
div { class: "asd" }
}
}
}
}"#;
pretty_assertions::assert_eq!(&out, &expected);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/tests/raw.rs | packages/rsx-rosetta/tests/raw.rs | use html_parser::Dom;
#[test]
fn raw_attribute() {
let html = r#"
<div>
<div unrecognizedattribute="asd">hello world!</div>
</div>
"#
.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
let expected = r#"
div {
div { "unrecognizedattribute": "asd", "hello world!" }
}"#;
pretty_assertions::assert_eq!(&out, &expected);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/tests/svgs.rs | packages/rsx-rosetta/tests/svgs.rs | use html_parser::Dom;
#[test]
fn svgs() {
let viewbox = dioxus_html::map_html_attribute_to_rsx("viewBox");
assert_eq!(viewbox, Some("view_box"));
let html = r###"
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icons-fr" viewBox="0 0 640 480">
<path fill="#fff" d="M0 0h640v480H0z"/>
<path fill="#000091" d="M0 0h213.3v480H0z"/>
<path fill="#e1000f" d="M426.7 0H640v480H426.7z"/>
</svg>
"###;
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
pretty_assertions::assert_eq!(
&out,
r##"
svg {
id: "flag-icons-fr",
view_box: "0 0 640 480",
xmlns: "http://www.w3.org/2000/svg",
path { d: "M0 0h640v480H0z", fill: "#fff" }
path { d: "M0 0h213.3v480H0z", fill: "#000091" }
path { d: "M426.7 0H640v480H426.7z", fill: "#e1000f" }
}"##
);
let html = r###"
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="flag-icons-cn" viewBox="0 0 640 480">
<defs>
<path id="cn-a" fill="#ff0" d="M-.6.8 0-1 .6.8-1-.3h2z"/>
</defs>
<path fill="#ee1c25" d="M0 0h640v480H0z"/>
<use xlink:href="#cn-a" width="30" height="20" transform="matrix(71.9991 0 0 72 120 120)"/>
<use xlink:href="#cn-a" width="30" height="20" transform="matrix(-12.33562 -20.5871 20.58684 -12.33577 240.3 48)"/>
<use xlink:href="#cn-a" width="30" height="20" transform="matrix(-3.38573 -23.75998 23.75968 -3.38578 288 95.8)"/>
<use xlink:href="#cn-a" width="30" height="20" transform="matrix(6.5991 -23.0749 23.0746 6.59919 288 168)"/>
<use xlink:href="#cn-a" width="30" height="20" transform="matrix(14.9991 -18.73557 18.73533 14.99929 240 216)"/>
</svg>
"###;
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
pretty_assertions::assert_eq!(
&out,
r##"
svg {
id: "flag-icons-cn",
view_box: "0 0 640 480",
"xlink": "http://www.w3.org/1999/xlink",
xmlns: "http://www.w3.org/2000/svg",
defs {
path { d: "M-.6.8 0-1 .6.8-1-.3h2z", fill: "#ff0", id: "cn-a" }
}
path { d: "M0 0h640v480H0z", fill: "#ee1c25" }
use {
height: "20",
href: "#cn-a",
transform: "matrix(71.9991 0 0 72 120 120)",
width: "30",
}
use {
height: "20",
href: "#cn-a",
transform: "matrix(-12.33562 -20.5871 20.58684 -12.33577 240.3 48)",
width: "30",
}
use {
height: "20",
href: "#cn-a",
transform: "matrix(-3.38573 -23.75998 23.75968 -3.38578 288 95.8)",
width: "30",
}
use {
height: "20",
href: "#cn-a",
transform: "matrix(6.5991 -23.0749 23.0746 6.59919 288 168)",
width: "30",
}
use {
height: "20",
href: "#cn-a",
transform: "matrix(14.9991 -18.73557 18.73533 14.99929 240 216)",
width: "30",
}
}"##
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/tests/escape.rs | packages/rsx-rosetta/tests/escape.rs | use html_parser::Dom;
// Regression test for https://github.com/DioxusLabs/dioxus/issues/3037
// We need to escape html entities as we translate html because rsx doesn't support them
#[test]
fn escaped_text() {
let html = r#"<div><div>⌛⌛⌛⌛</div>"#.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
let expected = r#"
div { "<div>⌛⌛⌛⌛" }"#;
pretty_assertions::assert_eq!(&out, &expected);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-rosetta/examples/html.rs | packages/rsx-rosetta/examples/html.rs | use html_parser::Dom;
fn main() {
let html = r#"
<div>
<div class="asd">hello world!</div>
<div id="asd">hello world!</div>
<div id="asd">hello world!</div>
<div for="asd">hello world!</div>
<div async="asd">hello world!</div>
<div LargeThing="asd">hello world!</div>
<ai-is-awesome>hello world!</ai-is-awesome>
</div>
"#
.trim();
let dom = Dom::parse(html).unwrap();
let body = dioxus_rsx_rosetta::rsx_from_html(&dom);
let out = dioxus_autofmt::write_block_out(&body).unwrap();
println!("{out}");
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/src/config.rs | packages/ssr/src/config.rs | rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false | |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/src/lib.rs | packages/ssr/src/lib.rs | #![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 cache;
pub mod config;
pub mod renderer;
pub mod template;
use dioxus_core::{Element, VirtualDom};
pub use crate::renderer::Renderer;
/// A convenience function to render an `rsx!` call to a string
///
/// For advanced rendering, create a new `SsrRender`.
pub fn render_element(element: Element) -> String {
Renderer::new().render_element(element)
}
/// A convenience function to render an existing VirtualDom to a string
///
/// We generally recommend creating a new `Renderer` to take advantage of template caching.
pub fn render(dom: &VirtualDom) -> String {
Renderer::new().render(dom)
}
/// A convenience function to pre-render an existing VirtualDom to a string
///
/// We generally recommend creating a new `Renderer` to take advantage of template caching.
pub fn pre_render(dom: &VirtualDom) -> String {
let mut renderer = Renderer::new();
renderer.pre_render = true;
renderer.render(dom)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/src/renderer.rs | packages/ssr/src/renderer.rs | use super::cache::Segment;
use crate::cache::StringCache;
use dioxus_core::{
Attribute, AttributeValue, DynamicNode, Element, ScopeId, Template, VNode, VirtualDom,
};
use rustc_hash::FxHashMap;
use std::fmt::Write;
use std::sync::Arc;
type ComponentRenderCallback = Arc<
dyn Fn(&mut Renderer, &mut dyn Write, &VirtualDom, ScopeId) -> std::fmt::Result + Send + Sync,
>;
/// A virtualdom renderer that caches the templates it has seen for faster rendering
#[derive(Default)]
pub struct Renderer {
/// Choose to write ElementIDs into elements so the page can be re-hydrated later on
pub pre_render: bool,
/// A callback used to render components. You can set this callback to control what components are rendered and add wrappers around components that are not present in CSR
render_components: Option<ComponentRenderCallback>,
/// A cache of templates that have been rendered
template_cache: FxHashMap<Template, Arc<StringCache>>,
/// The current dynamic node id for hydration
dynamic_node_id: usize,
}
impl Renderer {
pub fn new() -> Self {
Self::default()
}
/// Set the callback that the renderer uses to render components
pub fn set_render_components(
&mut self,
callback: impl Fn(&mut Renderer, &mut dyn Write, &VirtualDom, ScopeId) -> std::fmt::Result
+ Send
+ Sync
+ 'static,
) {
self.render_components = Some(Arc::new(callback));
}
/// Completely clear the renderer cache and reset the dynamic node id
pub fn clear(&mut self) {
self.template_cache.clear();
self.dynamic_node_id = 0;
self.render_components = None;
}
/// Reset the callback that the renderer uses to render components
pub fn reset_render_components(&mut self) {
self.render_components = None;
}
pub fn render(&mut self, dom: &VirtualDom) -> String {
let mut buf = String::new();
self.render_to(&mut buf, dom).unwrap();
buf
}
pub fn render_to<W: Write + ?Sized>(
&mut self,
buf: &mut W,
dom: &VirtualDom,
) -> std::fmt::Result {
self.reset_hydration();
self.render_scope(buf, dom, ScopeId::ROOT)
}
/// Render an element to a string
pub fn render_element(&mut self, element: Element) -> String {
let mut buf = String::new();
self.render_element_to(&mut buf, element).unwrap();
buf
}
/// Render an element to the buffer
pub fn render_element_to<W: Write + ?Sized>(
&mut self,
buf: &mut W,
element: Element,
) -> std::fmt::Result {
fn lazy_app(props: Element) -> Element {
props
}
let mut dom = VirtualDom::new_with_props(lazy_app, element);
dom.rebuild_in_place();
self.render_to(buf, &dom)
}
/// Reset the renderer hydration state
pub fn reset_hydration(&mut self) {
self.dynamic_node_id = 0;
}
pub fn render_scope<W: Write + ?Sized>(
&mut self,
buf: &mut W,
dom: &VirtualDom,
scope: ScopeId,
) -> std::fmt::Result {
let node = dom.get_scope(scope).unwrap().root_node();
self.render_template(buf, dom, node, true)?;
Ok(())
}
fn render_template<W: Write + ?Sized>(
&mut self,
mut buf: &mut W,
dom: &VirtualDom,
template: &VNode,
parent_escaped: bool,
) -> std::fmt::Result {
let entry = self
.template_cache
.entry(template.template)
.or_insert_with(move || Arc::new(StringCache::from_template(template).unwrap()))
.clone();
let mut inner_html = None;
// We need to keep track of the dynamic styles so we can insert them into the right place
let mut accumulated_dynamic_styles = Vec::new();
// We need to keep track of the listeners so we can insert them into the right place
let mut accumulated_listeners = Vec::new();
// We keep track of the index we are on manually so that we can jump forward to a new section quickly without iterating every item
let mut index = 0;
while let Some(segment) = entry.segments.get(index) {
match segment {
Segment::HydrationOnlySection(jump_to) => {
// If we are not prerendering, we don't need to write the content of the hydration only section
// Instead we can jump to the next section
if !self.pre_render {
index = *jump_to;
continue;
}
}
Segment::Attr(idx) => {
let attrs = &*template.dynamic_attrs[*idx];
for attr in attrs {
if attr.name == "dangerous_inner_html" {
inner_html = Some(attr);
} else if attr.namespace == Some("style") {
accumulated_dynamic_styles.push(attr);
} else if BOOL_ATTRS.contains(&attr.name) {
if truthy(&attr.value) {
write_attribute(buf, attr)?;
}
} else {
write_attribute(buf, attr)?;
}
if self.pre_render {
if let AttributeValue::Listener(_) = &attr.value {
// The onmounted event doesn't need a DOM listener
if attr.name != "onmounted" {
accumulated_listeners.push(attr.name);
}
}
}
}
}
Segment::Node { index, escape_text } => {
let escaped = escape_text.should_escape(parent_escaped);
match &template.dynamic_nodes[*index] {
DynamicNode::Component(node) => {
if let Some(render_components) = self.render_components.clone() {
let scope_id =
node.mounted_scope_id(*index, template, dom).unwrap();
render_components(self, &mut buf, dom, scope_id)?;
} else {
let scope = node.mounted_scope(*index, template, dom).unwrap();
let node = scope.root_node();
self.render_template(buf, dom, node, escaped)?
}
}
DynamicNode::Text(text) => {
// in SSR, we are concerned that we can't hunt down the right text node since they might get merged
if self.pre_render {
write!(buf, "<!--node-id{}-->", self.dynamic_node_id)?;
self.dynamic_node_id += 1;
}
if escaped {
write!(
buf,
"{}",
askama_escape::escape(&text.value, askama_escape::Html)
)?;
} else {
write!(buf, "{}", text.value)?;
}
if self.pre_render {
write!(buf, "<!--#-->")?;
}
}
DynamicNode::Fragment(nodes) => {
for child in nodes {
self.render_template(buf, dom, child, escaped)?;
}
}
DynamicNode::Placeholder(_) => {
if self.pre_render {
write!(buf, "<!--placeholder{}-->", self.dynamic_node_id)?;
self.dynamic_node_id += 1;
}
}
}
}
Segment::PreRendered(contents) => write!(buf, "{contents}")?,
Segment::PreRenderedMaybeEscaped {
value,
renderer_if_escaped,
} => {
if *renderer_if_escaped == parent_escaped {
write!(buf, "{value}")?;
}
}
Segment::StyleMarker { inside_style_tag } => {
if !accumulated_dynamic_styles.is_empty() {
// if we are inside a style tag, we don't need to write the style attribute
if !*inside_style_tag {
write!(buf, " style=\"")?;
}
for attr in &accumulated_dynamic_styles {
write!(buf, "{}:", attr.name)?;
write_value_unquoted(buf, &attr.value)?;
write!(buf, ";")?;
}
if !*inside_style_tag {
write!(buf, "\"")?;
}
// clear the accumulated styles
accumulated_dynamic_styles.clear();
}
}
Segment::InnerHtmlMarker => {
if let Some(inner_html) = inner_html.take() {
let inner_html = &inner_html.value;
match inner_html {
AttributeValue::Text(value) => write!(buf, "{}", value)?,
AttributeValue::Bool(value) => write!(buf, "{}", value)?,
AttributeValue::Float(f) => write!(buf, "{}", f)?,
AttributeValue::Int(i) => write!(buf, "{}", i)?,
_ => {}
}
}
}
Segment::AttributeNodeMarker => {
// first write the id
write!(buf, "{}", self.dynamic_node_id)?;
self.dynamic_node_id += 1;
// then write any listeners
for name in accumulated_listeners.drain(..) {
write!(buf, ",{}:", &name[2..])?;
write!(
buf,
"{}",
dioxus_core_types::event_bubbles(&name[2..]) as u8
)?;
}
}
Segment::RootNodeMarker => {
write!(buf, "{}", self.dynamic_node_id)?;
self.dynamic_node_id += 1
}
}
index += 1;
}
Ok(())
}
}
#[test]
fn to_string_works() {
use crate::cache::EscapeText;
use dioxus::prelude::*;
fn app() -> Element {
let dynamic = 123;
let dyn2 = "</diiiiiiiiv>"; // this should be escaped
rsx! {
div { class: "asdasdasd", class: "asdasdasd", id: "id-{dynamic}",
"Hello world 1 -->"
"{dynamic}"
"<-- Hello world 2"
div { "nest 1" }
div {}
div { "nest 2" }
"{dyn2}"
for i in (0..5) {
div { "finalize {i}" }
}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
let mut renderer = Renderer::new();
let out = renderer.render(&dom);
for item in renderer.template_cache.iter() {
if item.1.segments.len() > 10 {
assert_eq!(
item.1.segments,
vec![
PreRendered("<div class=\"asdasdasd asdasdasd\"".to_string()),
Attr(0),
StyleMarker {
inside_style_tag: false
},
HydrationOnlySection(7), // jump to `>` if we don't need to hydrate
PreRendered(" data-node-hydration=\"".to_string()),
AttributeNodeMarker,
PreRendered("\"".to_string()),
PreRendered(">".to_string()),
InnerHtmlMarker,
PreRendered("Hello world 1 -->".to_string()),
Node {
index: 0,
escape_text: EscapeText::Escape
},
PreRendered(
"<-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div>"
.to_string()
),
Node {
index: 1,
escape_text: EscapeText::Escape
},
Node {
index: 2,
escape_text: EscapeText::Escape
},
PreRendered("</div>".to_string())
]
);
}
}
use Segment::*;
assert_eq!(out, "<div class=\"asdasdasd asdasdasd\" id=\"id-123\">Hello world 1 -->123<-- Hello world 2<div>nest 1</div><div></div><div>nest 2</div></diiiiiiiiv><div>finalize 0</div><div>finalize 1</div><div>finalize 2</div><div>finalize 3</div><div>finalize 4</div></div>");
}
#[test]
fn empty_for_loop_works() {
use crate::cache::EscapeText;
use dioxus::prelude::*;
fn app() -> Element {
rsx! {
div { class: "asdasdasd",
for _ in (0..5) {
}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
let mut renderer = Renderer::new();
let out = renderer.render(&dom);
for item in renderer.template_cache.iter() {
if item.1.segments.len() > 5 {
assert_eq!(
item.1.segments,
vec![
PreRendered("<div class=\"asdasdasd\"".to_string()),
HydrationOnlySection(5), // jump to `>` if we don't need to hydrate
PreRendered(" data-node-hydration=\"".to_string()),
RootNodeMarker,
PreRendered("\"".to_string()),
PreRendered(">".to_string()),
Node {
index: 0,
escape_text: EscapeText::Escape
},
PreRendered("</div>".to_string())
]
);
}
}
use Segment::*;
assert_eq!(out, "<div class=\"asdasdasd\"></div>");
}
#[test]
fn empty_render_works() {
use dioxus::prelude::*;
fn app() -> Element {
rsx! {}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
let mut renderer = Renderer::new();
let out = renderer.render(&dom);
for item in renderer.template_cache.iter() {
if item.1.segments.len() > 5 {
assert_eq!(item.1.segments, vec![]);
}
}
assert_eq!(out, "");
}
pub(crate) const BOOL_ATTRS: &[&str] = &[
"allowfullscreen",
"allowpaymentrequest",
"async",
"autofocus",
"autoplay",
"checked",
"controls",
"default",
"defer",
"disabled",
"formnovalidate",
"hidden",
"ismap",
"itemscope",
"loop",
"multiple",
"muted",
"nomodule",
"novalidate",
"open",
"playsinline",
"readonly",
"required",
"reversed",
"selected",
"truespeed",
"webkitdirectory",
];
pub(crate) fn str_truthy(value: &str) -> bool {
!value.is_empty() && value != "0" && value.to_lowercase() != "false"
}
pub(crate) fn truthy(value: &AttributeValue) -> bool {
match value {
AttributeValue::Text(value) => str_truthy(value),
AttributeValue::Bool(value) => *value,
AttributeValue::Int(value) => *value != 0,
AttributeValue::Float(value) => *value != 0.0,
_ => false,
}
}
pub(crate) fn write_attribute<W: Write + ?Sized>(
buf: &mut W,
attr: &Attribute,
) -> std::fmt::Result {
let name = &attr.name;
match &attr.value {
AttributeValue::Text(value) => write!(
buf,
" {name}=\"{}\"",
askama_escape::escape(value, askama_escape::Html)
),
AttributeValue::Bool(value) => write!(buf, " {name}={value}"),
AttributeValue::Int(value) => write!(buf, " {name}={value}"),
AttributeValue::Float(value) => write!(buf, " {name}={value}"),
_ => Ok(()),
}
}
pub(crate) fn write_value_unquoted<W: Write + ?Sized>(
buf: &mut W,
value: &AttributeValue,
) -> std::fmt::Result {
match value {
AttributeValue::Text(value) => {
write!(buf, "{}", askama_escape::escape(value, askama_escape::Html))
}
AttributeValue::Bool(value) => write!(buf, "{}", value),
AttributeValue::Int(value) => write!(buf, "{}", value),
AttributeValue::Float(value) => write!(buf, "{}", value),
_ => Ok(()),
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/src/template.rs | packages/ssr/src/template.rs | rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false | |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/src/cache.rs | packages/ssr/src/cache.rs | //! Dioxus SSR uses the design of templates to cache as much as possible about the HTML a block of rsx can render.
//!
//! The structure of templates can tell us what segments are rendered where and lets us cache segments in the output string.
//!
//! For example, in this code, we can cache the whole render:
//! ```rust, no_run
//! use dioxus::prelude::*;
//! rsx! {
//! div {
//! "Hello world"
//! }
//! };
//! ```
//! Because everything exists in the template, we can calculate the whole HTML for the template once and then reuse it.
//! ```html
//! <div>Hello world</div>
//! ```
//!
//! If the template is more complex, we can only cache the parts that are static. In this case, we can cache `<div width="100px">` and `</div>`, but not the child text.
//!
//! ```rust, no_run
//! use dioxus::prelude::*;
//! let dynamic = 123;
//! rsx! {
//! div {
//! width: "100px",
//! "{dynamic}"
//! }
//! };
//!```
use crate::renderer::{str_truthy, BOOL_ATTRS};
use dioxus_core::{TemplateAttribute, TemplateNode, VNode};
use std::{fmt::Write, ops::AddAssign};
#[derive(Debug)]
pub(crate) struct StringCache {
pub segments: Vec<Segment>,
}
#[derive(Default)]
pub struct StringChain {
// If we should add new static text to the last segment
// This will be true if the last segment is a static text and the last text isn't part of a hydration only boundary
add_text_to_last_segment: bool,
segments: Vec<Segment>,
}
impl StringChain {
/// Add segments but only when hydration is enabled
fn if_hydration_enabled<O>(
&mut self,
during_prerender: impl FnOnce(&mut StringChain) -> O,
) -> O {
// Insert a placeholder jump to the end of the hydration only segments
let jump_index = self.segments.len();
*self += Segment::HydrationOnlySection(0);
let out = during_prerender(self);
// Go back and fill in where the placeholder jump should skip to
let after_hydration_only_section = self.segments.len();
// Don't add any text to static text in the hydration only section. This would cause the text to be skipped during non-hydration renders
self.add_text_to_last_segment = false;
self.segments[jump_index] = Segment::HydrationOnlySection(after_hydration_only_section);
out
}
/// Add a new segment
pub fn push(&mut self, segment: Segment) {
self.add_text_to_last_segment = matches!(segment, Segment::PreRendered(_));
self.segments.push(segment);
}
}
impl AddAssign<Segment> for StringChain {
fn add_assign(&mut self, rhs: Segment) {
self.push(rhs)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// The escape text enum is used to mark segments that should be escaped
/// when rendering. This is used to prevent XSS attacks by escaping user input.
pub(crate) enum EscapeText {
/// Always escape the text. This will be assigned if the text node is under
/// a normal tag like a div in the template
Escape,
/// Don't escape the text. This will be assigned if the text node is under
/// a script or style tag in the template
NoEscape,
/// Only escape the tag if this is rendered under a script or style tag in
/// the parent template. This will be assigned if the text node is a root
/// node in the template
ParentEscape,
}
impl EscapeText {
/// Check if the text should be escaped based on the parent's resolved
/// escape text value
pub fn should_escape(&self, parent_escaped: bool) -> bool {
match self {
EscapeText::Escape => true,
EscapeText::NoEscape => false,
EscapeText::ParentEscape => parent_escaped,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Segment {
/// A marker for where to insert an attribute with a given index
Attr(usize),
/// A marker for where to insert a node with a given index
Node {
index: usize,
escape_text: EscapeText,
},
/// Text that we know is static in the template that is pre-rendered
PreRendered(String),
/// Text we know is static in the template that is pre-rendered that may or may not be escaped
PreRenderedMaybeEscaped {
/// The text to render
value: String,
/// Only render this text if the escaped value is this
renderer_if_escaped: bool,
},
/// Anything between this and the segments at the index is only required for hydration. If you don't need to hydrate, you can safely skip to the section at the given index
HydrationOnlySection(usize),
/// A marker for where to insert a dynamic styles
StyleMarker {
// If the marker is inside a style tag or not
// This will be true if there are static styles
inside_style_tag: bool,
},
/// A marker for where to insert a dynamic inner html
InnerHtmlMarker,
/// A marker for where to insert a node id for an attribute
AttributeNodeMarker,
/// A marker for where to insert a node id for a root node
RootNodeMarker,
}
impl std::fmt::Write for StringChain {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
if self.add_text_to_last_segment {
match self.segments.last_mut() {
Some(Segment::PreRendered(s2)) => s2.push_str(s),
_ => unreachable!(),
}
} else {
self.segments.push(Segment::PreRendered(s.to_string()))
}
self.add_text_to_last_segment = true;
Ok(())
}
}
impl StringCache {
/// Create a new string cache from a template. This intentionally does not include any settings about the render mode (hydration or not) so that we can reuse the cache for both hydration and non-hydration renders.
pub fn from_template(template: &VNode) -> Result<Self, std::fmt::Error> {
let mut chain = StringChain::default();
let mut cur_path = vec![];
for (root_idx, root) in template.template.roots.iter().enumerate() {
from_template_recursive(
root,
&mut cur_path,
root_idx,
true,
EscapeText::ParentEscape,
&mut chain,
)?;
}
Ok(Self {
segments: chain.segments,
})
}
}
fn from_template_recursive(
root: &TemplateNode,
cur_path: &mut Vec<usize>,
root_idx: usize,
is_root: bool,
escape_text: EscapeText,
chain: &mut StringChain,
) -> Result<(), std::fmt::Error> {
match root {
TemplateNode::Element {
tag,
attrs,
children,
..
} => {
cur_path.push(root_idx);
write!(chain, "<{tag}")?;
// we need to collect the styles and write them at the end
let mut styles = Vec::new();
// we need to collect the inner html and write it at the end
let mut inner_html = None;
// we need to keep track of if we have dynamic attrs to know if we need to insert a style and inner_html marker
let mut has_dyn_attrs = false;
for attr in *attrs {
match attr {
TemplateAttribute::Static {
name,
value,
namespace,
} => {
if *name == "dangerous_inner_html" {
inner_html = Some(value);
} else if let Some("style") = namespace {
styles.push((name, value));
} else if BOOL_ATTRS.contains(name) {
if str_truthy(value) {
write!(
chain,
" {name}=\"{}\"",
askama_escape::escape(value, askama_escape::Html)
)?;
}
} else {
write!(
chain,
" {name}=\"{}\"",
askama_escape::escape(value, askama_escape::Html)
)?;
}
}
TemplateAttribute::Dynamic { id: index } => {
let index = *index;
*chain += Segment::Attr(index);
has_dyn_attrs = true
}
}
}
// write the styles
if !styles.is_empty() {
write!(chain, " style=\"")?;
for (name, value) in styles {
write!(
chain,
"{name}:{};",
askama_escape::escape(value, askama_escape::Html)
)?;
}
*chain += Segment::StyleMarker {
inside_style_tag: true,
};
write!(chain, "\"")?;
} else if has_dyn_attrs {
*chain += Segment::StyleMarker {
inside_style_tag: false,
};
}
// write the id if we are prerendering and this is either a root node or a node with a dynamic attribute
if has_dyn_attrs || is_root {
chain.if_hydration_enabled(|chain| {
write!(chain, " data-node-hydration=\"")?;
if has_dyn_attrs {
*chain += Segment::AttributeNodeMarker;
} else if is_root {
*chain += Segment::RootNodeMarker;
}
write!(chain, "\"")?;
std::fmt::Result::Ok(())
})?;
}
if children.is_empty() && tag_is_self_closing(tag) {
write!(chain, "/>")?;
} else {
write!(chain, ">")?;
// Write the static inner html, or insert a marker if dynamic inner html is possible
if let Some(inner_html) = inner_html {
chain.write_str(inner_html)?;
} else if has_dyn_attrs {
*chain += Segment::InnerHtmlMarker;
}
// Escape the text in children if this is not a style or script tag. If it is a style
// or script tag, we want to allow the user to write code inside the tag
let escape_text = match *tag {
"style" | "script" => EscapeText::NoEscape,
_ => EscapeText::Escape,
};
for child in *children {
from_template_recursive(child, cur_path, root_idx, false, escape_text, chain)?;
}
write!(chain, "</{tag}>")?;
}
cur_path.pop();
}
TemplateNode::Text { text } => {
// write the id if we are prerendering and this is a root node that may need to be removed in the future
if is_root {
chain.if_hydration_enabled(|chain| {
write!(chain, "<!--node-id")?;
*chain += Segment::RootNodeMarker;
write!(chain, "-->")?;
std::fmt::Result::Ok(())
})?;
}
match escape_text {
// If we know this is statically escaped we can just write it out
// rsx! { div { "hello" } }
EscapeText::Escape => {
write!(
chain,
"{}",
askama_escape::escape(text, askama_escape::Html)
)?;
}
// If we know this is statically not escaped we can just write it out
// rsx! { script { "console.log('hello')" } }
EscapeText::NoEscape => {
write!(chain, "{}", text)?;
}
// Otherwise, write out both versions and let the renderer decide which one to use
// at runtime
// rsx! { "console.log('hello')" }
EscapeText::ParentEscape => {
*chain += Segment::PreRenderedMaybeEscaped {
value: text.to_string(),
renderer_if_escaped: false,
};
*chain += Segment::PreRenderedMaybeEscaped {
value: askama_escape::escape(text, askama_escape::Html).to_string(),
renderer_if_escaped: true,
};
}
}
if is_root {
chain.if_hydration_enabled(|chain| write!(chain, "<!--#-->"))?;
}
}
TemplateNode::Dynamic { id: idx } => {
*chain += Segment::Node {
index: *idx,
escape_text,
}
}
}
Ok(())
}
fn tag_is_self_closing(tag: &str) -> bool {
matches!(
tag,
"area"
| "base"
| "br"
| "col"
| "embed"
| "hr"
| "img"
| "input"
| "link"
| "meta"
| "param"
| "source"
| "track"
| "wbr"
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/hydration.rs | packages/ssr/tests/hydration.rs | use dioxus::prelude::*;
#[test]
fn root_ids() {
fn app() -> Element {
rsx! { div { width: "100px" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div style="width:100px;" data-node-hydration="0"></div>"#
);
}
#[test]
fn dynamic_attributes() {
fn app() -> Element {
let dynamic = 123;
rsx! {
div { width: "100px", div { width: "{dynamic}px" } }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div style="width:100px;" data-node-hydration="0"><div style="width:123px;" data-node-hydration="1"></div></div>"#
);
}
#[test]
fn listeners() {
fn app() -> Element {
rsx! {
div { width: "100px", div { onclick: |_| {} } }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div style="width:100px;" data-node-hydration="0"><div data-node-hydration="1,click:1"></div></div>"#
);
fn app2() -> Element {
let dynamic = 123;
rsx! {
div { width: "100px", div { width: "{dynamic}px", onclick: |_| {} } }
}
}
let mut dom = VirtualDom::new(app2);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div style="width:100px;" data-node-hydration="0"><div style="width:123px;" data-node-hydration="1,click:1"></div></div>"#
);
}
#[test]
fn text_nodes() {
fn app() -> Element {
let dynamic_text = "hello";
rsx! {
div { {dynamic_text} }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div data-node-hydration="0"><!--node-id1-->hello<!--#--></div>"#
);
fn app2() -> Element {
let dynamic = 123;
rsx! {
div { "{dynamic}" "{1234}" }
}
}
let mut dom = VirtualDom::new(app2);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div data-node-hydration="0"><!--node-id1-->123<!--#--><!--node-id2-->1234<!--#--></div>"#
);
}
#[allow(non_snake_case)]
#[test]
fn components_hydrate() {
fn app() -> Element {
rsx! { Child {} }
}
fn Child() -> Element {
rsx! { div { "hello" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div data-node-hydration="0">hello</div>"#
);
fn app2() -> Element {
rsx! { Child2 {} }
}
fn Child2() -> Element {
let dyn_text = "hello";
rsx! {
div { {dyn_text} }
}
}
let mut dom = VirtualDom::new(app2);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div data-node-hydration="0"><!--node-id1-->hello<!--#--></div>"#
);
fn app3() -> Element {
rsx! { Child3 {} }
}
fn Child3() -> Element {
rsx! { div { width: "{1}" } }
}
let mut dom = VirtualDom::new(app3);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<div style="width:1;" data-node-hydration="0"></div>"#
);
fn app4() -> Element {
rsx! { Child4 {} }
}
fn Child4() -> Element {
rsx! {
for _ in 0..2 {
{rsx! { "{1}" }}
}
}
}
let mut dom = VirtualDom::new(app4);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<!--node-id0-->1<!--#--><!--node-id1-->1<!--#-->"#
);
}
#[test]
fn hello_world_hydrates() {
use dioxus::hooks::use_signal;
fn app() -> Element {
let mut count = use_signal(|| 0);
rsx! {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
r#"<h1 data-node-hydration="0"><!--node-id1-->High-Five counter: 0<!--#--></h1><button data-node-hydration="2,click:1">Up high!</button><button data-node-hydration="3,click:1">Down low!</button>"#
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/bool_attr.rs | packages/ssr/tests/bool_attr.rs | use dioxus::prelude::*;
#[test]
fn static_boolean_attributes() {
fn app() -> Element {
rsx! {
div { hidden: "false" }
div { hidden: "true" }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::render(&dom),
r#"<div></div><div hidden="true"></div>"#
);
}
#[test]
fn dynamic_boolean_attributes() {
fn app() -> Element {
rsx! {
div { hidden: false }
div { hidden: true }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::render(&dom),
r#"<div></div><div hidden=true></div>"#
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/styles.rs | packages/ssr/tests/styles.rs | use dioxus::prelude::*;
#[test]
fn static_styles() {
fn app() -> Element {
rsx! { div { width: "100px" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::render(&dom),
r#"<div style="width:100px;"></div>"#
);
}
#[test]
fn partially_dynamic_styles() {
let dynamic = 123;
assert_eq!(
dioxus_ssr::render_element(rsx! {
div { width: "100px", height: "{dynamic}px" }
}),
r#"<div style="width:100px;height:123px;"></div>"#
);
}
#[test]
fn dynamic_styles() {
let dynamic = 123;
assert_eq!(
dioxus_ssr::render_element(rsx! {
div { width: "{dynamic}px" }
}),
r#"<div style="width:123px;"></div>"#
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/simple.rs | packages/ssr/tests/simple.rs | #![allow(non_snake_case)]
use dioxus::prelude::*;
#[test]
fn simple() {
fn App() -> Element {
rsx! { div { "hello!" } }
}
let mut dom = VirtualDom::new(App);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(dioxus_ssr::render(&dom), "<div>hello!</div>");
assert_eq!(
dioxus_ssr::render_element(rsx!( div {"hello!"} )),
"<div>hello!</div>"
);
}
#[test]
fn lists() {
assert_eq!(
dioxus_ssr::render_element(rsx! {
ul {
{
(0..5).map(|i| rsx! {
li { "item {i}" }
})
}
}
}),
"<ul><li>item 0</li><li>item 1</li><li>item 2</li><li>item 3</li><li>item 4</li></ul>"
);
}
#[test]
fn dynamic() {
let dynamic = 123;
assert_eq!(
dioxus_ssr::render_element(rsx! {
div { "Hello world 1 -->" "{dynamic}" "<-- Hello world 2" }
}),
"<div>Hello world 1 -->123<-- Hello world 2</div>"
);
}
#[test]
fn components() {
#[derive(Props, Clone, PartialEq)]
struct MyComponentProps {
name: i32,
}
fn MyComponent(MyComponentProps { name }: MyComponentProps) -> Element {
rsx! { div { "component {name}" } }
}
assert_eq!(
dioxus_ssr::render_element(rsx! {
div {
{
(0..5).map(|name| rsx! {
MyComponent { name: name }
})
}
}
}),
"<div><div>component 0</div><div>component 1</div><div>component 2</div><div>component 3</div><div>component 4</div></div>"
);
}
#[test]
fn fragments() {
assert_eq!(
dioxus_ssr::render_element(rsx! {
div {
{
(0..5).map(|_| rsx! ({}))
}
}
}),
"<div></div>"
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/forward_spreads.rs | packages/ssr/tests/forward_spreads.rs | use dioxus::prelude::*;
// Regression test for https://github.com/DioxusLabs/dioxus/issues/3844
#[test]
fn forward_spreads() {
#[derive(Props, Clone, PartialEq)]
struct Comp1Props {
#[props(extends = GlobalAttributes)]
attributes: Vec<Attribute>,
}
#[component]
fn Comp1(props: Comp1Props) -> Element {
rsx! {
Comp2 {
attributes: props.attributes.clone(),
height: "100%",
}
Comp2 {
height: "100%",
attributes: props.attributes.clone(),
}
}
}
#[derive(Props, Clone, PartialEq)]
struct CompProps2 {
#[props(extends = GlobalAttributes)]
attributes: Vec<Attribute>,
}
#[component]
fn Comp2(props: CompProps2) -> Element {
let attributes = props.attributes;
rsx! {
div {
..attributes
}
}
}
let merged = || {
rsx! {
Comp1 {
width: "100%"
}
}
};
let dom = VirtualDom::prebuilt(merged);
let html = dioxus_ssr::render(&dom);
assert_eq!(
html,
r#"<div style="width:100%;height:100%;"></div><div style="width:100%;height:100%;"></div>"#
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/spread.rs | packages/ssr/tests/spread.rs | use dioxus::prelude::*;
#[test]
fn spread() {
let dom = VirtualDom::prebuilt(app);
let html = dioxus_ssr::render(&dom);
assert_eq!(
html,
r#"<audio data-custom-attribute="value" style="width:10px;height:10px;left:1;">1: hello1
2: hello2</audio>"#
);
}
fn app() -> Element {
rsx! {
SpreadableComponent {
width: "10px",
extra_data: "hello{1}",
extra_data2: "hello{2}",
height: "10px",
left: 1,
"data-custom-attribute": "value",
}
}
}
#[derive(Props, PartialEq, Clone)]
struct Props {
#[props(extends = GlobalAttributes)]
attributes: Vec<Attribute>,
extra_data: String,
extra_data2: String,
}
#[component]
fn SpreadableComponent(props: Props) -> Element {
rsx! {
audio { ..props.attributes, "1: {props.extra_data}\n2: {props.extra_data2}" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/escape.rs | packages/ssr/tests/escape.rs | use dioxus::prelude::*;
#[test]
fn escape_static_values() {
fn app() -> Element {
rsx! { input { disabled: "\"><div>" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<input disabled=\""><div>\" data-node-hydration=\"0\"/>"
);
}
#[test]
fn escape_dynamic_values() {
fn app() -> Element {
let disabled = "\"><div>";
rsx! { input { disabled } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<input disabled=\""><div>\" data-node-hydration=\"0\"/>"
);
}
#[test]
fn escape_static_style() {
fn app() -> Element {
rsx! { div { width: "\"><div>" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div style=\"width:"><div>;\" data-node-hydration=\"0\"></div>"
);
}
#[test]
fn escape_dynamic_style() {
fn app() -> Element {
let width = "\"><div>";
rsx! { div { width } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div style=\"width:"><div>;\" data-node-hydration=\"0\"></div>"
);
}
#[test]
fn escape_static_text() {
fn app() -> Element {
rsx! {
div {
"\"><div>"
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div data-node-hydration=\"0\">"><div></div>"
);
}
#[test]
fn escape_dynamic_text() {
fn app() -> Element {
let text = "\"><div>";
rsx! {
div {
{text}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div data-node-hydration=\"0\"><!--node-id1-->"><div><!--#--></div>"
);
}
#[test]
fn don_t_escape_static_scripts() {
fn app() -> Element {
rsx! {
script {
"console.log('hello world');"
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<script data-node-hydration=\"0\">console.log('hello world');</script>"
);
}
#[test]
fn don_t_escape_dynamic_scripts() {
fn app() -> Element {
let script = "console.log('hello world');";
rsx! {
script {
{script}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<script data-node-hydration=\"0\"><!--node-id1-->console.log('hello world');<!--#--></script>"
);
}
#[test]
fn don_t_escape_static_styles() {
fn app() -> Element {
rsx! {
style {
"body {{ background-color: red; }}"
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<style data-node-hydration=\"0\">body { background-color: red; }</style>"
);
}
#[test]
fn don_t_escape_dynamic_styles() {
fn app() -> Element {
let style = "body { font-family: \"sans-serif\"; }";
rsx! {
style {
{style}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<style data-node-hydration=\"0\"><!--node-id1-->body { font-family: \"sans-serif\"; }<!--#--></style>"
);
}
#[test]
fn don_t_escape_static_fragment_styles() {
fn app() -> Element {
let style_element = rsx! { "body {{ font-family: \"sans-serif\"; }}" };
rsx! {
style {
{style_element}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<style data-node-hydration=\"0\"><!--node-id1-->body { font-family: \"sans-serif\"; }<!--#--></style>"
);
}
#[test]
fn escape_static_component_fragment_div() {
#[component]
fn StyleContents() -> Element {
rsx! { "body {{ font-family: \"sans-serif\"; }}" }
}
fn app() -> Element {
rsx! {
div {
StyleContents {}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div data-node-hydration=\"0\"><!--node-id1-->body { font-family: "sans-serif"; }<!--#--></div>"
);
}
#[test]
fn escape_dynamic_component_fragment_div() {
#[component]
fn StyleContents() -> Element {
let dynamic = "body { font-family: \"sans-serif\"; }";
rsx! { "{dynamic}" }
}
fn app() -> Element {
rsx! {
div {
StyleContents {}
}
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(
dioxus_ssr::pre_render(&dom),
"<div data-node-hydration=\"0\"><!--node-id1-->body { font-family: "sans-serif"; }<!--#--></div>"
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/ssr/tests/inner_html.rs | packages/ssr/tests/inner_html.rs | use dioxus::prelude::*;
#[test]
fn static_inner_html() {
fn app() -> Element {
rsx! { div { dangerous_inner_html: "<div>1234</div>" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(dioxus_ssr::render(&dom), r#"<div><div>1234</div></div>"#);
}
#[test]
fn dynamic_inner_html() {
fn app() -> Element {
let inner_html = "<div>1234</div>";
rsx! { div { dangerous_inner_html: "{inner_html}" } }
}
let mut dom = VirtualDom::new(app);
dom.rebuild(&mut dioxus_core::NoOpMutations);
assert_eq!(dioxus_ssr::render(&dom), r#"<div><div>1234</div></div>"#);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/wasm-split/wasm-split-macro/src/lib.rs | packages/wasm-split/wasm-split-macro/src/lib.rs | use proc_macro::TokenStream;
use digest::Digest;
use quote::{format_ident, quote};
use syn::{parse_macro_input, parse_quote, FnArg, Ident, ItemFn, ReturnType, Signature};
#[proc_macro_attribute]
pub fn wasm_split(args: TokenStream, input: TokenStream) -> TokenStream {
let module_ident = parse_macro_input!(args as Ident);
let item_fn = parse_macro_input!(input as ItemFn);
if item_fn.sig.asyncness.is_none() {
panic!("wasm_split functions must be async. Use a LazyLoader with synchronous functions instead.");
}
let LoaderNames {
split_loader_ident,
impl_import_ident,
impl_export_ident,
load_module_ident,
..
} = LoaderNames::new(item_fn.sig.ident.clone(), module_ident.to_string());
let mut desugard_async_sig = item_fn.sig.clone();
desugard_async_sig.asyncness = None;
desugard_async_sig.output = match &desugard_async_sig.output {
ReturnType::Default => {
parse_quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = ()>>> }
}
ReturnType::Type(_, ty) => {
parse_quote! { -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = #ty>>> }
}
};
let import_sig = Signature {
ident: impl_import_ident.clone(),
..desugard_async_sig.clone()
};
let export_sig = Signature {
ident: impl_export_ident.clone(),
..desugard_async_sig.clone()
};
let default_item = item_fn.clone();
let mut wrapper_sig = item_fn.sig;
wrapper_sig.asyncness = Some(Default::default());
let mut args = Vec::new();
for (i, param) in wrapper_sig.inputs.iter_mut().enumerate() {
match param {
syn::FnArg::Receiver(_) => args.push(format_ident!("self")),
syn::FnArg::Typed(pat_type) => {
let param_ident = format_ident!("__wasm_split_arg_{i}");
args.push(param_ident.clone());
*pat_type.pat = syn::Pat::Ident(syn::PatIdent {
attrs: vec![],
by_ref: None,
mutability: None,
ident: param_ident,
subpat: None,
});
}
}
}
let attrs = &item_fn.attrs;
let stmts = &item_fn.block.stmts;
quote! {
#[cfg(target_arch = "wasm32")]
#wrapper_sig {
#(#attrs)*
#[allow(improper_ctypes_definitions)]
#[no_mangle]
pub extern "C" #export_sig {
Box::pin(async move { #(#stmts)* })
}
#[link(wasm_import_module = "./__wasm_split.js")]
extern "C" {
#[no_mangle]
fn #load_module_ident (
callback: unsafe extern "C" fn(*const ::std::ffi::c_void, bool),
data: *const ::std::ffi::c_void
);
#[allow(improper_ctypes)]
#[no_mangle]
#import_sig;
}
thread_local! {
static #split_loader_ident: wasm_split::LazySplitLoader = unsafe {
wasm_split::LazySplitLoader::new(#load_module_ident)
};
}
// Initiate the download by calling the load_module_ident function which will kick-off the loader
if !wasm_split::LazySplitLoader::ensure_loaded(&#split_loader_ident).await {
panic!("Failed to load wasm-split module");
}
unsafe { #impl_import_ident( #(#args),* ) }.await
}
#[cfg(not(target_arch = "wasm32"))]
#default_item
}
.into()
}
/// Create a lazy loader for a given function. Meant to be used in statics. Designed for libraries to
/// integrate with.
///
/// ```rust, ignore
/// fn SomeFunction(args: Args) -> Ret {}
///
/// static LOADER: wasm_split::LazyLoader<Args, Ret> = lazy_loader!(SomeFunction);
///
/// LOADER.load().await.call(args)
/// ```
#[proc_macro]
pub fn lazy_loader(input: TokenStream) -> TokenStream {
// We can only accept idents/paths that will be the source function
let sig = parse_macro_input!(input as Signature);
let params = sig.inputs.clone();
let outputs = sig.output.clone();
let Some(FnArg::Typed(arg)) = params.first().cloned() else {
panic!(
"Lazy Loader must define a single input argument to satisfy the LazyLoader signature"
)
};
let arg_ty = arg.ty.clone();
let LoaderNames {
name,
split_loader_ident,
impl_import_ident,
impl_export_ident,
load_module_ident,
..
} = LoaderNames::new(
sig.ident.clone(),
sig.abi
.as_ref()
.and_then(|abi| abi.name.as_ref().map(|f| f.value()))
.expect("abi to be module name")
.to_string(),
);
quote! {
{
#[cfg(target_arch = "wasm32")]
{
#[link(wasm_import_module = "./__wasm_split.js")]
extern "C" {
// The function we'll use to initiate the download of the module
#[no_mangle]
fn #load_module_ident(
callback: unsafe extern "C" fn(*const ::std::ffi::c_void, bool),
data: *const ::std::ffi::c_void,
);
#[allow(improper_ctypes)]
#[no_mangle]
fn #impl_import_ident(arg: #arg_ty) #outputs;
}
#[allow(improper_ctypes_definitions)]
#[no_mangle]
pub extern "C" fn #impl_export_ident(arg: #arg_ty) #outputs {
#name(arg)
}
thread_local! {
static #split_loader_ident: wasm_split::LazySplitLoader = unsafe {
wasm_split::LazySplitLoader::new(#load_module_ident)
};
};
unsafe {
wasm_split::LazyLoader::new(#impl_import_ident, &#split_loader_ident)
}
}
#[cfg(not(target_arch = "wasm32"))]
{
wasm_split::LazyLoader::preloaded(#name)
}
}
}
.into()
}
struct LoaderNames {
name: Ident,
split_loader_ident: Ident,
impl_import_ident: Ident,
impl_export_ident: Ident,
load_module_ident: Ident,
}
impl LoaderNames {
fn new(name: Ident, module: String) -> Self {
let unique_identifier = base16::encode_lower(
&sha2::Sha256::digest(format!("{name} {span:?}", name = name, span = name.span()))
[..16],
);
Self {
split_loader_ident: format_ident!("__wasm_split_loader_{module}"),
impl_export_ident: format_ident!(
"__wasm_split_00___{module}___00_export_{unique_identifier}_{name}"
),
impl_import_ident: format_ident!(
"__wasm_split_00___{module}___00_import_{unique_identifier}_{name}"
),
load_module_ident: format_ident!(
"__wasm_split_load_{module}_{unique_identifier}_{name}"
),
name,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/wasm-split/wasm-split/src/lib.rs | packages/wasm-split/wasm-split/src/lib.rs | use std::{
cell::Cell,
ffi::c_void,
future::Future,
pin::Pin,
rc::Rc,
task::{Context, Poll, Waker},
thread::LocalKey,
};
pub use wasm_split_macro::{lazy_loader, wasm_split};
pub type Result<T> = std::result::Result<T, SplitLoaderError>;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum SplitLoaderError {
FailedToLoad,
}
impl std::fmt::Display for SplitLoaderError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SplitLoaderError::FailedToLoad => write!(f, "Failed to load wasm-split module"),
}
}
}
/// A lazy loader that can be used to load a function from a split out `.wasm` file.
///
/// # Example
///
/// To use the split loader, you must first create the loader using the `lazy_loader` macro. This macro
/// requires the complete signature of the function you want to load. The extern abi string denotes
/// which module the function should be loaded from. If you don't know which module to use, use `auto`
/// and wasm-split will automatically combine all the modules into one.
///
/// ```rust, ignore
/// static LOADER: wasm_split::LazyLoader<Args, Ret> = wasm_split::lazy_loader!(extern "auto" fn SomeFunction(args: Args) -> Ret);
///
/// fn SomeFunction(args: Args) -> Ret {
/// // Implementation
/// }
/// ```
///
/// ## The `#[component(lazy)]` macro
///
/// If you're using wasm-split with Dioxus, the `#[component(lazy)]` macro is provided that wraps
/// the lazy loader with suspense. This means that the component will suspense until its body has
/// been loaded.
///
/// ```rust, ignore
/// fn app() -> Element {
/// rsx! {
/// Suspense {
/// fallback: rsx! { "Loading..." },
/// LazyComponent { abc: 0 }
/// }
/// }
/// }
///
/// #[component(lazy)]
/// fn LazyComponent(abc: i32) -> Element {
/// rsx! {
/// div {
/// "This is a lazy component! {abc}"
/// }
/// }
/// }
/// ```
pub struct LazyLoader<Args, Ret> {
imported: unsafe extern "C" fn(arg: Args) -> Ret,
key: &'static LocalKey<LazySplitLoader>,
}
impl<Args, Ret> LazyLoader<Args, Ret> {
/// Create a new lazy loader from a lazy imported function and a LazySplitLoader
///
/// # Safety
/// This is unsafe because we're taking an arbitrary function pointer and using it as the loader.
/// This function is likely not instantiated when passed here, so it should never be called directly.
#[doc(hidden)]
pub const unsafe fn new(
imported: unsafe extern "C" fn(arg: Args) -> Ret,
key: &'static LocalKey<LazySplitLoader>,
) -> Self {
Self { imported, key }
}
/// Create a new lazy loader that is already resolved.
pub const fn preloaded(f: fn(Args) -> Ret) -> Self {
let imported =
unsafe { std::mem::transmute::<fn(Args) -> Ret, unsafe extern "C" fn(Args) -> Ret>(f) };
thread_local! {
static LAZY: LazySplitLoader = LazySplitLoader::preloaded();
};
Self {
imported,
key: &LAZY,
}
}
/// Load the lazy loader, returning an boolean indicating whether it loaded successfully
pub async fn load(&'static self) -> bool {
*self.key.with(|inner| inner.lazy.clone()).as_ref().await
}
/// Call the lazy loader with the given arguments
pub fn call(&'static self, args: Args) -> Result<Ret> {
let Some(true) = self.key.with(|inner| inner.lazy.try_get().copied()) else {
return Err(SplitLoaderError::FailedToLoad);
};
Ok(unsafe { (self.imported)(args) })
}
}
type Lazy = async_once_cell::Lazy<bool, SplitLoaderFuture>;
type LoadCallbackFn = unsafe extern "C" fn(*const c_void, bool) -> ();
type LoadFn = unsafe extern "C" fn(LoadCallbackFn, *const c_void) -> ();
pub struct LazySplitLoader {
lazy: Pin<Rc<Lazy>>,
}
impl LazySplitLoader {
/// Create a new lazy split loader from a load function that is generated by the wasm-split macro
///
/// # Safety
///
/// This is unsafe because we're taking an arbitrary function pointer and using it as the loader.
/// It is likely not instantiated when passed here, so it should never be called directly.
#[doc(hidden)]
pub unsafe fn new(load: LoadFn) -> Self {
Self {
lazy: Rc::pin(Lazy::new({
SplitLoaderFuture {
loader: Rc::new(SplitLoader {
state: Cell::new(SplitLoaderState::Deferred(load)),
waker: Cell::new(None),
}),
}
})),
}
}
fn preloaded() -> Self {
Self {
lazy: Rc::pin(Lazy::new({
SplitLoaderFuture {
loader: Rc::new(SplitLoader {
state: Cell::new(SplitLoaderState::Completed(true)),
waker: Cell::new(None),
}),
}
})),
}
}
/// Wait for the lazy loader to load
pub async fn ensure_loaded(loader: &'static std::thread::LocalKey<LazySplitLoader>) -> bool {
*loader.with(|inner| inner.lazy.clone()).as_ref().await
}
}
struct SplitLoader {
state: Cell<SplitLoaderState>,
waker: Cell<Option<Waker>>,
}
#[derive(Clone, Copy)]
enum SplitLoaderState {
Deferred(LoadFn),
Pending,
Completed(bool),
}
struct SplitLoaderFuture {
loader: Rc<SplitLoader>,
}
impl Future for SplitLoaderFuture {
type Output = bool;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<bool> {
unsafe extern "C" fn load_callback(loader: *const c_void, success: bool) {
let loader = unsafe { Rc::from_raw(loader as *const SplitLoader) };
loader.state.set(SplitLoaderState::Completed(success));
if let Some(waker) = loader.waker.take() {
waker.wake()
}
}
match self.loader.state.get() {
SplitLoaderState::Deferred(load) => {
self.loader.state.set(SplitLoaderState::Pending);
self.loader.waker.set(Some(cx.waker().clone()));
unsafe {
load(
load_callback,
Rc::<SplitLoader>::into_raw(self.loader.clone()) as *const c_void,
)
};
Poll::Pending
}
SplitLoaderState::Pending => {
self.loader.waker.set(Some(cx.waker().clone()));
Poll::Pending
}
SplitLoaderState::Completed(value) => Poll::Ready(value),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/wasm-split/wasm-split-cli/src/lib.rs | packages/wasm-split/wasm-split-cli/src/lib.rs | use anyhow::{Context, Result};
use itertools::Itertools;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
hash::Hash,
ops::Range,
sync::{Arc, RwLock},
};
use walrus::{
ir::{self, dfs_in_order, Visitor},
ConstExpr, DataKind, ElementItems, ElementKind, ExportId, ExportItem, FunctionBuilder,
FunctionId, FunctionKind, GlobalKind, ImportId, ImportKind, Module, ModuleConfig, RefType,
TableId, TypeId,
};
use wasmparser::{
BinaryReader, Linking, LinkingSectionReader, Payload, RelocSectionReader, RelocationEntry,
SymbolInfo,
};
pub const MAKE_LOAD_JS: &str = include_str!("./__wasm_split.js");
/// A parsed wasm module with additional metadata and functionality for splitting and patching.
///
/// This struct assumes that relocations will be present in incoming wasm binary.
/// Upon construction, all the required metadata will be constructed.
pub struct Splitter<'a> {
/// The original module we use as a reference
source_module: Module,
// The byte sources of the pre and post wasm-bindgen .wasm files
// We need the original around since wasm-bindgen ruins the relocation locations.
original: &'a [u8],
bindgened: &'a [u8],
// Mapping of indices of source functions
// This lets us use a much faster approach to emitting split modules simply by maintaining a mapping
// between the original Module and the new Module. Ideally we could just index the new module
// with old FunctionIds but the underlying IndexMap actually checks that a key belongs to a particular
// arena.
fns_to_ids: HashMap<FunctionId, usize>,
_ids_to_fns: Vec<FunctionId>,
shared_symbols: BTreeSet<Node>,
split_points: Vec<SplitPoint>,
chunks: Vec<HashSet<Node>>,
data_symbols: BTreeMap<usize, DataSymbol>,
main_graph: HashSet<Node>,
call_graph: HashMap<Node, HashSet<Node>>,
parent_graph: HashMap<Node, HashSet<Node>>,
}
/// The results of splitting the wasm module with some additional metadata for later use.
pub struct OutputModules {
/// The main chunk
pub main: SplitModule,
/// The modules of the wasm module that were split.
pub modules: Vec<SplitModule>,
/// The chunks that might be imported by the main modules
pub chunks: Vec<SplitModule>,
}
/// A wasm module that was split from the main module.
///
/// All IDs here correspond to *this* module - not the parent main module
pub struct SplitModule {
pub module_name: String,
pub hash_id: Option<String>,
pub component_name: Option<String>,
pub bytes: Vec<u8>,
pub relies_on_chunks: HashSet<usize>,
}
impl<'a> Splitter<'a> {
/// Create a new "splitter" instance using the original wasm and the wasm from the output of wasm-bindgen.
///
/// This will use the relocation data from the original module to create a call graph that we
/// then use with the post-bindgened module to create the split modules.
///
/// It's important to compile the wasm with --emit-relocs such that the relocations are available
/// to construct the callgraph.
pub fn new(original: &'a [u8], bindgened: &'a [u8]) -> Result<Self> {
let (module, ids, fns_to_ids) = parse_module_with_ids(bindgened)?;
let split_points = accumulate_split_points(&module);
// Note that we can't trust the normal symbols - just the data symbols - and we can't use the data offset
// since that's not reliable after bindgening
let raw_data = parse_bytes_to_data_segment(bindgened)?;
let mut module = Self {
source_module: module,
original,
bindgened,
split_points,
data_symbols: raw_data.data_symbols,
_ids_to_fns: ids,
fns_to_ids,
main_graph: Default::default(),
chunks: Default::default(),
call_graph: Default::default(),
parent_graph: Default::default(),
shared_symbols: Default::default(),
};
module.build_call_graph()?;
module.build_split_chunks();
Ok(module)
}
/// Split the module into multiple modules at the boundaries of split points.
///
/// Note that the binaries might still be "large" at the end of this process. In practice, you
/// need to push these binaries through wasm-bindgen and wasm-opt to take advantage of the
/// optimizations and splitting. We perform a few steps like zero-ing out the data segments
/// that will only be removed by the memory-packing step of wasm-opt.
///
/// This returns the list of chunks, an import map, and some javascript to link everything together.
pub fn emit(self) -> Result<OutputModules> {
tracing::info!("Emitting split modules.");
let chunks = (0..self.chunks.len())
.into_par_iter()
.map(|idx| self.emit_split_chunk(idx))
.collect::<Result<Vec<SplitModule>>>()?;
let modules = (0..self.split_points.len())
.into_par_iter()
.map(|idx| self.emit_split_module(idx))
.collect::<Result<Vec<SplitModule>>>()?;
// Emit the main module, consuming self since we're going to
let main = self.emit_main_module()?;
Ok(OutputModules {
modules,
chunks,
main,
})
}
/// Emit the main module.
///
/// This will analyze the call graph and then perform some transformations on the module.
/// - Clear out active segments that the split modules will initialize
/// - Wipe away unused functions and data symbols
/// - Re-export the memories, globals, and other items that the split modules will need
/// - Convert the split module import functions to real functions that call the indirect function
///
/// Once this is done, all the split module functions will have been removed, making the main module smaller.
///
/// Emitting the main module is conceptually pretty simple. Emitting the split modules is more
/// complex.
fn emit_main_module(mut self) -> Result<SplitModule> {
tracing::info!("Emitting main bundle split module");
// Perform some analysis of the module before we start messing with it
let unused_symbols = self.unused_main_symbols();
// Use the original module that contains all the right ids
let mut out = std::mem::take(&mut self.source_module);
// 1. Clear out the active segments that try to initialize functions for modules we just split off.
// When the side modules load, they will initialize functions into the table where the "holes" are.
self.replace_segments_with_holes(&mut out, &unused_symbols);
// 2. Wipe away the unused functions and data symbols
self.prune_main_symbols(&mut out, &unused_symbols)?;
// 3. Change the functions called from split modules to be local functions that call the indirect function
self.create_ifunc_table(&mut out);
// 4. Re-export the memories, globals, and other stuff
self.re_export_items(&mut out);
// 6. Remove the reloc and linking custom sections
self.remove_custom_sections(&mut out);
// 7. Run the garbage collector to remove unused functions
walrus::passes::gc::run(&mut out);
Ok(SplitModule {
module_name: "main".to_string(),
component_name: None,
bytes: out.emit_wasm(),
relies_on_chunks: Default::default(),
hash_id: None,
})
}
/// Write the contents of the split modules to the output
fn emit_split_module(&self, split_idx: usize) -> Result<SplitModule> {
let split = self.split_points[split_idx].clone();
// These are the symbols that will only exist in this module and not in the main module.
let mut unique_symbols = split
.reachable_graph
.difference(&self.main_graph)
.cloned()
.collect::<HashSet<_>>();
// The functions we'll need to import
let mut symbols_to_import: HashSet<_> = split
.reachable_graph
.intersection(&self.main_graph)
.cloned()
.collect();
// Identify the functions we'll delete
let symbols_to_delete: HashSet<_> = self
.main_graph
.difference(&split.reachable_graph)
.cloned()
.collect();
// Convert split chunk functions to imports
let mut relies_on_chunks = HashSet::new();
for (idx, chunk) in self.chunks.iter().enumerate() {
let nodes_to_extract = unique_symbols
.intersection(chunk)
.cloned()
.collect::<Vec<_>>();
for node in nodes_to_extract {
if !self.main_graph.contains(&node) {
unique_symbols.remove(&node);
symbols_to_import.insert(node);
relies_on_chunks.insert(idx);
}
}
}
tracing::info!(
"Emitting module {}/{} {}: {:?}",
split_idx,
self.split_points.len(),
split.module_name,
relies_on_chunks
);
let (mut out, ids_to_fns, _fns_to_ids) = parse_module_with_ids(self.bindgened)?;
// Remap the graph to our module's IDs
let shared_funcs = self
.shared_symbols
.iter()
.map(|f| self.remap_id(&ids_to_fns, f))
.collect::<Vec<_>>();
let unique_symbols = self.remap_ids(&unique_symbols, &ids_to_fns);
let symbols_to_delete = self.remap_ids(&symbols_to_delete, &ids_to_fns);
let symbols_to_import = self.remap_ids(&symbols_to_import, &ids_to_fns);
let split_export_func = ids_to_fns[self.fns_to_ids[&split.export_func]];
// Do some basic cleanup of the module to make it smaller
// This removes exports, imports, and the start function
self.prune_split_module(&mut out);
// Clear away the data segments
self.clear_data_segments(&mut out, &unique_symbols);
// Clear out the element segments and then add in the initializers for the shared imports
self.create_ifunc_initializers(&mut out, &unique_symbols);
// Convert our split module's functions to real functions that call the indirect function
self.add_split_imports(
&mut out,
split.index,
split_export_func,
split.export_name,
&symbols_to_import,
&shared_funcs,
);
// Delete all the functions that are not reachable from the main module
self.delete_main_funcs_from_split(&mut out, &symbols_to_delete);
// Remove the reloc and linking custom sections
self.remove_custom_sections(&mut out);
// Run the gc to remove unused functions - also validates the module to ensure we can emit it properly
// todo(jon): prefer to delete the items as we go so we don't need to run a gc pass. it/it's quite slow
walrus::passes::gc::run(&mut out);
Ok(SplitModule {
bytes: out.emit_wasm(),
module_name: split.module_name.clone(),
component_name: Some(split.component_name.clone()),
relies_on_chunks,
hash_id: Some(split.hash_name.clone()),
})
}
/// Write a split chunk - this is a chunk with no special functions, just exports + initializers
fn emit_split_chunk(&self, idx: usize) -> Result<SplitModule> {
tracing::info!("emitting chunk {}", idx);
let unique_symbols = &self.chunks[idx];
// The functions we'll need to import
let symbols_to_import: HashSet<_> = unique_symbols
.intersection(&self.main_graph)
.cloned()
.collect();
// Delete everything except the symbols that are reachable from this module
let symbols_to_delete: HashSet<_> = self
.main_graph
.difference(unique_symbols)
.cloned()
.collect();
// Make sure to remap any ids from the main module to this module
let (mut out, ids_to_fns, _fns_to_ids) = parse_module_with_ids(self.bindgened)?;
// Remap the graph to our module's IDs
let shared_funcs = self
.shared_symbols
.iter()
.map(|f| self.remap_id(&ids_to_fns, f))
.collect::<Vec<_>>();
let unique_symbols = self.remap_ids(unique_symbols, &ids_to_fns);
let symbols_to_import = self.remap_ids(&symbols_to_import, &ids_to_fns);
let symbols_to_delete = self.remap_ids(&symbols_to_delete, &ids_to_fns);
self.prune_split_module(&mut out);
// Clear away the data segments
self.clear_data_segments(&mut out, &unique_symbols);
// Clear out the element segments and then add in the initializers for the shared imports
self.create_ifunc_initializers(&mut out, &unique_symbols);
// We have to make sure our table matches that of the other tables even though we don't call them.
let ifunc_table_id = self.load_funcref_table(&mut out);
let segment_start = self
.expand_ifunc_table_max(
&mut out,
ifunc_table_id,
self.split_points.len() + shared_funcs.len(),
)
.unwrap();
self.convert_shared_to_imports(&mut out, segment_start, &shared_funcs, &symbols_to_import);
// Make sure we haven't deleted anything important....
self.delete_main_funcs_from_split(&mut out, &symbols_to_delete);
// Remove the reloc and linking custom sections
self.remove_custom_sections(&mut out);
// Run the gc to remove unused functions - also validates the module to ensure we can emit it properly
walrus::passes::gc::run(&mut out);
Ok(SplitModule {
bytes: out.emit_wasm(),
module_name: "split".to_string(),
component_name: None,
relies_on_chunks: Default::default(),
hash_id: None,
})
}
/// Convert functions coming in from outside the module to indirect calls to the ifunc table created in the main module
fn convert_shared_to_imports(
&self,
out: &mut Module,
segment_start: usize,
ifuncs: &Vec<Node>,
symbols_to_import: &HashSet<Node>,
) {
let ifunc_table_id = self.load_funcref_table(out);
let mut idx = self.split_points.len();
for node in ifuncs {
if let Node::Function(ifunc) = node {
if symbols_to_import.contains(node) {
let ty_id = out.funcs.get(*ifunc).ty();
let stub = (idx + segment_start) as _;
out.funcs.get_mut(*ifunc).kind =
self.make_stub_funcs(out, ifunc_table_id, ty_id, stub);
}
idx += 1;
}
}
}
/// Convert split import functions to local functions that call an indirect function that will
/// be filled in from the loaded split module.
///
/// This is because these imports are going to be delayed until the split module is loaded
/// and loading in the main module these as imports won't be possible since the imports won't
/// be resolved until the split module is loaded.
fn create_ifunc_table(&self, out: &mut Module) {
let ifunc_table = self.load_funcref_table(out);
let dummy_func = self.make_dummy_func(out);
out.exports.add("__indirect_function_table", ifunc_table);
// Expand the ifunc table to accommodate the new ifuncs
let segment_start = self
.expand_ifunc_table_max(
out,
ifunc_table,
self.split_points.len() + self.shared_symbols.len(),
)
.expect("failed to expand ifunc table");
// Delete the split import functions and replace them with local functions
//
// Start by pushing all the shared imports into the list
// These don't require an additional stub function
let mut ifuncs = vec![];
// Push the split import functions into the list - after we've pushed in the shared imports
for idx in 0..self.split_points.len() {
// this is okay since we're in the main module
let import_func = self.split_points[idx].import_func;
let import_id = self.split_points[idx].import_id;
let ty_id = out.funcs.get(import_func).ty();
let stub_idx = segment_start + ifuncs.len();
// Replace the import function with a local function that calls the indirect function
out.funcs.get_mut(import_func).kind =
self.make_stub_funcs(out, ifunc_table, ty_id, stub_idx as _);
// And remove the corresponding import
out.imports.delete(import_id);
// Push into the list the properly typed dummy func so the entry is populated
// unclear if the typing is important here
ifuncs.push(dummy_func);
}
// Add the stub functions to the ifunc table
// The callers of these functions will call the stub instead of the import
let mut _idx = 0;
for func in self.shared_symbols.iter() {
if let Node::Function(id) = func {
ifuncs.push(*id);
_idx += 1;
}
}
// Now add segments to the ifunc table
out.tables
.get_mut(ifunc_table)
.elem_segments
.insert(out.elements.add(
ElementKind::Active {
table: ifunc_table,
offset: ConstExpr::Value(ir::Value::I32(segment_start as _)),
},
ElementItems::Functions(ifuncs),
));
}
/// Re-export the memories, globals, and other items from the main module to the side modules
fn re_export_items(&self, out: &mut Module) {
// Re-export memories
for (idx, memory) in out.memories.iter().enumerate() {
let name = memory
.name
.clone()
.unwrap_or_else(|| format!("__memory_{}", idx));
out.exports.add(&name, memory.id());
}
// Re-export globals
for (idx, global) in out.globals.iter().enumerate() {
let global_name = format!("__global__{idx}");
out.exports.add(&global_name, global.id());
}
// Export any tables
for (idx, table) in out.tables.iter().enumerate() {
if table.element_ty != RefType::Funcref {
let table_name = format!("__imported_table_{}", idx);
out.exports.add(&table_name, table.id());
}
}
}
fn prune_main_symbols(&self, out: &mut Module, unused_symbols: &HashSet<Node>) -> Result<()> {
// Wipe the split point exports
for split in self.split_points.iter() {
// it's okay that we're not re-mapping IDs since this is just used by the main module
out.exports.delete(split.export_id);
}
// And then any actual symbols from the callgraph
for symbol in unused_symbols.iter().cloned() {
match symbol {
// Simply delete functions
Node::Function(id) => {
out.funcs.delete(id);
}
// Otherwise, zero out the data segment, which should lead to elimination by wasm-opt
Node::DataSymbol(id) => {
let symbol = self
.data_symbols
.get(&id)
.context("Failed to find data symbol")?;
// VERY IMPORTANT
//
// apparently wasm-bindgen makes data segments that aren't the main one
// even *touching* those will break the vtable / binding layer
// We can only interact with the first data segment - the rest need to stay available
// for the `.js` to interact with.
if symbol.which_data_segment == 0 {
let data_id = out.data.iter().nth(symbol.which_data_segment).unwrap().id();
let data = out.data.get_mut(data_id);
for i in symbol.segment_offset..symbol.segment_offset + symbol.symbol_size {
data.value[i] = 0;
}
}
}
}
}
Ok(())
}
// 2.1 Create a dummy func that will be overridden later as modules pop in
// 2.2 swap the segment entries with the dummy func, leaving hole in its placed that will be filled in later
fn replace_segments_with_holes(&self, out: &mut Module, unused_symbols: &HashSet<Node>) {
let dummy_func = self.make_dummy_func(out);
for element in out.elements.iter_mut() {
match &mut element.items {
ElementItems::Functions(vec) => {
for item in vec.iter_mut() {
if unused_symbols.contains(&Node::Function(*item)) {
*item = dummy_func;
}
}
}
ElementItems::Expressions(_ref_type, const_exprs) => {
for item in const_exprs.iter_mut() {
if let &mut ConstExpr::RefFunc(id) = item {
if unused_symbols.contains(&Node::Function(id)) {
*item = ConstExpr::RefFunc(dummy_func);
}
}
}
}
}
}
}
/// Creates the jump points
fn create_ifunc_initializers(&self, out: &mut Module, unique_symbols: &HashSet<Node>) {
let ifunc_table = self.load_funcref_table(out);
let mut initializers = HashMap::new();
for segment in out.elements.iter_mut() {
let ElementKind::Active { offset, .. } = &mut segment.kind else {
continue;
};
let ConstExpr::Value(ir::Value::I32(offset)) = offset else {
continue;
};
match &segment.items {
ElementItems::Functions(vec) => {
for (idx, id) in vec.iter().enumerate() {
if unique_symbols.contains(&Node::Function(*id)) {
initializers
.insert(*offset + idx as i32, ElementItems::Functions(vec![*id]));
}
}
}
ElementItems::Expressions(ref_type, const_exprs) => {
for (idx, expr) in const_exprs.iter().enumerate() {
if let ConstExpr::RefFunc(id) = expr {
if unique_symbols.contains(&Node::Function(*id)) {
initializers.insert(
*offset + idx as i32,
ElementItems::Expressions(
*ref_type,
vec![ConstExpr::RefFunc(*id)],
),
);
}
}
}
}
}
}
// Wipe away references to these segments
for table in out.tables.iter_mut() {
table.elem_segments.clear();
}
// Wipe away the element segments themselves
let segments_to_delete: Vec<_> = out.elements.iter().map(|e| e.id()).collect();
for id in segments_to_delete {
out.elements.delete(id);
}
// Add in our new segments
let ifunc_table_ = out.tables.get_mut(ifunc_table);
for (offset, items) in initializers {
let kind = ElementKind::Active {
table: ifunc_table,
offset: ConstExpr::Value(ir::Value::I32(offset)),
};
ifunc_table_
.elem_segments
.insert(out.elements.add(kind, items));
}
}
fn add_split_imports(
&self,
out: &mut Module,
split_idx: usize,
split_export_func: FunctionId,
split_export_name: String,
symbols_to_import: &HashSet<Node>,
ifuncs: &Vec<Node>,
) {
let ifunc_table_id = self.load_funcref_table(out);
let segment_start = self
.expand_ifunc_table_max(out, ifunc_table_id, self.split_points.len() + ifuncs.len())
.unwrap();
// Make sure to re-export the split func
out.exports.add(&split_export_name, split_export_func);
// Add the elements back to the table
out.tables
.get_mut(ifunc_table_id)
.elem_segments
.insert(out.elements.add(
ElementKind::Active {
table: ifunc_table_id,
offset: ConstExpr::Value(ir::Value::I32((segment_start + split_idx) as i32)),
},
ElementItems::Functions(vec![split_export_func]),
));
self.convert_shared_to_imports(out, segment_start, ifuncs, symbols_to_import);
}
fn delete_main_funcs_from_split(&self, out: &mut Module, symbols_to_delete: &HashSet<Node>) {
for node in symbols_to_delete {
if let Node::Function(id) = *node {
// if out.exports.get_exported_func(id).is_none() {
out.funcs.delete(id);
// }
}
}
}
/// Remove un-needed stuff and then hoist
fn prune_split_module(&self, out: &mut Module) {
// Clear the module's start/main
if let Some(start) = out.start.take() {
if let Some(export) = out.exports.get_exported_func(start) {
out.exports.delete(export.id());
}
}
// We're going to import the funcref table, so wipe it altogether
for table in out.tables.iter_mut() {
table.elem_segments.clear();
}
// Wipe all our imports - we're going to use a different set of imports
let all_imports: HashSet<_> = out.imports.iter().map(|i| i.id()).collect();
for import_id in all_imports {
out.imports.delete(import_id);
}
// Wipe away memories
let all_memories: Vec<_> = out.memories.iter().map(|m| m.id()).collect();
for memory_id in all_memories {
out.memories.get_mut(memory_id).data_segments.clear();
}
// Add exports that call the corresponding import
let exports = out.exports.iter().map(|e| e.id()).collect::<Vec<_>>();
for export_id in exports {
out.exports.delete(export_id);
}
// Convert the tables to imports.
// Should be as simple as adding a new import and then writing the `.import` field
for (idx, table) in out.tables.iter_mut().enumerate() {
let name = table.name.clone().unwrap_or_else(|| {
if table.element_ty == RefType::Funcref {
"__indirect_function_table".to_string()
} else {
format!("__imported_table_{}", idx)
}
});
let import = out.imports.add("__wasm_split", &name, table.id());
table.import = Some(import);
}
// Convert the memories to imports
// Should be as simple as adding a new import and then writing the `.import` field
for (idx, memory) in out.memories.iter_mut().enumerate() {
let name = memory
.name
.clone()
.unwrap_or_else(|| format!("__memory_{}", idx));
let import = out.imports.add("__wasm_split", &name, memory.id());
memory.import = Some(import);
}
// Convert the globals to imports
// We might not use the global, so if we don't, we can just get
let global_ids: Vec<_> = out.globals.iter().map(|t| t.id()).collect();
for (idx, global_id) in global_ids.into_iter().enumerate() {
let global = out.globals.get_mut(global_id);
let global_name = format!("__global__{idx}");
let import = out.imports.add("__wasm_split", &global_name, global.id());
global.kind = GlobalKind::Import(import);
}
}
fn make_dummy_func(&self, out: &mut Module) -> FunctionId {
let mut b = FunctionBuilder::new(&mut out.types, &[], &[]);
b.name("dummy".into()).func_body().unreachable();
b.finish(vec![], &mut out.funcs)
}
fn clear_data_segments(&self, out: &mut Module, unique_symbols: &HashSet<Node>) {
// Preserve the data symbols for this module and then clear them away
let data_ids: Vec<_> = out.data.iter().map(|t| t.id()).collect();
for (idx, data_id) in data_ids.into_iter().enumerate() {
let data = out.data.get_mut(data_id);
// Take the data out of the vec - zeroing it out unless we patch it in manually
let contents = data.value.split_off(0);
// Zero out the non-primary data segments
if idx != 0 {
continue;
}
let DataKind::Active { memory, offset } = data.kind else {
continue;
};
let ConstExpr::Value(ir::Value::I32(data_offset)) = offset else {
continue;
};
// And then assign chunks of the data to new data entries that will override the individual slots
for unique in unique_symbols {
if let Node::DataSymbol(id) = unique {
if let Some(symbol) = self.data_symbols.get(id) {
if symbol.which_data_segment == idx {
let range =
symbol.segment_offset..symbol.segment_offset + symbol.symbol_size;
let offset = ConstExpr::Value(ir::Value::I32(
data_offset + symbol.segment_offset as i32,
));
out.data.add(
DataKind::Active { memory, offset },
contents[range].to_vec(),
);
}
}
}
}
}
}
/// Load the funcref table from the main module. This *should* exist for all modules created by
/// Rustc or Wasm-Bindgen, but we create it if it doesn't exist.
fn load_funcref_table(&self, out: &mut Module) -> TableId {
let ifunc_table = out
.tables
.iter()
.find(|t| t.element_ty == RefType::Funcref)
.map(|t| t.id());
if let Some(table) = ifunc_table {
table
} else {
out.tables.add_local(false, 0, None, RefType::Funcref)
}
}
/// Convert the imported function to a local function that calls an indirect function from the table
///
/// This will enable the main module (and split modules) to call functions from outside their own module.
/// The functions might not exist when the main module is loaded, so we'll register some elements
/// that fill those in eventually.
fn make_stub_funcs(
&self,
out: &mut Module,
table: TableId,
ty_id: TypeId,
table_idx: i32,
) -> FunctionKind {
// Convert the import function to a local function that calls the indirect function from the table
let ty = out.types.get(ty_id);
let params = ty.params().to_vec();
let results = ty.results().to_vec();
let args: Vec<_> = params.iter().map(|ty| out.locals.add(*ty)).collect();
// New function that calls the indirect function
let mut builder = FunctionBuilder::new(&mut out.types, ¶ms, &results);
let mut body = builder.name("stub".into()).func_body();
// Push the params onto the stack
for arg in args.iter() {
body.local_get(*arg);
}
// And then the address of the indirect function
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/wasm-split/wasm-split-cli/src/main.rs | packages/wasm-split/wasm-split-cli/src/main.rs | use clap::Parser;
use std::path::PathBuf;
use wasm_split_cli::SplitModule;
fn main() {
tracing_subscriber::fmt()
.without_time()
.compact()
.with_env_filter("debug,walrus=info")
.init();
match Commands::parse() {
Commands::Split(split_args) => split(split_args),
Commands::Validate(validate_args) => validate(validate_args),
}
}
#[derive(Parser)]
enum Commands {
/// Split a wasm module into multiple chunks
#[clap(name = "split")]
Split(SplitArgs),
/// Validate the main module of a wasm module
#[clap(name = "validate")]
Validate(ValidateArgs),
}
#[derive(Parser)]
struct SplitArgs {
/// The wasm module emitted by rustc
original: PathBuf,
/// The wasm module emitted by wasm-bindgen
bindgened: PathBuf,
/// The output *directory* to write the split wasm files to
out_dir: PathBuf,
}
fn split(args: SplitArgs) {
let original = std::fs::read(&args.original).expect("failed to read input file");
let bindgened = std::fs::read(&args.bindgened).expect("failed to read input file");
_ = std::fs::remove_dir_all(&args.out_dir);
std::fs::create_dir_all(&args.out_dir).expect("failed to create output dir");
tracing::info!("Building split module");
let module = wasm_split_cli::Splitter::new(&original, &bindgened).unwrap();
let mut chunks = module.emit().unwrap();
// Write out the main module
tracing::info!(
"Writing main module to {}",
args.out_dir.join("main.wasm").display()
);
std::fs::write(args.out_dir.join("main.wasm"), &chunks.main.bytes).unwrap();
// Write the js module
std::fs::write(
args.out_dir.join("__wasm_split.js"),
emit_js(&chunks.chunks, &chunks.modules),
)
.expect("failed to write js module");
for (idx, chunk) in chunks.chunks.iter().enumerate() {
tracing::info!(
"Writing chunk {} to {}",
idx,
args.out_dir
.join(format!("chunk_{}_{}.wasm", idx, chunk.module_name))
.display()
);
std::fs::write(
args.out_dir
.join(format!("chunk_{}_{}.wasm", idx, chunk.module_name)),
&chunk.bytes,
)
.expect("failed to write chunk");
}
for (idx, module) in chunks.modules.iter_mut().enumerate() {
tracing::info!(
"Writing module {} to {}",
idx,
args.out_dir
.join(format!(
"module_{}_{}.wasm",
idx,
module.component_name.as_ref().unwrap()
))
.display()
);
std::fs::write(
args.out_dir.join(format!(
"module_{}_{}.wasm",
idx,
module.component_name.as_ref().unwrap()
)),
&module.bytes,
)
.expect("failed to write chunk");
}
}
fn emit_js(chunks: &[SplitModule], modules: &[SplitModule]) -> String {
use std::fmt::Write;
let mut glue = format!(
r#"import {{ initSync }} from "./main.js";
{}"#,
include_str!("./__wasm_split.js")
);
for (idx, chunk) in chunks.iter().enumerate() {
tracing::debug!("emitting chunk: {:?}", chunk.module_name);
writeln!(
glue,
"export const __wasm_split_load_chunk_{idx} = makeLoad(\"/harness/split/chunk_{idx}_{module}.wasm\", [], fusedImports, initSync);",
module = chunk.module_name
).expect("failed to write to string");
}
// Now write the modules
for (idx, module) in modules.iter().enumerate() {
let deps = module
.relies_on_chunks
.iter()
.map(|idx| format!("__wasm_split_load_chunk_{idx}"))
.collect::<Vec<_>>()
.join(", ");
let hash_id = module.hash_id.as_ref().unwrap();
writeln!(
glue,
"export const __wasm_split_load_{module}_{hash_id}_{cname} = makeLoad(\"/harness/split/module_{idx}_{cname}.wasm\", [{deps}], fusedImports, initSync);",
module = module.module_name,
idx = idx,
cname = module.component_name.as_ref().unwrap(),
deps = deps
)
.expect("failed to write to string");
}
glue
}
#[derive(Parser)]
struct ValidateArgs {
/// The input wasm file to validate
main: PathBuf,
chunks: Vec<PathBuf>,
}
fn validate(args: ValidateArgs) {
let bytes = std::fs::read(&args.main).expect("failed to read input file");
let main_module = walrus::Module::from_buffer(&bytes).unwrap();
for chunk in args.chunks {
let bytes = std::fs::read(chunk).expect("failed to read input file");
let chunk_module = walrus::Module::from_buffer(&bytes).unwrap();
assert!(chunk_module.tables.iter().count() == 1);
for import in chunk_module.imports.iter() {
let matching = main_module.exports.iter().find(|e| e.name == import.name);
let Some(matching) = matching else {
tracing::error!("Could not find matching export for import {import:#?}");
continue;
};
tracing::debug!("import: {:?}", matching.name);
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/wasm-split/wasm-used/src/lib.rs | packages/wasm-split/wasm-used/src/lib.rs | use std::collections::HashSet;
use id_arena::Id;
use walrus::{ir::*, ExportId};
use walrus::{ConstExpr, Data, DataId, DataKind, Element, ExportItem, Function};
use walrus::{ElementId, ElementItems, ElementKind, Module, RefType, Type, TypeId};
use walrus::{FunctionId, FunctionKind, Global, GlobalId};
use walrus::{GlobalKind, Memory, MemoryId, Table, TableId};
type IdHashSet<T> = HashSet<Id<T>>;
/// Set of all root used items in a wasm module.
#[derive(Debug, Default)]
pub struct Roots {
tables: Vec<TableId>,
funcs: Vec<(FunctionId, Location)>,
globals: Vec<GlobalId>,
memories: Vec<MemoryId>,
data: Vec<DataId>,
elements: Vec<ElementId>,
used: Used,
}
#[allow(dead_code)]
#[derive(Debug)]
pub enum Location {
Start,
Export { export: ExportId },
Table { table: TableId },
Memory { memory: MemoryId },
Global { global: GlobalId },
Data,
Element { element: ElementId },
Code { func: FunctionId },
}
impl Roots {
/// Creates a new set of empty roots.
pub fn new() -> Roots {
Roots::default()
}
/// Adds a new function to the set of roots
pub fn push_func(&mut self, func: FunctionId, from: Location) -> &mut Roots {
if self.used.funcs.insert(func) {
// log::trace!("function is used: {:?}", func);
self.funcs.push((func, from));
}
self
}
/// Adds a new table to the set of roots
pub fn push_table(&mut self, table: TableId) -> &mut Roots {
if self.used.tables.insert(table) {
// log::trace!("table is used: {:?}", table);
self.tables.push(table);
}
self
}
/// Adds a new memory to the set of roots
pub fn push_memory(&mut self, memory: MemoryId) -> &mut Roots {
if self.used.memories.insert(memory) {
// log::trace!("memory is used: {:?}", memory);
self.memories.push(memory);
}
self
}
/// Adds a new global to the set of roots
pub fn push_global(&mut self, global: GlobalId) -> &mut Roots {
if self.used.globals.insert(global) {
// log::trace!("global is used: {:?}", global);
self.globals.push(global);
}
self
}
fn push_data(&mut self, data: DataId) -> &mut Roots {
if self.used.data.insert(data) {
// log::trace!("data is used: {:?}", data);
self.data.push(data);
}
self
}
fn push_element(&mut self, element: ElementId) -> &mut Roots {
if self.used.elements.insert(element) {
// log::trace!("element is used: {:?}", element);
self.elements.push(element);
}
self
}
}
/// Finds the things within a module that are used.
///
/// This is useful for implementing something like a linker's `--gc-sections` so
/// that our emitted `.wasm` binaries are small and don't contain things that
/// are not used.
#[derive(Debug, Default)]
pub struct Used {
/// The module's used tables.
pub tables: IdHashSet<Table>,
/// The module's used types.
pub types: IdHashSet<Type>,
/// The module's used functions.
pub funcs: IdHashSet<Function>,
/// The module's used globals.
pub globals: IdHashSet<Global>,
/// The module's used memories.
pub memories: IdHashSet<Memory>,
/// The module's used passive element segments.
pub elements: IdHashSet<Element>,
/// The module's used passive data segments.
pub data: IdHashSet<Data>,
}
impl Used {
/// Construct a new `Used` set for the given module.
pub fn new(module: &Module, deleted: &HashSet<FunctionId>) -> Used {
// log::debug!("starting to calculate used set");
let mut stack = Roots::default();
// All exports are roots
for export in module.exports.iter() {
match export.item {
ExportItem::Function(f) => stack.push_func(
f,
Location::Export {
export: export.id(),
},
),
ExportItem::Table(t) => stack.push_table(t),
ExportItem::Memory(m) => stack.push_memory(m),
ExportItem::Global(g) => stack.push_global(g),
};
}
// The start function is an implicit root as well
if let Some(f) = module.start {
stack.push_func(f, Location::Start);
}
// Initialization of memories or tables is a side-effectful operation
// because they can be out-of-bounds, so keep all active segments.
for data in module.data.iter() {
if let DataKind::Active { .. } = &data.kind {
stack.push_data(data.id());
}
}
for elem in module.elements.iter() {
match elem.kind {
// Active segments are rooted because they initialize imported
// tables.
ElementKind::Active { table, .. } => {
if module.tables.get(table).import.is_some() {
stack.push_element(elem.id());
}
}
// Declared segments can probably get gc'd but for now we're
// conservative and we root them
ElementKind::Declared => {
stack.push_element(elem.id());
}
ElementKind::Passive => {}
}
}
// // And finally ask custom sections for their roots
// for (_id, section) in module.customs.iter() {
// section.add_gc_roots(&mut stack);
// }
// tracing::info!("Used roots: {:#?}", stack);
// Iteratively visit all items until our stack is empty
while !stack.funcs.is_empty()
|| !stack.tables.is_empty()
|| !stack.memories.is_empty()
|| !stack.globals.is_empty()
|| !stack.data.is_empty()
|| !stack.elements.is_empty()
{
while let Some((f, _loc)) = stack.funcs.pop() {
if deleted.contains(&f) {
let func = module.funcs.get(f);
let name = func
.name
.as_ref()
.cloned()
.unwrap_or_else(|| format!("unknown - {}", f.index()));
// panic!(
// "Found a function that should be deleted but is still used: {:?} - {:?}",
// name, f
// );
tracing::error!(
"Found a function that should be deleted but is still used: {:?} - {:?} - {:?}",
name,
f,
_loc
);
if let Location::Code { func } = _loc {
let func_name = module.funcs.get(func).name.as_ref().unwrap();
tracing::error!("Function {:?} is used by {:?}", f, func_name);
}
// continue;
}
let func = module.funcs.get(f);
stack.used.types.insert(func.ty());
match &func.kind {
FunctionKind::Local(func) => {
let mut visitor = UsedVisitor {
cur_func: f,
stack: &mut stack,
};
dfs_in_order(&mut visitor, func, func.entry_block());
}
FunctionKind::Import(_) => {}
FunctionKind::Uninitialized(_) => unreachable!(),
}
}
while let Some(t) = stack.tables.pop() {
for elem in module.tables.get(t).elem_segments.iter() {
stack.push_element(*elem);
}
}
while let Some(t) = stack.globals.pop() {
match &module.globals.get(t).kind {
GlobalKind::Import(_) => {}
GlobalKind::Local(ConstExpr::Global(global)) => {
stack.push_global(*global);
}
GlobalKind::Local(ConstExpr::RefFunc(func)) => {
stack.push_func(*func, Location::Global { global: t });
}
GlobalKind::Local(ConstExpr::Value(_))
| GlobalKind::Local(ConstExpr::RefNull(_)) => {}
}
}
while let Some(t) = stack.memories.pop() {
for data in &module.memories.get(t).data_segments {
stack.push_data(*data);
}
}
while let Some(d) = stack.data.pop() {
let d = module.data.get(d);
if let DataKind::Active { memory, offset } = &d.kind {
stack.push_memory(*memory);
if let ConstExpr::Global(g) = offset {
stack.push_global(*g);
}
}
}
while let Some(e) = stack.elements.pop() {
let e = module.elements.get(e);
if let ElementItems::Functions(function_ids) = &e.items {
function_ids.iter().for_each(|f| {
stack.push_func(*f, Location::Element { element: e.id() });
});
}
if let ElementItems::Expressions(RefType::Funcref, items) = &e.items {
for item in items {
match item {
ConstExpr::Global(g) => {
stack.push_global(*g);
}
ConstExpr::RefFunc(f) => {
stack.push_func(*f, Location::Element { element: e.id() });
}
_ => {}
}
}
}
if let ElementKind::Active { offset, table } = &e.kind {
if let ConstExpr::Global(g) = offset {
stack.push_global(*g);
}
stack.push_table(*table);
}
}
}
// Wabt seems to have weird behavior where a `data` segment, if present
// even if passive, requires a `memory` declaration. Our GC pass is
// pretty aggressive and if you have a passive data segment and only
// `data.drop` instructions you technically don't need the `memory`.
// Let's keep `wabt` passing though and just say that if there are data
// segments kept, but no memories, then we try to add the first memory,
// if any, to the used set.
if !stack.used.data.is_empty() && stack.used.memories.is_empty() {
if let Some(mem) = module.memories.iter().next() {
stack.used.memories.insert(mem.id());
}
}
stack.used
}
}
struct UsedVisitor<'a> {
cur_func: FunctionId,
stack: &'a mut Roots,
}
impl Visitor<'_> for UsedVisitor<'_> {
fn visit_function_id(&mut self, &func: &FunctionId) {
self.stack.push_func(
func,
Location::Code {
func: self.cur_func,
},
);
}
fn visit_memory_id(&mut self, &m: &MemoryId) {
self.stack.push_memory(m);
}
fn visit_global_id(&mut self, &g: &GlobalId) {
self.stack.push_global(g);
}
fn visit_table_id(&mut self, &t: &TableId) {
self.stack.push_table(t);
}
fn visit_type_id(&mut self, &t: &TypeId) {
self.stack.used.types.insert(t);
}
fn visit_data_id(&mut self, &d: &DataId) {
self.stack.push_data(d);
}
fn visit_element_id(&mut self, &e: &ElementId) {
self.stack.push_element(e);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html-internal-macro/src/lib.rs | packages/html-internal-macro/src/lib.rs | use proc_macro::TokenStream;
use convert_case::{Case, Casing};
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{braced, parse_macro_input, Ident, Token};
#[proc_macro]
pub fn impl_extension_attributes(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ImplExtensionAttributes);
input.to_token_stream().into()
}
struct ImplExtensionAttributes {
name: Ident,
attrs: Punctuated<Ident, Token![,]>,
}
impl Parse for ImplExtensionAttributes {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;
let name = input.parse()?;
braced!(content in input);
let attrs = content.parse_terminated(Ident::parse, Token![,])?;
Ok(ImplExtensionAttributes { name, attrs })
}
}
impl ToTokens for ImplExtensionAttributes {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let name = &self.name;
let name_string = name.to_string();
let camel_name = name_string
.strip_prefix("r#")
.unwrap_or(&name_string)
.to_case(Case::UpperCamel);
let extension_name = Ident::new(format!("{}Extension", &camel_name).as_str(), name.span());
let impls = self.attrs.iter().map(|ident| {
let d = quote! { #name::#ident };
quote! {
fn #ident(self, value: impl IntoAttributeValue) -> Self {
let d = #d;
self.push_attribute(d.0, d.1, value, d.2)
}
}
});
tokens.append_all(quote! {
pub trait #extension_name: HasAttributes + Sized {
#(#impls)*
}
});
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html-internal-macro/tests/01-simple.rs | packages/html-internal-macro/tests/01-simple.rs | fn main() {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html-internal-macro/tests/progress.rs | packages/html-internal-macro/tests/progress.rs | #[test]
fn tests() {
let t = trybuild::TestCases::new();
t.pass("tests/01-simple.rs");
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/build.rs | packages/desktop/build.rs | use std::{io::Write as _, path::PathBuf};
fn check_gnu() {
// WARN about wry support on windows gnu targets. GNU windows targets don't work well in wry currently
if std::env::var("CARGO_CFG_WINDOWS").is_ok()
&& std::env::var("CARGO_CFG_TARGET_ENV").unwrap() == "gnu"
&& !cfg!(feature = "gnu")
{
println!("cargo:warning=GNU windows targets have some limitations within Wry. Using the MSVC windows toolchain is recommended. If you would like to use continue using GNU, you can read https://github.com/wravery/webview2-rs#cross-compilation and disable this warning by adding the gnu feature to dioxus-desktop in your Cargo.toml")
}
// To prepare for a release, we add extra examples to desktop for doc scraping and copy assets from the workspace to make those examples compile
if option_env!("DIOXUS_RELEASE").is_some() {
// Append EXAMPLES_TOML to the cargo.toml
let cargo_toml = std::fs::OpenOptions::new()
.append(true)
.open("Cargo.toml")
.unwrap();
let mut write = std::io::BufWriter::new(cargo_toml);
write.write_all(EXAMPLES_TOML.as_bytes()).unwrap();
// Copy the assets from the workspace to the examples directory
let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let workspace_dir = crate_dir.parent().unwrap().parent().unwrap();
let workspace_assets_dir = workspace_dir.join("examples").join("assets");
let desktop_assets_dir = PathBuf::from("examples").join("assets");
std::fs::create_dir_all(&desktop_assets_dir).unwrap();
// move all files from the workspace assets dir to the desktop assets dir
for entry in std::fs::read_dir(workspace_assets_dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_file() {
std::fs::copy(&path, desktop_assets_dir.join(path.file_name().unwrap())).unwrap();
}
}
}
}
fn compile_ts() {
// If any TS files change, re-run the build script
lazy_js_bundle::LazyTypeScriptBindings::new()
.with_watching("./src/ts")
.with_binding("./src/ts/native_eval.ts", "./src/js/native_eval.js")
.run();
}
fn main() {
check_gnu();
compile_ts();
}
const EXAMPLES_TOML: &str = r#"
# Most of the examples live in the workspace. We include some here so that docs.rs can scrape our examples for better inline docs
[[example]]
name = "video_stream"
path = "../../examples/video_stream.rs"
doc-scrape-examples = true
[[example]]
name = "suspense"
path = "../../examples/suspense.rs"
doc-scrape-examples = true
[[example]]
name = "calculator_mutable"
path = "../../examples/calculator_mutable.rs"
doc-scrape-examples = true
[[example]]
name = "custom_html"
path = "../../examples/custom_html.rs"
doc-scrape-examples = true
[[example]]
name = "custom_menu"
path = "../../examples/custom_menu.rs"
doc-scrape-examples = true
[[example]]
name = "errors"
path = "../../examples/errors.rs"
doc-scrape-examples = true
[[example]]
name = "future"
path = "../../examples/future.rs"
doc-scrape-examples = true
[[example]]
name = "hydration"
path = "../../examples/hydration.rs"
doc-scrape-examples = true
[[example]]
name = "multiwindow"
path = "../../examples/multiwindow.rs"
doc-scrape-examples = true
[[example]]
name = "overlay"
path = "../../examples/overlay.rs"
doc-scrape-examples = true
[[example]]
name = "popup"
path = "../../examples/popup.rs"
doc-scrape-examples = true
[[example]]
name = "read_size"
path = "../../examples/read_size.rs"
doc-scrape-examples = true
[[example]]
name = "shortcut"
path = "../../examples/shortcut.rs"
doc-scrape-examples = true
[[example]]
name = "streams"
path = "../../examples/streams.rs"
doc-scrape-examples = true
[[example]]
name = "window_event"
path = "../../examples/window_event.rs"
doc-scrape-examples = true
[[example]]
name = "window_focus"
path = "../../examples/window_focus.rs"
doc-scrape-examples = true
[[example]]
name = "window_zoom"
path = "../../examples/window_zoom.rs"
doc-scrape-examples = true"#;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/headless_tests/rendering.rs | packages/desktop/headless_tests/rendering.rs | use dioxus::prelude::*;
use dioxus_desktop::DesktopContext;
#[path = "./utils.rs"]
mod utils;
fn main() {
#[cfg(not(windows))]
utils::check_app_exits(check_html_renders);
}
fn use_inner_html(id: &'static str) -> Option<String> {
let mut value = use_signal(|| None as Option<String>);
use_effect(move || {
spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let res = document::eval(&format!(
r#"let element = document.getElementById('{id}');
return element.innerHTML"#
))
.await
.unwrap();
if let Some(html) = res.as_str() {
println!("html: {html}");
value.set(Some(html.to_string()));
}
});
});
value()
}
const EXPECTED_HTML: &str = r#"<div style="width: 100px; height: 100px; color: rgb(0, 0, 0);" id="5"><input type="checkbox"><h1>text</h1><div><p>hello world</p></div></div>"#;
fn check_html_renders() -> Element {
let inner_html = use_inner_html("main_div");
let desktop_context: DesktopContext = consume_context();
if let Some(raw_html) = inner_html {
println!("{raw_html}");
let fragment = &raw_html;
let expected = EXPECTED_HTML;
assert_eq!(raw_html, EXPECTED_HTML);
if fragment == expected {
println!("html matches");
desktop_context.close();
}
}
let dyn_value = 0;
let dyn_element = rsx! { div { dangerous_inner_html: "<p>hello world</p>" } };
rsx! {
div { id: "main_div",
div {
width: "100px",
height: "100px",
color: "rgb({dyn_value}, {dyn_value}, {dyn_value})",
id: 5,
input { "type": "checkbox" }
h1 { "text" }
{dyn_element}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/headless_tests/utils.rs | packages/desktop/headless_tests/utils.rs | #![allow(unused)] // for whatever reason, the compiler is not recognizing the use of these functions
use dioxus::prelude::*;
use dioxus_core::Element;
pub fn check_app_exits(app: fn() -> Element) {
use dioxus_desktop::tao::window::WindowBuilder;
use dioxus_desktop::Config;
// This is a deadman's switch to ensure that the app exits
let should_panic = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let should_panic_clone = should_panic.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(60));
if should_panic_clone.load(std::sync::atomic::Ordering::SeqCst) {
eprintln!("App did not exit in time");
std::process::exit(exitcode::SOFTWARE);
}
});
dioxus::LaunchBuilder::desktop()
.with_cfg(Config::new().with_window(WindowBuilder::new().with_visible(false)))
.launch(app);
// Stop deadman's switch
should_panic.store(false, std::sync::atomic::Ordering::SeqCst);
}
pub static EXPECTED_EVENTS: GlobalSignal<usize> = Signal::global(|| 0);
pub fn mock_event(id: &'static str, value: &'static str) {
mock_event_with_extra(id, value, "");
}
pub fn mock_event_with_extra(id: &'static str, value: &'static str, extra: &'static str) {
use_hook(move || {
EXPECTED_EVENTS.with_mut(|x| *x += 1);
spawn(async move {
// We need to wait for edits to be applied before we can send the event
// Sometimes (windows...) this takes a while
// we should really be running this check when mounted
tokio::time::sleep(std::time::Duration::from_millis(10000)).await;
let js = format!(
r#"
let event = {value};
let element = document.getElementById('{id}');
{extra}
element.dispatchEvent(event);
"#
);
document::eval(&js).await.unwrap();
});
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/headless_tests/eval.rs | packages/desktop/headless_tests/eval.rs | use dioxus::prelude::*;
use dioxus_desktop::window;
use serde::Deserialize;
#[path = "./utils.rs"]
mod utils;
pub fn main() {
#[cfg(not(windows))]
utils::check_app_exits(app);
}
static EVALS_RECEIVED: GlobalSignal<usize> = Signal::global(|| 0);
static EVALS_RETURNED: GlobalSignal<usize> = Signal::global(|| 0);
fn app() -> Element {
// Double 100 values in the value
use_future(|| async {
let mut eval = document::eval(
r#"for (let i = 0; i < 100; i++) {
let value = await dioxus.recv();
dioxus.send(value*2);
}"#,
);
for i in 0..100 {
eval.send(i).unwrap();
let value: i32 = eval.recv().await.unwrap();
assert_eq!(value, i * 2);
EVALS_RECEIVED.with_mut(|x| *x += 1);
}
});
// Make sure returning no value resolves the future
use_future(|| async {
let eval = document::eval(r#"return;"#);
eval.await.unwrap();
EVALS_RETURNED.with_mut(|x| *x += 1);
});
// Return a value from the future
use_future(|| async {
let eval = document::eval(
r#"
return [1, 2, 3];
"#,
);
assert_eq!(
Vec::<i32>::deserialize(&eval.await.unwrap()).unwrap(),
vec![1, 2, 3]
);
EVALS_RETURNED.with_mut(|x| *x += 1);
});
use_memo(|| {
println!("expected 100 evals received found {}", EVALS_RECEIVED());
println!("expected 2 eval returned found {}", EVALS_RETURNED());
if EVALS_RECEIVED() == 100 && EVALS_RETURNED() == 2 {
window().close();
}
});
VNode::empty()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/headless_tests/forms.rs | packages/desktop/headless_tests/forms.rs | use dioxus::prelude::*;
use dioxus_desktop::DesktopContext;
use dioxus_document::eval;
#[path = "./utils.rs"]
mod utils;
fn main() {
#[cfg(not(windows))]
utils::check_app_exits(check_html_renders);
}
async fn inner_html(count: usize) -> String {
let html = document::eval(&format!(
r#"// Wait until the element is available
const interval = setInterval(() => {{
const element = document.getElementById('div-{count}');
if (element) {{
dioxus.send(element.innerHTML);
clearInterval(interval);
}}
}}, 100);"#
))
.recv::<String>()
.await
.unwrap();
println!("html: {html}");
html
}
fn check_html_renders() -> Element {
let mut signal = use_signal(|| 0);
use_effect(move || {
let signal = signal();
// Pass the test once the count is greater than 10
if signal > 10 {
let desktop_context: DesktopContext = consume_context();
desktop_context.close();
}
spawn(async move {
let raw_html = inner_html(signal).await;
println!("{raw_html}");
// Make sure the html contains count is {signal}
assert!(raw_html.contains(&format!("count is {}", signal)));
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
eval(
r#"let button = document.querySelector('#increment');
button.dispatchEvent(new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true,
buttons: 2,
button: 2,
}));"#,
);
// If the signal is even, also submit the form. This should not effect the count because the navigation is blocked
if signal % 2 == 0 {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
eval(
r#"let form = document.getElementById('form-submit');
form.dispatchEvent(new Event('click', {
view: window,
bubbles: true,
cancelable: true,
buttons: 2,
button: 2,
}));"#,
);
}
});
});
rsx! {
div {
id: "div-{signal}",
h1 { "Form" }
form {
input {
r#type: "text",
name: "username",
id: "username",
value: "goodbye"
}
input { r#type: "text", name: "full-name", value: "lorem" }
input { r#type: "password", name: "password", value: "ipsum" }
input {
r#type: "radio",
name: "color",
value: "red",
checked: true
}
input { r#type: "radio", name: "color", value: "blue" }
button { id: "form-submit", r#type: "submit", value: "Submit", "Submit the form" }
}
button {
id: "increment",
onclick: move |_| {
signal += 1;
},
"count is {signal}"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/headless_tests/events.rs | packages/desktop/headless_tests/events.rs | use dioxus::html::geometry::euclid::Vector3D;
use dioxus::prelude::*;
use dioxus_desktop::DesktopContext;
#[path = "./utils.rs"]
mod utils;
pub fn main() {
#[cfg(not(windows))]
utils::check_app_exits(app);
}
static RECEIVED_EVENTS: GlobalSignal<usize> = Signal::global(|| 0);
fn app() -> Element {
let desktop_context: DesktopContext = consume_context();
let received = RECEIVED_EVENTS();
let expected = utils::EXPECTED_EVENTS();
use_memo(move || {
println!("expecting {} events", utils::EXPECTED_EVENTS());
println!("received {} events", RECEIVED_EVENTS());
});
if expected != 0 && received == expected {
println!("all events received");
desktop_context.close();
}
rsx! {
div {
test_mounted {}
test_button {}
test_mouse_move_div {}
test_mouse_click_div {}
test_mouse_dblclick_div {}
test_mouse_down_div {}
test_mouse_up_div {}
test_mouse_scroll_div {}
test_key_down_div {}
test_key_up_div {}
test_key_press_div {}
test_focus_in_div {}
test_focus_out_div {}
test_form_input {}
test_form_submit {}
test_select_multiple_options {}
test_unicode {}
}
}
}
fn test_mounted() -> Element {
use_hook(|| utils::EXPECTED_EVENTS.with_mut(|x| *x += 1));
let mut onmounted_triggered = use_signal(|| false);
rsx! {
div {
width: "100px",
height: "100px",
onmounted: move |evt| async move {
let rect = evt.get_client_rect().await.unwrap();
println!("rect: {rect:?}");
assert_eq!(rect.width(), 100.0);
assert_eq!(rect.height(), 100.0);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
// Onmounted should only be called once
let mut onmounted_triggered_write = onmounted_triggered.write();
assert!(!*onmounted_triggered_write);
*onmounted_triggered_write = true;
}
}
}
}
fn test_button() -> Element {
utils::mock_event(
"button",
r#"new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
button: 0,
})"#,
);
rsx! {
button {
id: "button",
onclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().is_empty());
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Primary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_move_div() -> Element {
utils::mock_event(
"mouse_move_div",
r#"new MouseEvent("mousemove", {
view: window,
bubbles: true,
cancelable: true,
buttons: 2,
})"#,
);
rsx! {
div {
id: "mouse_move_div",
onmousemove: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_click_div() -> Element {
utils::mock_event(
"mouse_click_div",
r#"new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
buttons: 2,
button: 2,
})"#,
);
rsx! {
div {
id: "mouse_click_div",
onclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_dblclick_div() -> Element {
utils::mock_event(
"mouse_dblclick_div",
r#"new MouseEvent("dblclick", {
view: window,
bubbles: true,
cancelable: true,
buttons: 1|2,
button: 2,
})"#,
);
rsx! {
div {
id: "mouse_dblclick_div",
ondoubleclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Primary),
);
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_down_div() -> Element {
utils::mock_event(
"mouse_down_div",
r#"new MouseEvent("mousedown", {
view: window,
bubbles: true,
cancelable: true,
buttons: 2,
button: 2,
})"#,
);
rsx! {
div {
id: "mouse_down_div",
onmousedown: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_up_div() -> Element {
utils::mock_event(
"mouse_up_div",
r#"new MouseEvent("mouseup", {
view: window,
bubbles: true,
cancelable: true,
buttons: 0,
button: 0,
})"#,
);
rsx! {
div {
id: "mouse_up_div",
onmouseup: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().is_empty());
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Primary),
);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_mouse_scroll_div() -> Element {
utils::mock_event(
"wheel_div",
r#"new WheelEvent("wheel", {
view: window,
deltaX: 1.0,
deltaY: 2.0,
deltaZ: 3.0,
deltaMode: 0x00,
bubbles: true,
})"#,
);
rsx! {
div {
id: "wheel_div",
width: "100px",
height: "100px",
background_color: "red",
onwheel: move |event| {
println!("{:?}", event.data);
let dioxus_html::geometry::WheelDelta::Pixels(delta) = event.data.delta() else {
panic!("Expected delta to be in pixels")
};
assert_eq!(delta, Vector3D::new(1.0, 2.0, 3.0));
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_key_down_div() -> Element {
utils::mock_event(
"key_down_div",
r#"new KeyboardEvent("keydown", {
key: "a",
code: "KeyA",
location: 0,
repeat: true,
keyCode: 65,
charCode: 97,
char: "a",
charCode: 0,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
isComposing: true,
which: 65,
bubbles: true,
})"#,
);
rsx! {
input {
id: "key_down_div",
onkeydown: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location(), Location::Standard);
assert!(event.data.is_auto_repeating());
assert!(event.data.is_composing());
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_key_up_div() -> Element {
utils::mock_event(
"key_up_div",
r#"new KeyboardEvent("keyup", {
key: "a",
code: "KeyA",
location: 0,
repeat: false,
keyCode: 65,
charCode: 97,
char: "a",
charCode: 0,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
isComposing: false,
which: 65,
bubbles: true,
})"#,
);
rsx! {
input {
id: "key_up_div",
onkeyup: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location(), Location::Standard);
assert!(!event.data.is_auto_repeating());
assert!(!event.data.is_composing());
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_key_press_div() -> Element {
utils::mock_event(
"key_press_div",
r#"new KeyboardEvent("keypress", {
key: "a",
code: "KeyA",
location: 0,
repeat: false,
keyCode: 65,
charCode: 97,
char: "a",
charCode: 0,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
isComposing: false,
which: 65,
bubbles: true,
})"#,
);
rsx! {
input {
id: "key_press_div",
onkeypress: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location(), Location::Standard);
assert!(!event.data.is_auto_repeating());
assert!(!event.data.is_composing());
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_focus_in_div() -> Element {
utils::mock_event(
"focus_in_div",
r#"new FocusEvent("focusin", {bubbles: true})"#,
);
rsx! {
input {
id: "focus_in_div",
onfocusin: move |event| {
println!("{:?}", event.data);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_focus_out_div() -> Element {
utils::mock_event(
"focus_out_div",
r#"new FocusEvent("focusout",{bubbles: true})"#,
);
rsx! {
input {
id: "focus_out_div",
onfocusout: move |event| {
println!("{:?}", event.data);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
fn test_form_input() -> Element {
let mut values = use_signal(Vec::new);
utils::mock_event_with_extra(
"form-username",
r#"new Event("input", { bubbles: true, cancelable: true, composed: true })"#,
r#"element.value = "hello";"#,
);
let set_username = move |ev: FormEvent| {
values.set(ev.values());
// The value of the input should match
assert_eq!(ev.value(), "hello");
// And then the value the form gives us should also match
values.with_mut(|x| {
assert_eq!(x.iter().find(|f| f.0 == "username").unwrap().1, "hello");
assert_eq!(x.iter().find(|f| f.0 == "full-name").unwrap().1, "lorem");
assert_eq!(x.iter().find(|f| f.0 == "password").unwrap().1, "ipsum");
assert_eq!(x.iter().find(|f| f.0 == "color").unwrap().1, "red");
});
RECEIVED_EVENTS.with_mut(|x| *x += 1);
};
rsx! {
div {
h1 { "Form" }
form {
id: "form",
oninput: move |ev| {
values.set(ev.values());
},
onsubmit: move |ev| {
println!("{ev:?}");
},
input {
r#type: "text",
name: "username",
id: "form-username",
oninput: set_username
}
input { r#type: "text", name: "full-name", value: "lorem" }
input { r#type: "password", name: "password", value: "ipsum" }
input {
r#type: "radio",
name: "color",
value: "red",
checked: true
}
input { r#type: "radio", name: "color", value: "blue" }
button { r#type: "submit", value: "Submit", "Submit the form" }
}
}
}
}
fn test_form_submit() -> Element {
let mut values = use_signal(Vec::new);
utils::mock_event_with_extra(
"form-submitter",
r#"new Event("submit", { bubbles: true, cancelable: true, composed: true })"#,
r#"element.submit();"#,
);
let set_values = move |ev: FormEvent| {
values.set(ev.values());
values.with_mut(|x| {
assert_eq!(x.iter().find(|f| f.0 == "username").unwrap().1, "goodbye");
assert_eq!(x.iter().find(|f| f.0 == "full-name").unwrap().1, "lorem");
assert_eq!(x.iter().find(|f| f.0 == "password").unwrap().1, "ipsum");
assert_eq!(x.iter().find(|f| f.0 == "color").unwrap().1, "red");
});
RECEIVED_EVENTS.with_mut(|x| *x += 1);
};
rsx! {
div {
h1 { "Form" }
form { id: "form-submitter", onsubmit: set_values,
input {
r#type: "text",
name: "username",
id: "username",
value: "goodbye"
}
input { r#type: "text", name: "full-name", value: "lorem" }
input { r#type: "password", name: "password", value: "ipsum" }
input {
r#type: "radio",
name: "color",
value: "red",
checked: true
}
input { r#type: "radio", name: "color", value: "blue" }
button { r#type: "submit", value: "Submit", "Submit the form" }
}
}
}
}
fn test_select_multiple_options() -> Element {
utils::mock_event_with_extra(
"select-many",
r#"new Event("input", { bubbles: true, cancelable: true, composed: true })"#,
r#"
document.getElementById('usa').selected = true;
document.getElementById('canada').selected = true;
document.getElementById('mexico').selected = false;
"#,
);
rsx! {
select {
id: "select-many",
name: "country",
multiple: true,
oninput: move |ev| {
let values = ev.value();
let values = values.split(',').collect::<Vec<_>>();
assert_eq!(values, vec!["usa", "canada"]);
RECEIVED_EVENTS.with_mut(|x| *x += 1);
},
option { id: "usa", value: "usa", "USA" }
option { id: "canada", value: "canada", "Canada" }
option { id: "mexico", value: "mexico", selected: true, "Mexico" }
}
}
}
fn test_unicode() -> Element {
// emulate an oninput event with a unicode character
utils::mock_event_with_extra(
"unicode",
r#"new InputEvent("input", {
inputType: 'insertText',
bubbles: true,
cancelable: true,
})"#,
r#"
element.value = "🦀";
"#,
);
rsx! {
input {
id: "unicode",
oninput: move |event| {
println!("{:?}", event.data);
assert_eq!(event.data.value(), "🦀");
RECEIVED_EVENTS.with_mut(|x| *x += 1);
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/desktop_context.rs | packages/desktop/src/desktop_context.rs | use crate::{
app::SharedContext,
assets::AssetHandlerRegistry,
file_upload::NativeFileHover,
ipc::UserWindowEvent,
query::QueryEngine,
shortcut::{HotKey, HotKeyState, ShortcutHandle, ShortcutRegistryError},
webview::PendingWebview,
AssetRequest, Config, WindowCloseBehaviour, WryEventHandler,
};
use dioxus_core::{Callback, VirtualDom};
use std::{
cell::Cell,
future::{Future, IntoFuture},
pin::Pin,
rc::{Rc, Weak},
sync::Arc,
};
use tao::{
event::Event,
event_loop::EventLoopWindowTarget,
window::{Fullscreen as WryFullscreen, Window, WindowId},
};
use wry::{RequestAsyncResponder, WebView};
#[cfg(target_os = "ios")]
use tao::platform::ios::WindowExtIOS;
/// Get an imperative handle to the current window without using a hook
///
/// ## Panics
///
/// This function will panic if it is called outside of the context of a Dioxus App.
pub fn window() -> DesktopContext {
dioxus_core::consume_context()
}
/// A handle to the [`DesktopService`] that can be passed around.
pub type DesktopContext = Rc<DesktopService>;
/// A weak handle to the [`DesktopService`] to ensure safe passing.
/// The problem without this is that the tao window is never dropped and therefore cannot be closed.
/// This was due to the Rc that had still references because of multiple copies when creating a webview.
pub type WeakDesktopContext = Weak<DesktopService>;
/// An imperative interface to the current window.
///
/// To get a handle to the current window, use the [`window`] function.
///
///
/// # Example
///
/// you can use `cx.consume_context::<DesktopContext>` to get this context
///
/// ```rust, ignore
/// let desktop = cx.consume_context::<DesktopContext>().unwrap();
/// ```
pub struct DesktopService {
/// The wry/tao proxy to the current window
pub webview: WebView,
/// The tao window itself
pub window: Arc<Window>,
pub(crate) shared: Rc<SharedContext>,
/// The receiver for queries about the current window
pub(super) query: QueryEngine,
pub(crate) asset_handlers: AssetHandlerRegistry,
pub(crate) file_hover: NativeFileHover,
pub(crate) close_behaviour: Rc<Cell<WindowCloseBehaviour>>,
#[cfg(target_os = "ios")]
pub(crate) views: Rc<std::cell::RefCell<Vec<*mut objc::runtime::Object>>>,
}
/// A smart pointer to the current window.
impl std::ops::Deref for DesktopService {
type Target = Window;
fn deref(&self) -> &Self::Target {
&self.window
}
}
impl DesktopService {
pub(crate) fn new(
webview: WebView,
window: Arc<Window>,
shared: Rc<SharedContext>,
asset_handlers: AssetHandlerRegistry,
file_hover: NativeFileHover,
close_behaviour: WindowCloseBehaviour,
) -> Self {
Self {
window,
webview,
shared,
asset_handlers,
file_hover,
close_behaviour: Rc::new(Cell::new(close_behaviour)),
query: Default::default(),
#[cfg(target_os = "ios")]
views: Default::default(),
}
}
/// Start the creation of a new window using the props and window builder
///
/// Returns a future that resolves to the webview handle for the new window. You can use this
/// to control other windows from the current window once the new window is created.
///
/// Be careful to not create a cycle of windows, or you might leak memory.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// fn popup() -> Element {
/// rsx! {
/// div { "This is a popup window!" }
/// }
/// }
///
/// # async fn app() {
/// // Create a new window with a component that will be rendered in the new window.
/// let dom = VirtualDom::new(popup);
/// // Create and wait for the window
/// let window = dioxus::desktop::window().new_window(dom, Default::default()).await;
/// // Fullscreen the new window
/// window.set_fullscreen(true);
/// # }
/// ```
// Note: This method is asynchronous because webview2 does not support creating a new window from
// inside of an existing webview callback. Dioxus runs event handlers synchronously inside of a webview
// callback. See [this page](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/threading-model#reentrancy) for more information.
//
// Related issues:
// - https://github.com/tauri-apps/wry/issues/583
// - https://github.com/DioxusLabs/dioxus/issues/3080
pub fn new_window(&self, dom: VirtualDom, cfg: Config) -> PendingDesktopContext {
let (window, context) = PendingWebview::new(dom, cfg);
self.shared
.proxy
.send_event(UserWindowEvent::NewWindow)
.unwrap();
self.shared.pending_webviews.borrow_mut().push(window);
context
}
/// trigger the drag-window event
///
/// Moves the window with the left mouse button until the button is released.
///
/// you need use it in `onmousedown` event:
/// ```rust, ignore
/// onmousedown: move |_| { desktop.drag_window(); }
/// ```
pub fn drag(&self) {
if self.window.fullscreen().is_none() {
_ = self.window.drag_window();
}
}
/// Toggle whether the window is maximized or not
pub fn toggle_maximized(&self) {
self.window.set_maximized(!self.window.is_maximized())
}
/// Set the close behavior of this window
///
/// By default, windows close when the user clicks the close button.
/// If this is set to `WindowCloseBehaviour::WindowHides`, the window will hide instead of closing.
pub fn set_close_behavior(&self, behaviour: WindowCloseBehaviour) {
self.close_behaviour.set(behaviour);
}
/// Close this window
pub fn close(&self) {
let _ = self
.shared
.proxy
.send_event(UserWindowEvent::CloseWindow(self.id()));
}
/// Close a particular window, given its ID
pub fn close_window(&self, id: WindowId) {
let _ = self
.shared
.proxy
.send_event(UserWindowEvent::CloseWindow(id));
}
/// change window to fullscreen
pub fn set_fullscreen(&self, fullscreen: bool) {
if let Some(handle) = &self.window.current_monitor() {
self.window.set_fullscreen(
fullscreen.then_some(WryFullscreen::Borderless(Some(handle.clone()))),
);
}
}
/// launch print modal
pub fn print(&self) {
if let Err(e) = self.webview.print() {
tracing::warn!("Open print modal failed: {e}");
}
}
/// Set the zoom level of the webview
pub fn set_zoom_level(&self, level: f64) {
if let Err(e) = self.webview.zoom(level) {
tracing::warn!("Set webview zoom failed: {e}");
}
}
/// opens DevTool window
pub fn devtool(&self) {
#[cfg(debug_assertions)]
self.webview.open_devtools();
#[cfg(not(debug_assertions))]
tracing::warn!("Devtools are disabled in release builds");
}
/// Create a wry event handler that listens for wry events.
/// This event handler is scoped to the currently active window and will only receive events that are either global or related to the current window.
///
/// The id this function returns can be used to remove the event handler with [`Self::remove_wry_event_handler`]
pub fn create_wry_event_handler(
&self,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
self.shared.event_handlers.add(self.window.id(), handler)
}
/// Remove a wry event handler created with [`Self::create_wry_event_handler`]
pub fn remove_wry_event_handler(&self, id: WryEventHandler) {
self.shared.event_handlers.remove(id)
}
/// Create a global shortcut
///
/// Linux: Only works on x11. See [this issue](https://github.com/tauri-apps/tao/issues/331) for more information.
pub fn create_shortcut(
&self,
hotkey: HotKey,
callback: impl FnMut(HotKeyState) + 'static,
) -> Result<ShortcutHandle, ShortcutRegistryError> {
self.shared
.shortcut_manager
.add_shortcut(hotkey, Box::new(callback))
}
/// Remove a global shortcut
pub fn remove_shortcut(&self, id: ShortcutHandle) {
self.shared.shortcut_manager.remove_shortcut(id)
}
/// Remove all global shortcuts
pub fn remove_all_shortcuts(&self) {
self.shared.shortcut_manager.remove_all()
}
/// Provide a callback to handle asset loading yourself.
/// If the ScopeId isn't provided, defaults to a global handler.
/// Note that the handler is namespaced by name, not ScopeId.
///
/// When the component is dropped, the handler is removed.
///
/// See [`crate::use_asset_handler`] for a convenient hook.
pub fn register_asset_handler(
&self,
name: String,
handler: impl Fn(AssetRequest, RequestAsyncResponder) + 'static,
) {
self.asset_handlers
.register_handler(name, Callback::new(move |(req, resp)| handler(req, resp)))
}
/// Removes an asset handler by its identifier.
///
/// Returns `None` if the handler did not exist.
pub fn remove_asset_handler(&self, name: &str) -> Option<()> {
self.asset_handlers.remove_handler(name).map(|_| ())
}
/// Push an objc view to the window
#[cfg(target_os = "ios")]
pub fn push_view(&self, view: objc_id::ShareId<objc::runtime::Object>) {
let window = &self.window;
unsafe {
use objc::runtime::Object;
use objc::*;
assert!(is_main_thread());
let ui_view = window.ui_view() as *mut Object;
let ui_view_frame: *mut Object = msg_send![ui_view, frame];
let _: () = msg_send![view, setFrame: ui_view_frame];
let _: () = msg_send![view, setAutoresizingMask: 31];
let ui_view_controller = window.ui_view_controller() as *mut Object;
let _: () = msg_send![ui_view_controller, setView: view];
self.views.borrow_mut().push(ui_view);
}
}
/// Pop an objc view from the window
#[cfg(target_os = "ios")]
pub fn pop_view(&self) {
let window = &self.window;
unsafe {
use objc::runtime::Object;
use objc::*;
assert!(is_main_thread());
if let Some(view) = self.views.borrow_mut().pop() {
let ui_view_controller = window.ui_view_controller() as *mut Object;
let _: () = msg_send![ui_view_controller, setView: view];
}
}
}
}
#[cfg(target_os = "ios")]
fn is_main_thread() -> bool {
use objc::runtime::{Class, BOOL, NO};
use objc::*;
let cls = Class::get("NSThread").unwrap();
let result: BOOL = unsafe { msg_send![cls, isMainThread] };
result != NO
}
/// A [`DesktopContext`] that is pending creation.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # async fn app() {
/// // Create a new window with a component that will be rendered in the new window.
/// let dom = VirtualDom::new(|| rsx!{ "popup!" });
///
/// // Create a new window asynchronously
/// let pending_context = dioxus::desktop::window().new_window(dom, Default::default());
///
/// // Wait for the context to be created
/// let window = pending_context.await;
///
/// // Now control the window
/// window.set_fullscreen(true);
/// # }
/// ```
pub struct PendingDesktopContext {
pub(crate) receiver: futures_channel::oneshot::Receiver<DesktopContext>,
}
impl PendingDesktopContext {
/// Resolve the pending context into a [`DesktopContext`].
pub async fn resolve(self) -> DesktopContext {
self.try_resolve()
.await
.expect("Failed to resolve pending desktop context")
}
/// Try to resolve the pending context into a [`DesktopContext`].
pub async fn try_resolve(self) -> Result<DesktopContext, futures_channel::oneshot::Canceled> {
self.receiver.await
}
}
impl IntoFuture for PendingDesktopContext {
type Output = DesktopContext;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output>>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.resolve())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/config.rs | packages/desktop/src/config.rs | use dioxus_core::{LaunchConfig, VirtualDom};
use std::path::PathBuf;
use std::{borrow::Cow, sync::Arc};
use tao::window::{Icon, WindowBuilder};
use tao::{
event_loop::{EventLoop, EventLoopWindowTarget},
window::Window,
};
use wry::http::{Request as HttpRequest, Response as HttpResponse};
use wry::{RequestAsyncResponder, WebViewId};
use crate::ipc::UserWindowEvent;
use crate::menubar::{default_menu_bar, DioxusMenu};
type CustomEventHandler = Box<
dyn 'static
+ for<'a> FnMut(
&tao::event::Event<'a, UserWindowEvent>,
&EventLoopWindowTarget<UserWindowEvent>,
),
>;
/// The closing behaviour of specific application window.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum WindowCloseBehaviour {
/// Window will hide instead of closing
WindowHides,
/// Window will close
WindowCloses,
}
/// The state of the menu builder. We need to keep track of if the state is default
/// so we only swap out the default menu bar when decorations are disabled
pub(crate) enum MenuBuilderState {
Unset,
Set(Option<DioxusMenu>),
}
impl From<MenuBuilderState> for Option<DioxusMenu> {
fn from(val: MenuBuilderState) -> Self {
match val {
MenuBuilderState::Unset => Some(default_menu_bar()),
MenuBuilderState::Set(menu) => menu,
}
}
}
/// The configuration for the desktop application.
pub struct Config {
pub(crate) event_loop: Option<EventLoop<UserWindowEvent>>,
pub(crate) window: WindowBuilder,
pub(crate) as_child_window: bool,
pub(crate) menu: MenuBuilderState,
pub(crate) protocols: Vec<WryProtocol>,
pub(crate) asynchronous_protocols: Vec<AsyncWryProtocol>,
pub(crate) pre_rendered: Option<String>,
pub(crate) disable_context_menu: bool,
pub(crate) resource_dir: Option<PathBuf>,
pub(crate) data_dir: Option<PathBuf>,
pub(crate) custom_head: Option<String>,
pub(crate) custom_index: Option<String>,
pub(crate) root_name: String,
pub(crate) background_color: Option<(u8, u8, u8, u8)>,
pub(crate) exit_on_last_window_close: bool,
pub(crate) window_close_behavior: WindowCloseBehaviour,
pub(crate) custom_event_handler: Option<CustomEventHandler>,
pub(crate) disable_file_drop_handler: bool,
pub(crate) disable_dma_buf_on_wayland: bool,
pub(crate) additional_windows_args: Option<String>,
#[allow(clippy::type_complexity)]
pub(crate) on_window: Option<Box<dyn FnMut(Arc<Window>, &mut VirtualDom) + 'static>>,
}
impl LaunchConfig for Config {}
pub(crate) type WryProtocol = (
String,
Box<dyn Fn(WebViewId, HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static>,
);
pub(crate) type AsyncWryProtocol = (
String,
Box<dyn Fn(WebViewId, HttpRequest<Vec<u8>>, RequestAsyncResponder) + 'static>,
);
impl Config {
/// Initializes a new `WindowBuilder` with default values.
#[inline]
pub fn new() -> Self {
let mut window: WindowBuilder = WindowBuilder::new()
.with_title(dioxus_cli_config::app_title().unwrap_or_else(|| "Dioxus App".to_string()));
// During development we want the window to be on top so we can see it while we work
let always_on_top = dioxus_cli_config::always_on_top().unwrap_or(true);
if cfg!(debug_assertions) {
window = window.with_always_on_top(always_on_top);
}
Self {
window,
as_child_window: false,
event_loop: None,
menu: MenuBuilderState::Unset,
protocols: Vec::new(),
asynchronous_protocols: Vec::new(),
pre_rendered: None,
disable_context_menu: !cfg!(debug_assertions),
resource_dir: None,
data_dir: None,
custom_head: None,
custom_index: None,
root_name: "main".to_string(),
background_color: None,
exit_on_last_window_close: true,
window_close_behavior: WindowCloseBehaviour::WindowCloses,
custom_event_handler: None,
disable_file_drop_handler: false,
disable_dma_buf_on_wayland: true,
on_window: None,
additional_windows_args: None,
}
}
/// set the directory from which assets will be searched in release mode
pub fn with_resource_directory(mut self, path: impl Into<PathBuf>) -> Self {
self.resource_dir = Some(path.into());
self
}
/// set the directory where data will be stored in release mode.
///
/// > Note: This **must** be set when bundling on Windows.
pub fn with_data_directory(mut self, path: impl Into<PathBuf>) -> Self {
self.data_dir = Some(path.into());
self
}
/// Set whether or not the right-click context menu should be disabled.
pub fn with_disable_context_menu(mut self, disable: bool) -> Self {
self.disable_context_menu = disable;
self
}
/// Set whether or not the file drop handler should be disabled.
/// On Windows the drop handler must be disabled for HTML drag and drop APIs to work.
pub fn with_disable_drag_drop_handler(mut self, disable: bool) -> Self {
self.disable_file_drop_handler = disable;
self
}
/// Set the pre-rendered HTML content
pub fn with_prerendered(mut self, content: String) -> Self {
self.pre_rendered = Some(content);
self
}
/// Set the event loop to be used
pub fn with_event_loop(mut self, event_loop: EventLoop<UserWindowEvent>) -> Self {
self.event_loop = Some(event_loop);
self
}
/// Set the configuration for the window.
pub fn with_window(mut self, window: WindowBuilder) -> Self {
// We need to do a swap because the window builder only takes itself as muy self
self.window = window;
// If the decorations are off for the window, remove the menu as well
if !self.window.window.decorations && matches!(self.menu, MenuBuilderState::Unset) {
self.menu = MenuBuilderState::Set(None);
}
self
}
/// Set the window as child
pub fn with_as_child_window(mut self) -> Self {
self.as_child_window = true;
self
}
/// When the last window is closed, the application will exit.
///
/// This is the default behaviour.
///
/// If the last window is hidden, the application will not exit.
pub fn with_exits_when_last_window_closes(mut self, exit: bool) -> Self {
self.exit_on_last_window_close = exit;
self
}
/// Sets the behaviour of the application when the last window is closed.
pub fn with_close_behaviour(mut self, behaviour: WindowCloseBehaviour) -> Self {
self.window_close_behavior = behaviour;
self
}
/// Sets a custom callback to run whenever the event pool receives an event.
pub fn with_custom_event_handler(
mut self,
f: impl FnMut(&tao::event::Event<'_, UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>)
+ 'static,
) -> Self {
self.custom_event_handler = Some(Box::new(f));
self
}
/// Set a custom protocol
pub fn with_custom_protocol<F>(mut self, name: impl ToString, handler: F) -> Self
where
F: Fn(WebViewId, HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static,
{
self.protocols.push((name.to_string(), Box::new(handler)));
self
}
/// Set an asynchronous custom protocol
///
/// **Example Usage**
/// ```rust
/// # use wry::http::response::Response as HTTPResponse;
/// # use std::borrow::Cow;
/// # use dioxus_desktop::Config;
/// #
/// # fn main() {
/// let cfg = Config::new()
/// .with_asynchronous_custom_protocol("asset", |_webview_id, request, responder| {
/// tokio::spawn(async move {
/// responder.respond(
/// HTTPResponse::builder()
/// .status(404)
/// .body(Cow::Borrowed("404 - Not Found".as_bytes()))
/// .unwrap()
/// );
/// });
/// });
/// # }
/// ```
/// note a key difference between Dioxus and Wry, the protocol name doesn't explicitly need to be a
/// [`String`], but needs to implement [`ToString`].
///
/// See [`wry`](wry::WebViewBuilder::with_asynchronous_custom_protocol) for more details on implementation
pub fn with_asynchronous_custom_protocol<F>(mut self, name: impl ToString, handler: F) -> Self
where
F: Fn(WebViewId, HttpRequest<Vec<u8>>, RequestAsyncResponder) + 'static,
{
self.asynchronous_protocols
.push((name.to_string(), Box::new(handler)));
self
}
/// Set a custom icon for this application
pub fn with_icon(mut self, icon: Icon) -> Self {
self.window.window.window_icon = Some(icon);
self
}
/// Inject additional content into the document's HEAD.
///
/// This is useful for loading CSS libraries, JS libraries, etc.
pub fn with_custom_head(mut self, head: String) -> Self {
self.custom_head = Some(head);
self
}
/// Use a custom index.html instead of the default Dioxus one.
///
/// Make sure your index.html is valid HTML.
///
/// Dioxus injects some loader code into the closing body tag. Your document
/// must include a body element!
pub fn with_custom_index(mut self, index: String) -> Self {
self.custom_index = Some(index);
self
}
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akin to calling React.render() on the element with the specified name.
pub fn with_root_name(mut self, name: impl Into<String>) -> Self {
self.root_name = name.into();
self
}
/// Sets the background color of the WebView.
/// This will be set before the HTML is rendered and can be used to prevent flashing when the page loads.
/// Accepts a color in RGBA format
pub fn with_background_color(mut self, color: (u8, u8, u8, u8)) -> Self {
self.background_color = Some(color);
self
}
/// Sets the menu the window will use. This will override the default menu bar.
///
/// > Note: Menu will be hidden if
/// > [`with_decorations`](tao::window::WindowBuilder::with_decorations)
/// > is set to false and passed into [`with_window`](Config::with_window)
#[allow(unused)]
pub fn with_menu(mut self, menu: impl Into<Option<DioxusMenu>>) -> Self {
#[cfg(not(any(target_os = "ios", target_os = "android")))]
{
if self.window.window.decorations {
self.menu = MenuBuilderState::Set(menu.into())
}
}
self
}
/// Allows modifying the window and virtual dom right after they are built, but before the webview is created.
///
/// This is important for z-ordering textures in child windows. Note that this callback runs on
/// every window creation, so it's up to you to
pub fn with_on_window(mut self, f: impl FnMut(Arc<Window>, &mut VirtualDom) + 'static) -> Self {
self.on_window = Some(Box::new(f));
self
}
/// Set whether or not DMA-BUF usage should be disabled on Wayland.
///
/// Defaults to true to avoid issues on some systems. If you want to enable DMA-BUF usage, set this to false.
/// See <https://github.com/DioxusLabs/dioxus/issues/4528#issuecomment-3476430611>
pub fn with_disable_dma_buf_on_wayland(mut self, disable: bool) -> Self {
self.disable_dma_buf_on_wayland = disable;
self
}
/// Add additional windows only launch arguments for webview2
pub fn with_windows_browser_args(mut self, additional_args: impl ToString) -> Self {
self.additional_windows_args = Some(additional_args.to_string());
self
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
// dirty trick, avoid introducing `image` at runtime
// TODO: use serde when `Icon` impl serde
//
// This function should only be enabled when generating new icons.
//
// #[test]
// #[ignore]
// fn prepare_default_icon() {
// use image::io::Reader as ImageReader;
// use image::ImageFormat;
// use std::fs::File;
// use std::io::Cursor;
// use std::io::Write;
// use std::path::PathBuf;
// let png: &[u8] = include_bytes!("default_icon.png");
// let mut reader = ImageReader::new(Cursor::new(png));
// reader.set_format(ImageFormat::Png);
// let icon = reader.decode().unwrap();
// let bin = PathBuf::from(file!())
// .parent()
// .unwrap()
// .join("default_icon.bin");
// println!("{:?}", bin);
// let mut file = File::create(bin).unwrap();
// file.write_all(icon.as_bytes()).unwrap();
// println!("({}, {})", icon.width(), icon.height())
// }
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/app.rs | packages/desktop/src/app.rs | use crate::{
config::{Config, WindowCloseBehaviour},
edits::EditWebsocket,
event_handlers::WindowEventHandlers,
ipc::{IpcMessage, UserWindowEvent},
query::QueryResult,
shortcut::ShortcutRegistry,
webview::{PendingWebview, WebviewInstance},
};
use dioxus_core::VirtualDom;
use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
time::Duration,
};
use tao::{
dpi::PhysicalSize,
event::Event,
event_loop::{ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget},
window::WindowId,
};
/// The single top-level object that manages all the running windows, assets, shortcuts, etc
pub(crate) struct App {
// move the props into a cell so we can pop it out later to create the first window
// iOS panics if we create a window before the event loop is started, so we toss them into a cell
pub(crate) unmounted_dom: Cell<Option<VirtualDom>>,
pub(crate) cfg: Cell<Option<Config>>,
// Stuff we need mutable access to
pub(crate) control_flow: ControlFlow,
pub(crate) is_visible_before_start: bool,
pub(crate) exit_on_last_window_close: bool,
pub(crate) disable_dma_buf_on_wayland: bool,
pub(crate) webviews: HashMap<WindowId, WebviewInstance>,
pub(crate) float_all: bool,
pub(crate) show_devtools: bool,
/// This single blob of state is shared between all the windows so they have access to the runtime state
///
/// This includes stuff like the event handlers, shortcuts, etc as well as ways to modify *other* windows
pub(crate) shared: Rc<SharedContext>,
}
/// A bundle of state shared between all the windows, providing a way for us to communicate with running webview.
pub(crate) struct SharedContext {
pub(crate) event_handlers: WindowEventHandlers,
pub(crate) pending_webviews: RefCell<Vec<PendingWebview>>,
pub(crate) shortcut_manager: ShortcutRegistry,
pub(crate) proxy: EventLoopProxy<UserWindowEvent>,
pub(crate) target: EventLoopWindowTarget<UserWindowEvent>,
pub(crate) websocket: EditWebsocket,
}
impl App {
pub fn new(mut cfg: Config, virtual_dom: VirtualDom) -> (EventLoop<UserWindowEvent>, Self) {
let event_loop = cfg
.event_loop
.take()
.unwrap_or_else(|| EventLoopBuilder::<UserWindowEvent>::with_user_event().build());
let app = Self {
exit_on_last_window_close: cfg.exit_on_last_window_close,
disable_dma_buf_on_wayland: cfg.disable_dma_buf_on_wayland,
is_visible_before_start: true,
webviews: HashMap::new(),
control_flow: ControlFlow::Wait,
unmounted_dom: Cell::new(Some(virtual_dom)),
float_all: false,
show_devtools: false,
cfg: Cell::new(Some(cfg)),
shared: Rc::new(SharedContext {
event_handlers: WindowEventHandlers::default(),
pending_webviews: Default::default(),
shortcut_manager: ShortcutRegistry::new(),
proxy: event_loop.create_proxy(),
target: event_loop.clone(),
websocket: EditWebsocket::start(),
}),
};
// Set the event converter
dioxus_html::set_event_converter(Box::new(crate::events::SerializedHtmlEventConverter));
// Wire up the global hotkey handler
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
app.set_global_hotkey_handler();
// Wire up the menubar receiver - this way any component can key into the menubar actions
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
app.set_menubar_receiver();
// Wire up the tray icon receiver - this way any component can key into the menubar actions
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
app.set_tray_icon_receiver();
// Allow hotreloading to work - but only in debug mode
#[cfg(all(feature = "devtools", debug_assertions))]
app.connect_hotreload();
#[cfg(debug_assertions)]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
app.connect_preserve_window_state_handler();
// Make sure to disable DMA buffer rendering on Linux Wayland sessions
app.disable_dma_buf();
(event_loop, app)
}
pub fn tick(&mut self, window_event: &Event<'_, UserWindowEvent>) {
self.control_flow = ControlFlow::Wait;
self.shared
.event_handlers
.apply_event(window_event, &self.shared.target);
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn handle_global_hotkey(&self, event: global_hotkey::GlobalHotKeyEvent) {
self.shared.shortcut_manager.call_handlers(event);
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn handle_menu_event(&mut self, event: muda::MenuEvent) {
match event.id().0.as_str() {
"dioxus-float-top" => {
for webview in self.webviews.values() {
webview
.desktop_context
.window
.set_always_on_top(self.float_all);
}
self.float_all = !self.float_all;
}
"dioxus-toggle-dev-tools" => {
self.show_devtools = !self.show_devtools;
for webview in self.webviews.values() {
let wv = &webview.desktop_context.webview;
if self.show_devtools {
wv.open_devtools();
} else {
wv.close_devtools();
}
}
}
_ => (),
}
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn handle_tray_menu_event(&mut self, event: tray_icon::menu::MenuEvent) {
_ = event;
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn handle_tray_icon_event(&mut self, event: tray_icon::TrayIconEvent) {
if let tray_icon::TrayIconEvent::Click {
id: _,
position: _,
rect: _,
button,
button_state: _,
} = event
{
if button == tray_icon::MouseButton::Left {
for webview in self.webviews.values() {
webview.desktop_context.window.set_visible(true);
webview.desktop_context.window.set_focus();
}
}
}
}
#[cfg(all(feature = "devtools", debug_assertions))]
pub fn connect_hotreload(&self) {
let proxy = self.shared.proxy.clone();
dioxus_devtools::connect(move |msg| {
_ = proxy.send_event(UserWindowEvent::HotReloadEvent(msg));
})
}
pub fn handle_new_window(&mut self) {
for pending_webview in self.shared.pending_webviews.borrow_mut().drain(..) {
let window = pending_webview.create_window(&self.shared);
let id = window.desktop_context.window.id();
self.webviews.insert(id, window);
_ = self.shared.proxy.send_event(UserWindowEvent::Poll(id));
}
}
pub fn handle_close_requested(&mut self, id: WindowId) {
let Some(window) = self.webviews.get(&id) else {
// If the window is not found, we can just return
return;
};
match window.desktop_context.close_behaviour.get() {
// If the window is just set to hide when closed, we can just hide it
WindowCloseBehaviour::WindowHides => {
window.desktop_context.window.set_visible(false);
}
// If the window is set to close, we can remove it from the list of webviews
// If the app is set to exit when the last window closes, we should also exit the app
WindowCloseBehaviour::WindowCloses => {
#[cfg(debug_assertions)]
self.persist_window_state();
self.webviews.remove(&id);
if self.exit_on_last_window_close && self.webviews.is_empty() {
self.control_flow = ControlFlow::Exit
}
}
};
}
pub fn window_destroyed(&mut self, id: WindowId) {
self.webviews.remove(&id);
if self.exit_on_last_window_close && self.webviews.is_empty() {
self.control_flow = ControlFlow::Exit
}
}
pub fn resize_window(&self, id: WindowId, size: PhysicalSize<u32>) {
// TODO: the app layer should avoid directly manipulating the webview webview instance internals.
// Window creation and modification is the responsibility of the webview instance so it makes sense to
// encapsulate that there.
if let Some(webview) = self.webviews.get(&id) {
use wry::Rect;
_ = webview.desktop_context.webview.set_bounds(Rect {
position: wry::dpi::Position::Logical(wry::dpi::LogicalPosition::new(0.0, 0.0)),
size: wry::dpi::Size::Physical(wry::dpi::PhysicalSize::new(
size.width,
size.height,
)),
});
}
}
pub fn handle_start_cause_init(&mut self) {
let virtual_dom = self
.unmounted_dom
.take()
.expect("Virtualdom should be set before initialization");
#[allow(unused_mut)]
let mut cfg = self
.cfg
.take()
.expect("Config should be set before initialization");
self.is_visible_before_start = cfg.window.window.visible;
#[cfg(not(target_os = "linux"))]
{
cfg.window = cfg.window.with_visible(false);
}
let explicit_window_size = cfg.window.window.inner_size;
let explicit_window_position = cfg.window.window.position;
let webview = WebviewInstance::new(cfg, virtual_dom, self.shared.clone());
// And then attempt to resume from state
self.resume_from_state(&webview, explicit_window_size, explicit_window_position);
let id = webview.desktop_context.window.id();
self.webviews.insert(id, webview);
}
pub fn handle_browser_open(&mut self, msg: IpcMessage) {
if let Some(temp) = msg.params().as_object() {
if temp.contains_key("href") {
if let Some(href) = temp.get("href").and_then(|v| v.as_str()) {
if let Err(err) = webbrowser::open(href) {
tracing::error!("Failed to open URL: {}", err);
}
}
}
}
}
/// The webview is finally loaded
///
/// Let's rebuild it and then start polling it
pub fn handle_initialize_msg(&mut self, id: WindowId) {
let view = self.webviews.get_mut(&id).unwrap();
view.edits
.wry_queue
.with_mutation_state_mut(|f| view.dom.rebuild(f));
view.edits.wry_queue.send_edits();
#[cfg(not(target_os = "linux"))]
{
view.desktop_context
.window
.set_visible(self.is_visible_before_start);
}
_ = self.shared.proxy.send_event(UserWindowEvent::Poll(id));
}
pub fn handle_query_msg(&mut self, msg: IpcMessage, id: WindowId) {
let Ok(result) = serde_json::from_value::<QueryResult>(msg.params()) else {
return;
};
let Some(view) = self.webviews.get(&id) else {
return;
};
view.desktop_context.query.send(result);
}
#[cfg(all(feature = "devtools", debug_assertions))]
pub fn handle_hot_reload_msg(&mut self, msg: dioxus_devtools::DevserverMsg) {
use std::time::Duration;
use dioxus_devtools::DevserverMsg;
// Amount of time that toats should be displayed.
const TOAST_TIMEOUT: Duration = Duration::from_secs(2);
const TOAST_TIMEOUT_LONG: Duration = Duration::from_secs(3600); // Duration::MAX is too long for JS.
match msg {
DevserverMsg::HotReload(hr_msg) => {
for webview in self.webviews.values_mut() {
{
// This is a place where wry says it's threadsafe but it's actually not.
// If we're patching the app, we want to make sure it's not going to progress in the interim.
let lock = crate::android_sync_lock::android_runtime_lock();
dioxus_devtools::apply_changes(&webview.dom, &hr_msg);
drop(lock);
}
webview.poll_vdom();
}
if !hr_msg.assets.is_empty() {
for webview in self.webviews.values_mut() {
webview.kick_stylsheets();
}
}
if hr_msg.jump_table.is_some()
&& hr_msg.for_build_id == Some(dioxus_cli_config::build_id())
{
self.send_toast_to_all(
"Hot-patch success!",
&format!("App successfully patched in {} ms", hr_msg.ms_elapsed),
"success",
TOAST_TIMEOUT,
false,
);
}
}
DevserverMsg::FullReloadCommand => {
self.send_toast_to_all(
"Successfully rebuilt.",
"Your app was rebuilt successfully and without error.",
"success",
TOAST_TIMEOUT,
true,
);
}
DevserverMsg::FullReloadStart => self.send_toast_to_all(
"Your app is being rebuilt.",
"A non-hot-reloadable change occurred and we must rebuild.",
"info",
TOAST_TIMEOUT_LONG,
false,
),
DevserverMsg::FullReloadFailed => self.send_toast_to_all(
"Oops! The build failed.",
"We tried to rebuild your app, but something went wrong.",
"error",
TOAST_TIMEOUT_LONG,
false,
),
DevserverMsg::HotPatchStart => self.send_toast_to_all(
"Hot-patching app...",
"Hot-patching modified Rust code.",
"info",
TOAST_TIMEOUT_LONG,
false,
),
DevserverMsg::Shutdown => {
self.control_flow = ControlFlow::Exit;
}
_ => {}
}
}
#[cfg(all(feature = "devtools", debug_assertions))]
fn send_toast_to_all(
&self,
header_text: &str,
message: &str,
level: &str,
duration: Duration,
after_reload: bool,
) {
for webview in self.webviews.values() {
webview.show_toast(header_text, message, level, duration, after_reload);
}
}
/// Poll the virtualdom until it's pending
///
/// The waker we give it is connected to the event loop, so it will wake up the event loop when it's ready to be polled again
///
/// All IO is done on the tokio runtime we started earlier
pub fn poll_vdom(&mut self, id: WindowId) {
let Some(view) = self.webviews.get_mut(&id) else {
return;
};
view.poll_vdom();
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
fn set_global_hotkey_handler(&self) {
let receiver = self.shared.proxy.clone();
// The event loop becomes the hotkey receiver
// This means we don't need to poll the receiver on every tick - we just get the events as they come in
// This is a bit more efficient than the previous implementation, but if someone else sets a handler, the
// receiver will become inert.
global_hotkey::GlobalHotKeyEvent::set_event_handler(Some(move |t| {
// todo: should we unset the event handler when the app shuts down?
_ = receiver.send_event(UserWindowEvent::GlobalHotKeyEvent(t));
}));
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
fn set_menubar_receiver(&self) {
let receiver = self.shared.proxy.clone();
// The event loop becomes the menu receiver
// This means we don't need to poll the receiver on every tick - we just get the events as they come in
// This is a bit more efficient than the previous implementation, but if someone else sets a handler, the
// receiver will become inert.
muda::MenuEvent::set_event_handler(Some(move |t| {
// todo: should we unset the event handler when the app shuts down?
_ = receiver.send_event(UserWindowEvent::MudaMenuEvent(t));
}));
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
fn set_tray_icon_receiver(&self) {
let receiver = self.shared.proxy.clone();
// The event loop becomes the menu receiver
// This means we don't need to poll the receiver on every tick - we just get the events as they come in
// This is a bit more efficient than the previous implementation, but if someone else sets a handler, the
// receiver will become inert.
tray_icon::TrayIconEvent::set_event_handler(Some(move |t| {
// todo: should we unset the event handler when the app shuts down?
_ = receiver.send_event(UserWindowEvent::TrayIconEvent(t));
}));
// for whatever reason they had to make it separate
let receiver = self.shared.proxy.clone();
tray_icon::menu::MenuEvent::set_event_handler(Some(move |t| {
// todo: should we unset the event handler when the app shuts down?
_ = receiver.send_event(UserWindowEvent::TrayMenuEvent(t));
}));
}
/// Do our best to preserve state about the window when the event loop is destroyed
///
/// This will attempt to save the window position, size, and monitor into the environment before
/// closing. This way, when the app is restarted, it can attempt to restore the window to the same
/// position and size it was in before, making a better DX.
pub(crate) fn handle_loop_destroyed(&self) {
#[cfg(debug_assertions)]
self.persist_window_state();
}
#[cfg(debug_assertions)]
fn persist_window_state(&self) {
if let Some(webview) = self.webviews.values().next() {
let window = &webview.desktop_context.window;
let Some(monitor) = window.current_monitor() else {
return;
};
let Ok(position) = window.outer_position() else {
return;
};
let (x, y) = if cfg!(target_os = "macos") {
let position = position.to_logical::<i32>(window.scale_factor());
(position.x, position.y)
} else {
(position.x, position.y)
};
let (width, height) = if cfg!(target_os = "macos") {
let size = window.outer_size();
let size = size.to_logical::<u32>(window.scale_factor());
// This is to work around a bug in how tao handles inner_size on macOS
// We *want* to use inner_size, but that's currently broken, so we use outer_size instead and then an adjustment
//
// https://github.com/tauri-apps/tao/issues/889
let adjustment = if window.is_decorated() { 28 } else { 0 };
(size.width, size.height.saturating_sub(adjustment))
} else {
let size = window.inner_size();
(size.width, size.height)
};
let Some(monitor_name) = monitor.name() else {
return;
};
let state = PreservedWindowState {
x,
y,
width: width.max(200),
height: height.max(200),
monitor: monitor_name.to_string(),
};
// Yes... I know... we're loading a file that might not be ours... but it's a debug feature
if let Ok(state) = serde_json::to_string(&state) {
_ = std::fs::write(restore_file(), state);
}
}
}
// Write this to the target dir so we can pick back up
fn resume_from_state(
&mut self,
webview: &WebviewInstance,
explicit_inner_size: Option<tao::dpi::Size>,
explicit_window_position: Option<tao::dpi::Position>,
) {
// We only want to do this on desktop
if cfg!(target_os = "android") || cfg!(target_os = "ios") {
return;
}
// We only want to do this in debug mode
if !cfg!(debug_assertions) {
return;
}
if let Ok(state) = std::fs::read_to_string(restore_file()) {
if let Ok(state) = serde_json::from_str::<PreservedWindowState>(&state) {
let window = &webview.desktop_context.window;
let position = (state.x, state.y);
let size = (state.width, state.height);
// Only set the outer position if it wasn't explicitly set
if explicit_window_position.is_none() {
if cfg!(target_os = "macos") {
window.set_outer_position(tao::dpi::LogicalPosition::new(
position.0, position.1,
));
} else {
window.set_outer_position(tao::dpi::PhysicalPosition::new(
position.0, position.1,
));
}
}
// Only set the inner size if it wasn't explicitly set
if explicit_inner_size.is_none() {
if cfg!(target_os = "macos") {
window.set_inner_size(tao::dpi::LogicalSize::new(size.0, size.1));
} else {
window.set_inner_size(tao::dpi::PhysicalSize::new(size.0, size.1));
}
}
}
}
}
/// Wire up a receiver to sigkill that lets us preserve the window state
/// Whenever sigkill is sent, we shut down the app and save the window state
#[cfg(debug_assertions)]
fn connect_preserve_window_state_handler(&self) {
// TODO: make this work on windows
#[cfg(unix)]
{
// Wire up the trap
let target = self.shared.proxy.clone();
std::thread::spawn(move || {
use signal_hook::consts::{SIGINT, SIGTERM};
let sigkill = signal_hook::iterator::Signals::new([SIGTERM, SIGINT]);
if let Ok(mut sigkill) = sigkill {
for _ in sigkill.forever() {
if target.send_event(UserWindowEvent::Shutdown).is_err() {
std::process::exit(0);
}
// give it a moment for the event to be processed
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
});
}
}
/// Disable DMA buffer rendering on Linux Wayland sessions to avoid bugs with WebKitGTK
fn disable_dma_buf(&self) {
if cfg!(target_os = "linux") && self.disable_dma_buf_on_wayland {
static INIT: std::sync::Once = std::sync::Once::new();
INIT.call_once(|| {
if std::path::Path::new("/dev/dri").exists()
&& std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland"
{
// Gnome Webkit is currently buggy under Wayland and KDE, so we will run it with XWayland mode.
// See: https://github.com/DioxusLabs/dioxus/issues/3667
unsafe {
// Disable explicit sync for NVIDIA drivers on Linux when using Way
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
}
unsafe {
std::env::set_var("GDK_BACKEND", "x11");
}
});
}
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct PreservedWindowState {
x: i32,
y: i32,
width: u32,
height: u32,
monitor: String,
}
/// Return the location of a tempfile with our window state in it such that we can restore it later
fn restore_file() -> std::path::PathBuf {
let dir = dioxus_cli_config::session_cache_dir().unwrap_or_else(std::env::temp_dir);
dir.join("window-state.json")
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/mobile.rs | packages/desktop/src/mobile.rs | /// Expose the `Java_dev_dioxus_main_WryActivity_create` function to the JNI layer.
/// We hardcode these to have a single trampoline for host Java code to call into.
///
/// This saves us from having to plumb the top-level package name all the way down into
/// this file. This is better for modularity (ie just call dioxus' main to run the app) as
/// well as cache thrashing since this crate doesn't rely on external env vars.
///
/// The CLI is expecting to find `dev.dioxus.main` in the final library. If you find a need to
/// change this, you'll need to change the CLI as well.
#[cfg(target_os = "android")]
#[no_mangle]
#[inline(never)]
pub extern "C" fn start_app() {
use crate::Config;
use dioxus_core::{Element, VirtualDom};
use std::any::Any;
tao::android_binding!(dev_dioxus, main, WryActivity, wry::android_setup, root, tao);
wry::android_binding!(dev_dioxus, main, wry);
#[cfg(target_os = "android")]
fn root() {
fn stop_unwind<F: FnOnce() -> T, T>(f: F) -> T {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(t) => t,
Err(err) => {
eprintln!("attempt to unwind out of `rust` with err: {:?}", err);
std::process::abort()
}
}
}
stop_unwind(|| unsafe {
let mut main_fn_ptr = libc::dlsym(libc::RTLD_DEFAULT, b"main\0".as_ptr() as _);
if main_fn_ptr.is_null() {
main_fn_ptr = libc::dlsym(libc::RTLD_DEFAULT, b"_main\0".as_ptr() as _);
}
if main_fn_ptr.is_null() {
panic!("Failed to find main symbol");
}
// Set the env vars that rust code might expect, passed off to us by the android app
// Doing this before main emulates the behavior of a regular executable
if cfg!(target_os = "android") && cfg!(debug_assertions) {
// Load the env file from the session cache if we're in debug mode and on android
//
// This is a slightly hacky way of being able to use std::env::var code in android apps without
// going through their custom java-based system.
let env_file = dioxus_cli_config::android_session_cache_dir().join(".env");
if let Ok(env_file) = std::fs::read_to_string(&env_file) {
for line in env_file.lines() {
if let Some((key, value)) = line.trim().split_once('=') {
std::env::set_var(key, value);
}
}
}
}
let main_fn: extern "C" fn() = std::mem::transmute(main_fn_ptr);
main_fn();
});
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/launch.rs | packages/desktop/src/launch.rs | use crate::Config;
use crate::{
app::App,
ipc::{IpcMethod, UserWindowEvent},
};
use dioxus_core::*;
use dioxus_document::eval;
use std::any::Any;
use tao::event::{Event, StartCause, WindowEvent};
/// Launch the WebView and run the event loop, with configuration and root props.
///
/// This will block the main thread, and *must* be spawned on the main thread. This function does not assume any runtime
/// and is equivalent to calling launch_with_props with the tokio feature disabled.
pub fn launch_virtual_dom_blocking(virtual_dom: VirtualDom, mut desktop_config: Config) -> ! {
let mut custom_event_handler = desktop_config.custom_event_handler.take();
let (event_loop, mut app) = App::new(desktop_config, virtual_dom);
event_loop.run(move |window_event, event_loop, control_flow| {
// Set the control flow and check if any events need to be handled in the app itself
app.tick(&window_event);
if let Some(ref mut f) = custom_event_handler {
f(&window_event, event_loop)
}
match window_event {
Event::NewEvents(StartCause::Init) => app.handle_start_cause_init(),
Event::LoopDestroyed => app.handle_loop_destroyed(),
Event::WindowEvent {
event, window_id, ..
} => match event {
WindowEvent::CloseRequested => app.handle_close_requested(window_id),
WindowEvent::Destroyed { .. } => app.window_destroyed(window_id),
WindowEvent::Resized(new_size) => app.resize_window(window_id, new_size),
_ => {}
},
Event::UserEvent(event) => match event {
UserWindowEvent::Poll(id) => app.poll_vdom(id),
UserWindowEvent::NewWindow => app.handle_new_window(),
UserWindowEvent::CloseWindow(id) => app.handle_close_requested(id),
UserWindowEvent::Shutdown => app.control_flow = tao::event_loop::ControlFlow::Exit,
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
UserWindowEvent::GlobalHotKeyEvent(evnt) => app.handle_global_hotkey(evnt),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
UserWindowEvent::MudaMenuEvent(evnt) => app.handle_menu_event(evnt),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
UserWindowEvent::TrayMenuEvent(evnt) => app.handle_tray_menu_event(evnt),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
UserWindowEvent::TrayIconEvent(evnt) => app.handle_tray_icon_event(evnt),
#[cfg(all(feature = "devtools", debug_assertions))]
UserWindowEvent::HotReloadEvent(msg) => app.handle_hot_reload_msg(msg),
// Windows-only drag-n-drop fix events. We need to call the interpreter drag-n-drop code.
UserWindowEvent::WindowsDragDrop(id) => {
if let Some(webview) = app.webviews.get(&id) {
webview.dom.in_scope(ScopeId::ROOT, || {
eval("window.interpreter.handleWindowsDragDrop();");
});
}
}
UserWindowEvent::WindowsDragLeave(id) => {
if let Some(webview) = app.webviews.get(&id) {
webview.dom.in_scope(ScopeId::ROOT, || {
eval("window.interpreter.handleWindowsDragLeave();");
});
}
}
UserWindowEvent::WindowsDragOver(id, x_pos, y_pos) => {
if let Some(webview) = app.webviews.get(&id) {
webview.dom.in_scope(ScopeId::ROOT, || {
let e = eval(
r#"
const xPos = await dioxus.recv();
const yPos = await dioxus.recv();
window.interpreter.handleWindowsDragOver(xPos, yPos)
"#,
);
_ = e.send(x_pos);
_ = e.send(y_pos);
});
}
}
UserWindowEvent::Ipc { id, msg } => match msg.method() {
IpcMethod::Initialize => app.handle_initialize_msg(id),
IpcMethod::UserEvent => {}
IpcMethod::Query => app.handle_query_msg(msg, id),
IpcMethod::BrowserOpen => app.handle_browser_open(msg),
IpcMethod::Other(_) => {}
},
},
_ => {}
}
*control_flow = app.control_flow;
})
}
/// Launches the WebView and runs the event loop, with configuration and root props.
pub fn launch_virtual_dom(virtual_dom: VirtualDom, desktop_config: Config) -> ! {
#[cfg(feature = "tokio_runtime")]
{
if let std::result::Result::Ok(handle) = tokio::runtime::Handle::try_current() {
assert_ne!(
handle.runtime_flavor(),
tokio::runtime::RuntimeFlavor::CurrentThread,
"The tokio current-thread runtime does not work with dioxus event handling"
);
launch_virtual_dom_blocking(virtual_dom, desktop_config);
} else {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(tokio::task::unconstrained(async move {
launch_virtual_dom_blocking(virtual_dom, desktop_config)
}));
unreachable!("The desktop launch function will never exit")
}
}
#[cfg(not(feature = "tokio_runtime"))]
{
launch_virtual_dom_blocking(virtual_dom, desktop_config);
}
}
/// Launches the WebView and runs the event loop, with configuration and root props.
pub fn launch(
root: fn() -> Element,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
platform_config: Vec<Box<dyn Any>>,
) -> ! {
let mut virtual_dom = VirtualDom::new(root);
for context in contexts {
virtual_dom.insert_any_root_context(context());
}
let platform_config = *platform_config
.into_iter()
.find_map(|cfg| cfg.downcast::<Config>().ok())
.unwrap_or_default();
launch_virtual_dom(virtual_dom, platform_config)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/element.rs | packages/desktop/src/element.rs | use std::rc::Rc;
use dioxus_core::ElementId;
use dioxus_html::{
geometry::{PixelsRect, PixelsSize, PixelsVector2D},
MountedResult, RenderedElementBacking,
};
use crate::{desktop_context::DesktopContext, query::QueryEngine, WeakDesktopContext};
#[derive(Clone)]
/// A mounted element passed to onmounted events
pub struct DesktopElement {
id: ElementId,
webview: WeakDesktopContext,
query: QueryEngine,
}
impl DesktopElement {
pub(crate) fn new(id: ElementId, webview: DesktopContext, query: QueryEngine) -> Self {
let webview = Rc::downgrade(&webview);
Self { id, webview, query }
}
}
macro_rules! scripted_getter {
($meth_name:ident, $script:literal, $output_type:path) => {
fn $meth_name(
&self,
) -> std::pin::Pin<
Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<$output_type>>>,
> {
let script = format!($script, id = self.id.0);
let webview = self
.webview
.upgrade()
.expect("Webview should be alive if the element is being queried");
let fut = self
.query
.new_query::<Option<$output_type>>(&script, webview)
.resolve();
Box::pin(async move {
match fut.await {
Ok(Some(res)) => Ok(res),
Ok(None) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(err),
)),
}
})
}
};
}
impl RenderedElementBacking for DesktopElement {
fn as_any(&self) -> &dyn std::any::Any {
self
}
scripted_getter!(
get_scroll_offset,
"return [window.interpreter.getScrollLeft({id}), window.interpreter.getScrollTop({id})]",
PixelsVector2D
);
scripted_getter!(
get_scroll_size,
"return [window.interpreter.getScrollWidth({id}), window.interpreter.getScrollHeight({id})]",
PixelsSize
);
scripted_getter!(
get_client_rect,
"return window.interpreter.getClientRect({id});",
PixelsRect
);
fn scroll_to(
&self,
options: dioxus_html::ScrollToOptions,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scrollTo({}, {});",
self.id.0,
serde_json::to_string(&options).expect("Failed to serialize ScrollToOptions")
);
let webview = self
.webview
.upgrade()
.expect("Webview should be alive if the element is being queried");
let fut = self.query.new_query::<bool>(&script, webview).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scroll({}, {}, {}, {});",
self.id.0,
coordinates.x,
coordinates.y,
serde_json::to_string(&behavior).expect("Failed to serialize ScrollBehavior")
);
let webview = self
.webview
.upgrade()
.expect("Webview should be alive if the element is being queried");
let fut = self.query.new_query::<bool>(&script, webview).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
fn set_focus(
&self,
focus: bool,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.setFocus({}, {});",
self.id.0, focus
);
let webview = self
.webview
.upgrade()
.expect("Webview should be alive if the element is being queried");
let fut = self.query.new_query::<bool>(&script, webview).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
}
#[derive(Debug)]
enum DesktopQueryError {
FailedToQuery,
}
impl std::fmt::Display for DesktopQueryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DesktopQueryError::FailedToQuery => write!(f, "Failed to query the element"),
}
}
}
impl std::error::Error for DesktopQueryError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/lib.rs | packages/desktop/src/lib.rs | #![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")]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
mod android_sync_lock;
mod app;
mod assets;
mod config;
mod desktop_context;
mod document;
mod edits;
mod element;
mod event_handlers;
mod events;
mod file_upload;
mod hooks;
mod ipc;
mod menubar;
mod mobile;
mod protocol;
mod query;
mod shortcut;
mod waker;
mod webview;
// mobile shortcut is only supported on mobile platforms
#[cfg(any(target_os = "ios", target_os = "android"))]
mod mobile_shortcut;
/// The main entrypoint for this crate
pub mod launch;
// Reexport tao and wry, might want to re-export other important things
pub use tao;
pub use tao::dpi::{LogicalPosition, LogicalSize};
pub use tao::event::WindowEvent;
pub use tao::window::WindowBuilder;
pub use wry;
// Reexport muda only if we are on desktop platforms that support menus
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub use muda;
// Tray icon
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub mod trayicon;
// Public exports
pub use assets::AssetRequest;
pub use config::{Config, WindowCloseBehaviour};
pub use desktop_context::{
window, DesktopContext, DesktopService, PendingDesktopContext, WeakDesktopContext,
};
pub use event_handlers::WryEventHandler;
pub use hooks::*;
pub use shortcut::{HotKeyState, ShortcutHandle, ShortcutRegistryError};
pub use wry::RequestAsyncResponder;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/shortcut.rs | packages/desktop/src/shortcut.rs | #[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub use global_hotkey::{
hotkey::{Code, HotKey},
Error as HotkeyError, GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState,
};
#[cfg(any(target_os = "ios", target_os = "android"))]
pub use crate::mobile_shortcut::*;
use crate::window;
use dioxus_html::input_data::keyboard_types::Modifiers;
use slab::Slab;
use std::{cell::RefCell, collections::HashMap, rc::Rc, str::FromStr};
use tao::keyboard::ModifiersState;
/// An global id for a shortcut.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShortcutHandle {
id: u32,
number: usize,
}
impl ShortcutHandle {
/// Remove the shortcut.
pub fn remove(&self) {
window().remove_shortcut(*self);
}
}
/// An error that can occur when registering a shortcut.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum ShortcutRegistryError {
/// The shortcut is invalid.
InvalidShortcut(String),
/// An unknown error occurred.
Other(Rc<dyn std::error::Error>),
}
pub(crate) struct ShortcutRegistry {
manager: GlobalHotKeyManager,
shortcuts: RefCell<HashMap<u32, ShortcutInner>>,
}
struct ShortcutInner {
#[allow(unused)]
shortcut: HotKey,
callbacks: Slab<Box<dyn FnMut(HotKeyState)>>,
}
impl ShortcutRegistry {
pub fn new() -> Self {
Self {
manager: GlobalHotKeyManager::new().unwrap(),
shortcuts: RefCell::new(HashMap::new()),
}
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub(crate) fn call_handlers(&self, id: GlobalHotKeyEvent) {
if let Some(ShortcutInner { callbacks, .. }) = self.shortcuts.borrow_mut().get_mut(&id.id) {
for (_, callback) in callbacks.iter_mut() {
(callback)(id.state);
}
}
}
pub(crate) fn add_shortcut(
&self,
hotkey: HotKey,
callback: Box<dyn FnMut(HotKeyState)>,
) -> Result<ShortcutHandle, ShortcutRegistryError> {
let accelerator_id = hotkey.clone().id();
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&accelerator_id) {
return Ok(ShortcutHandle {
id: accelerator_id,
number: callbacks.callbacks.insert(callback),
});
};
self.manager.register(hotkey).map_err(|e| match e {
HotkeyError::HotKeyParseError(shortcut) => {
ShortcutRegistryError::InvalidShortcut(shortcut)
}
err => ShortcutRegistryError::Other(Rc::new(err)),
})?;
let mut shortcut = ShortcutInner {
shortcut: hotkey,
callbacks: Slab::new(),
};
let id = shortcut.callbacks.insert(callback);
shortcuts.insert(accelerator_id, shortcut);
Ok(ShortcutHandle {
id: accelerator_id,
number: id,
})
}
pub(crate) fn remove_shortcut(&self, id: ShortcutHandle) {
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&id.id) {
let _ = callbacks.callbacks.remove(id.number);
if callbacks.callbacks.is_empty() {
if let Some(_shortcut) = shortcuts.remove(&id.id) {
let _ = self.manager.unregister(_shortcut.shortcut);
}
}
}
}
pub(crate) fn remove_all(&self) {
let mut shortcuts = self.shortcuts.borrow_mut();
let hotkeys: Vec<_> = shortcuts.drain().map(|(_, v)| v.shortcut).collect();
let _ = self.manager.unregister_all(&hotkeys);
}
}
pub trait IntoAccelerator {
fn accelerator(&self) -> HotKey;
}
impl IntoAccelerator for (dioxus_html::KeyCode, ModifiersState) {
fn accelerator(&self) -> HotKey {
HotKey::new(Some(self.1.into_modifiers_state()), self.0.into_key_code())
}
}
impl IntoAccelerator for (ModifiersState, dioxus_html::KeyCode) {
fn accelerator(&self) -> HotKey {
HotKey::new(Some(self.0.into_modifiers_state()), self.1.into_key_code())
}
}
impl IntoAccelerator for dioxus_html::KeyCode {
fn accelerator(&self) -> HotKey {
HotKey::new(None, self.into_key_code())
}
}
impl IntoAccelerator for &str {
fn accelerator(&self) -> HotKey {
HotKey::from_str(self).unwrap()
}
}
pub trait IntoModifiersState {
fn into_modifiers_state(self) -> Modifiers;
}
impl IntoModifiersState for ModifiersState {
fn into_modifiers_state(self) -> Modifiers {
let mut modifiers = Modifiers::default();
if self.shift_key() {
modifiers |= Modifiers::SHIFT;
}
if self.control_key() {
modifiers |= Modifiers::CONTROL;
}
if self.alt_key() {
modifiers |= Modifiers::ALT;
}
if self.super_key() {
modifiers |= Modifiers::META;
}
modifiers
}
}
impl IntoModifiersState for Modifiers {
fn into_modifiers_state(self) -> Modifiers {
self
}
}
pub trait IntoKeyCode {
fn into_key_code(self) -> Code;
}
impl IntoKeyCode for Code {
fn into_key_code(self) -> Code {
self
}
}
impl IntoKeyCode for dioxus_html::KeyCode {
fn into_key_code(self) -> Code {
match self {
dioxus_html::KeyCode::Backspace => Code::Backspace,
dioxus_html::KeyCode::Tab => Code::Tab,
dioxus_html::KeyCode::Clear => Code::NumpadClear,
dioxus_html::KeyCode::Enter => Code::Enter,
dioxus_html::KeyCode::Shift => Code::ShiftLeft,
dioxus_html::KeyCode::Ctrl => Code::ControlLeft,
dioxus_html::KeyCode::Alt => Code::AltLeft,
dioxus_html::KeyCode::Pause => Code::Pause,
dioxus_html::KeyCode::CapsLock => Code::CapsLock,
dioxus_html::KeyCode::Escape => Code::Escape,
dioxus_html::KeyCode::Space => Code::Space,
dioxus_html::KeyCode::PageUp => Code::PageUp,
dioxus_html::KeyCode::PageDown => Code::PageDown,
dioxus_html::KeyCode::End => Code::End,
dioxus_html::KeyCode::Home => Code::Home,
dioxus_html::KeyCode::LeftArrow => Code::ArrowLeft,
dioxus_html::KeyCode::UpArrow => Code::ArrowUp,
dioxus_html::KeyCode::RightArrow => Code::ArrowRight,
dioxus_html::KeyCode::DownArrow => Code::ArrowDown,
dioxus_html::KeyCode::Insert => Code::Insert,
dioxus_html::KeyCode::Delete => Code::Delete,
dioxus_html::KeyCode::Num0 => Code::Numpad0,
dioxus_html::KeyCode::Num1 => Code::Numpad1,
dioxus_html::KeyCode::Num2 => Code::Numpad2,
dioxus_html::KeyCode::Num3 => Code::Numpad3,
dioxus_html::KeyCode::Num4 => Code::Numpad4,
dioxus_html::KeyCode::Num5 => Code::Numpad5,
dioxus_html::KeyCode::Num6 => Code::Numpad6,
dioxus_html::KeyCode::Num7 => Code::Numpad7,
dioxus_html::KeyCode::Num8 => Code::Numpad8,
dioxus_html::KeyCode::Num9 => Code::Numpad9,
dioxus_html::KeyCode::A => Code::KeyA,
dioxus_html::KeyCode::B => Code::KeyB,
dioxus_html::KeyCode::C => Code::KeyC,
dioxus_html::KeyCode::D => Code::KeyD,
dioxus_html::KeyCode::E => Code::KeyE,
dioxus_html::KeyCode::F => Code::KeyF,
dioxus_html::KeyCode::G => Code::KeyG,
dioxus_html::KeyCode::H => Code::KeyH,
dioxus_html::KeyCode::I => Code::KeyI,
dioxus_html::KeyCode::J => Code::KeyJ,
dioxus_html::KeyCode::K => Code::KeyK,
dioxus_html::KeyCode::L => Code::KeyL,
dioxus_html::KeyCode::M => Code::KeyM,
dioxus_html::KeyCode::N => Code::KeyN,
dioxus_html::KeyCode::O => Code::KeyO,
dioxus_html::KeyCode::P => Code::KeyP,
dioxus_html::KeyCode::Q => Code::KeyQ,
dioxus_html::KeyCode::R => Code::KeyR,
dioxus_html::KeyCode::S => Code::KeyS,
dioxus_html::KeyCode::T => Code::KeyT,
dioxus_html::KeyCode::U => Code::KeyU,
dioxus_html::KeyCode::V => Code::KeyV,
dioxus_html::KeyCode::W => Code::KeyW,
dioxus_html::KeyCode::X => Code::KeyX,
dioxus_html::KeyCode::Y => Code::KeyY,
dioxus_html::KeyCode::Z => Code::KeyZ,
dioxus_html::KeyCode::Numpad0 => Code::Numpad0,
dioxus_html::KeyCode::Numpad1 => Code::Numpad1,
dioxus_html::KeyCode::Numpad2 => Code::Numpad2,
dioxus_html::KeyCode::Numpad3 => Code::Numpad3,
dioxus_html::KeyCode::Numpad4 => Code::Numpad4,
dioxus_html::KeyCode::Numpad5 => Code::Numpad5,
dioxus_html::KeyCode::Numpad6 => Code::Numpad6,
dioxus_html::KeyCode::Numpad7 => Code::Numpad7,
dioxus_html::KeyCode::Numpad8 => Code::Numpad8,
dioxus_html::KeyCode::Numpad9 => Code::Numpad9,
dioxus_html::KeyCode::Multiply => Code::NumpadMultiply,
dioxus_html::KeyCode::Add => Code::NumpadAdd,
dioxus_html::KeyCode::Subtract => Code::NumpadSubtract,
dioxus_html::KeyCode::DecimalPoint => Code::NumpadDecimal,
dioxus_html::KeyCode::Divide => Code::NumpadDivide,
dioxus_html::KeyCode::F1 => Code::F1,
dioxus_html::KeyCode::F2 => Code::F2,
dioxus_html::KeyCode::F3 => Code::F3,
dioxus_html::KeyCode::F4 => Code::F4,
dioxus_html::KeyCode::F5 => Code::F5,
dioxus_html::KeyCode::F6 => Code::F6,
dioxus_html::KeyCode::F7 => Code::F7,
dioxus_html::KeyCode::F8 => Code::F8,
dioxus_html::KeyCode::F9 => Code::F9,
dioxus_html::KeyCode::F10 => Code::F10,
dioxus_html::KeyCode::F11 => Code::F11,
dioxus_html::KeyCode::F12 => Code::F12,
dioxus_html::KeyCode::NumLock => Code::NumLock,
dioxus_html::KeyCode::ScrollLock => Code::ScrollLock,
dioxus_html::KeyCode::Semicolon => Code::Semicolon,
dioxus_html::KeyCode::EqualSign => Code::Equal,
dioxus_html::KeyCode::Comma => Code::Comma,
dioxus_html::KeyCode::Period => Code::Period,
dioxus_html::KeyCode::ForwardSlash => Code::Slash,
dioxus_html::KeyCode::GraveAccent => Code::Backquote,
dioxus_html::KeyCode::OpenBracket => Code::BracketLeft,
dioxus_html::KeyCode::BackSlash => Code::Backslash,
dioxus_html::KeyCode::CloseBracket => Code::BracketRight,
dioxus_html::KeyCode::SingleQuote => Code::Quote,
key => panic!("Failed to convert {key:?} to tao::keyboard::KeyCode, try using tao::keyboard::KeyCode directly"),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/document.rs | packages/desktop/src/document.rs | use crate::{query::Query, DesktopContext, WeakDesktopContext};
use dioxus_core::queue_effect;
use dioxus_document::{
create_element_in_head, Document, Eval, EvalError, Evaluator, LinkProps, MetaProps,
ScriptProps, StyleProps,
};
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
/// Code for the Dioxus channel used to communicate between the dioxus and javascript code
pub const NATIVE_EVAL_JS: &str = include_str!("./js/native_eval.js");
/// Represents the desktop-target's provider of evaluators.
#[derive(Clone)]
pub struct DesktopDocument {
pub(crate) desktop_ctx: WeakDesktopContext,
}
impl DesktopDocument {
pub fn new(desktop_ctx: DesktopContext) -> Self {
let desktop_ctx = std::rc::Rc::downgrade(&desktop_ctx);
Self { desktop_ctx }
}
}
impl Document for DesktopDocument {
fn eval(&self, js: String) -> Eval {
Eval::new(DesktopEvaluator::create(
self.desktop_ctx
.upgrade()
.expect("Window to exist when document is alive"),
js,
))
}
fn set_title(&self, title: String) {
if let Some(ctx) = self.desktop_ctx.upgrade() {
ctx.set_title(&title);
}
}
/// Create a new meta tag in the head
fn create_meta(&self, props: MetaProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head("meta", &props.attributes(), None));
});
}
/// Create a new script tag in the head
fn create_script(&self, props: ScriptProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head(
"script",
&props.attributes(),
props.script_contents().ok(),
));
});
}
/// Create a new style tag in the head
fn create_style(&self, props: StyleProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head(
"style",
&props.attributes(),
props.style_contents().ok(),
));
});
}
/// Create a new link tag in the head
fn create_link(&self, props: LinkProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head("link", &props.attributes(), None));
});
}
}
/// Represents a desktop-target's JavaScript evaluator.
pub(crate) struct DesktopEvaluator {
query: Query<serde_json::Value>,
}
impl DesktopEvaluator {
/// Creates a new evaluator for desktop-based targets.
pub fn create(desktop_ctx: DesktopContext, js: String) -> GenerationalBox<Box<dyn Evaluator>> {
let query = desktop_ctx.query.new_query(&js, desktop_ctx.clone());
// We create a generational box that is owned by the query slot so that when we drop the query slot, the generational box is also dropped.
let owner = UnsyncStorage::owner();
let query_id = query.id;
let query = owner.insert(Box::new(DesktopEvaluator { query }) as Box<dyn Evaluator>);
desktop_ctx.query.active_requests.slab.borrow_mut()[query_id].owner = Some(owner);
query
}
}
impl Evaluator for DesktopEvaluator {
fn poll_join(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
self.query
.poll_result(cx)
.map_err(|e| EvalError::Communication(e.to_string()))
}
/// Sends a message to the evaluated JavaScript.
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
if let Err(e) = self.query.send(data) {
return Err(EvalError::Communication(e.to_string()));
}
Ok(())
}
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
fn poll_recv(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
self.query
.poll_recv(cx)
.map_err(|e| EvalError::Communication(e.to_string()))
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/trayicon.rs | packages/desktop/src/trayicon.rs | //! tray icon
use dioxus_core::{provide_context, try_consume_context, use_hook};
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub use tray_icon::*;
/// tray icon menu type trait
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub type DioxusTrayMenu = tray_icon::menu::Menu;
#[cfg(any(target_os = "ios", target_os = "android"))]
pub type DioxusTrayMenu = ();
/// tray icon icon type trait
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub type DioxusTrayIcon = tray_icon::Icon;
#[cfg(any(target_os = "ios", target_os = "android"))]
pub type DioxusTrayIcon = ();
/// tray icon type trait
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub type DioxusTray = tray_icon::TrayIcon;
#[cfg(any(target_os = "ios", target_os = "android"))]
pub type DioxusTray = ();
/// initializes a tray icon
#[allow(unused)]
pub fn init_tray_icon(menu: DioxusTrayMenu, icon: Option<DioxusTrayIcon>) -> DioxusTray {
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
{
let builder = tray_icon::TrayIconBuilder::new()
.with_menu(Box::new(menu))
.with_menu_on_left_click(false)
.with_icon(match icon {
Some(value) => value,
None => tray_icon::Icon::from_rgba(
include_bytes!("./assets/default_icon.bin").to_vec(),
460,
460,
)
.expect("image parse failed"),
});
provide_context(builder.build().expect("tray icon builder failed"))
}
}
/// Returns a default tray icon menu
pub fn default_tray_icon() -> DioxusTrayMenu {
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
{
use tray_icon::menu::{Menu, PredefinedMenuItem};
let tray_menu = Menu::new();
tray_menu
.append_items(&[&PredefinedMenuItem::quit(None)])
.unwrap();
tray_menu
}
}
/// Provides a hook to the tray icon
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn use_tray_icon() -> Option<tray_icon::TrayIcon> {
use_hook(try_consume_context)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/file_upload.rs | packages/desktop/src/file_upload.rs | #![allow(unused)]
use std::{any::Any, collections::HashMap};
#[cfg(feature = "tokio_runtime")]
use tokio::{fs::File, io::AsyncReadExt};
use dioxus_html::{
geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint},
input_data::{MouseButton, MouseButtonSet},
point_interaction::{
InteractionElementOffset, InteractionLocation, ModifiersInteraction, PointerInteraction,
},
FileData, FormValue, HasDataTransferData, HasDragData, HasFileData, HasFormData, HasMouseData,
NativeFileData, SerializedDataTransfer, SerializedFormData, SerializedFormObject,
SerializedMouseData, SerializedPointInteraction,
};
use serde::{Deserialize, Serialize};
use std::{
cell::{Cell, RefCell},
path::PathBuf,
rc::Rc,
str::FromStr,
sync::Arc,
};
use wry::DragDropEvent;
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct FileDialogRequest {
#[serde(default)]
accept: Option<String>,
multiple: bool,
directory: bool,
pub event: String,
pub target: usize,
pub bubbles: bool,
pub target_name: String,
pub values: Vec<SerializedFormObject>,
}
#[allow(unused)]
impl FileDialogRequest {
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
pub(crate) fn get_file_event(&self) -> Vec<PathBuf> {
vec![]
}
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
pub(crate) async fn get_file_event_async(&self) -> Vec<PathBuf> {
vec![]
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub(crate) fn get_file_event_sync(&self) -> Vec<PathBuf> {
let dialog = rfd::FileDialog::new();
if self.directory {
self.get_file_event_for_folder(dialog)
} else {
self.get_file_event_for_file(dialog)
}
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub(crate) async fn get_file_event_async(&self) -> Vec<PathBuf> {
let mut dialog = rfd::AsyncFileDialog::new();
if self.directory {
if self.multiple {
dialog
.pick_folders()
.await
.into_iter()
.flatten()
.map(|f| f.path().to_path_buf())
.collect()
} else {
dialog
.pick_folder()
.await
.into_iter()
.map(|f| f.path().to_path_buf())
.collect()
}
} else {
let filters: Vec<_> = self
.accept
.as_deref()
.unwrap_or(".*")
.split(',')
.filter_map(|s| Filters::from_str(s.trim()).ok())
.collect();
let file_extensions: Vec<_> = filters
.iter()
.flat_map(|f| f.as_extensions().into_iter())
.collect();
let filter_name = file_extensions
.iter()
.map(|extension| format!("*.{extension}"))
.collect::<Vec<_>>()
.join(", ");
dialog = dialog.add_filter(filter_name, file_extensions.as_slice());
let files: Vec<_> = if self.multiple {
dialog
.pick_files()
.await
.into_iter()
.flatten()
.map(|f| f.path().to_path_buf())
.collect()
} else {
dialog
.pick_file()
.await
.into_iter()
.map(|f| f.path().to_path_buf())
.collect()
};
files
}
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn get_file_event_for_file(&self, mut dialog: rfd::FileDialog) -> Vec<PathBuf> {
let filters: Vec<_> = self
.accept
.as_deref()
.unwrap_or(".*")
.split(',')
.filter_map(|s| Filters::from_str(s.trim()).ok())
.collect();
let file_extensions: Vec<_> = filters
.iter()
.flat_map(|f| f.as_extensions().into_iter())
.collect();
let filter_name = file_extensions
.iter()
.map(|extension| format!("*.{extension}"))
.collect::<Vec<_>>()
.join(", ");
dialog = dialog.add_filter(filter_name, file_extensions.as_slice());
let files: Vec<_> = if self.multiple {
dialog.pick_files().into_iter().flatten().collect()
} else {
dialog.pick_file().into_iter().collect()
};
files
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
fn get_file_event_for_folder(&self, dialog: rfd::FileDialog) -> Vec<PathBuf> {
if self.multiple {
dialog.pick_folders().into_iter().flatten().collect()
} else {
dialog.pick_folder().into_iter().collect()
}
}
}
enum Filters {
Extension(String),
Mime(String),
Audio,
Video,
Image,
}
impl Filters {
fn as_extensions(&self) -> Vec<&str> {
match self {
Filters::Extension(extension) => vec![extension.as_str()],
Filters::Mime(_) => vec![],
Filters::Audio => vec!["mp3", "wav", "ogg"],
Filters::Video => vec!["mp4", "webm"],
Filters::Image => vec!["png", "jpg", "jpeg", "gif", "webp"],
}
}
}
impl FromStr for Filters {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(extension) = s.strip_prefix('.') {
Ok(Filters::Extension(extension.to_string()))
} else {
match s {
"audio/*" => Ok(Filters::Audio),
"video/*" => Ok(Filters::Video),
"image/*" => Ok(Filters::Image),
_ => Ok(Filters::Mime(s.to_string())),
}
}
}
}
#[derive(Clone)]
pub(crate) struct DesktopFormData {
pub value: String,
pub valid: bool,
pub values: Vec<(String, FormValue)>,
}
impl DesktopFormData {
pub fn new(values: Vec<(String, FormValue)>) -> Self {
Self {
value: String::new(),
valid: true,
values,
}
}
}
impl HasFileData for DesktopFormData {
fn files(&self) -> Vec<FileData> {
self.values
.iter()
.filter_map(|(_, v)| {
if let FormValue::File(Some(f)) = v {
Some(f.clone())
} else {
None
}
})
.collect()
}
}
impl HasFormData for DesktopFormData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn value(&self) -> String {
self.value.clone()
}
fn valid(&self) -> bool {
self.valid
}
fn values(&self) -> Vec<(String, FormValue)> {
self.values.clone()
}
}
#[derive(Default, Clone)]
pub struct NativeFileHover {
event: Rc<RefCell<Option<DragDropEvent>>>,
}
impl NativeFileHover {
pub fn set(&self, event: DragDropEvent) {
self.event.borrow_mut().replace(event);
}
pub fn current(&self) -> Option<DragDropEvent> {
self.event.borrow_mut().clone()
}
}
#[derive(Clone)]
pub(crate) struct DesktopFileDragEvent {
pub mouse: SerializedPointInteraction,
pub data_transfer: SerializedDataTransfer,
pub files: Vec<PathBuf>,
}
impl HasFileData for DesktopFileDragEvent {
fn files(&self) -> Vec<FileData> {
self.files
.iter()
.cloned()
.map(|f| FileData::new(DesktopFileData(f)))
.collect()
}
}
impl HasDataTransferData for DesktopFileDragEvent {
fn data_transfer(&self) -> dioxus_html::DataTransfer {
dioxus_html::DataTransfer::new(self.data_transfer.clone())
}
}
impl HasDragData for DesktopFileDragEvent {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl HasMouseData for DesktopFileDragEvent {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl InteractionLocation for DesktopFileDragEvent {
fn client_coordinates(&self) -> ClientPoint {
self.mouse.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.mouse.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.mouse.screen_coordinates()
}
}
impl InteractionElementOffset for DesktopFileDragEvent {
fn element_coordinates(&self) -> ElementPoint {
self.mouse.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.mouse.coordinates()
}
}
impl ModifiersInteraction for DesktopFileDragEvent {
fn modifiers(&self) -> dioxus_html::Modifiers {
self.mouse.modifiers()
}
}
impl PointerInteraction for DesktopFileDragEvent {
fn held_buttons(&self) -> MouseButtonSet {
self.mouse.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.mouse.trigger_button()
}
}
#[derive(Clone)]
pub struct DesktopFileData(pub(crate) PathBuf);
impl NativeFileData for DesktopFileData {
fn name(&self) -> String {
self.0.file_name().unwrap().to_string_lossy().into_owned()
}
fn size(&self) -> u64 {
std::fs::metadata(&self.0).map(|m| m.len()).unwrap_or(0)
}
fn last_modified(&self) -> u64 {
std::fs::metadata(&self.0)
.and_then(|m| m.modified())
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| duration.as_secs())
.unwrap_or(0)
}
fn read_bytes(
&self,
) -> std::pin::Pin<
Box<
dyn std::future::Future<Output = Result<bytes::Bytes, dioxus_core::CapturedError>>
+ 'static,
>,
> {
let path = self.0.clone();
Box::pin(async move { Ok(bytes::Bytes::from(std::fs::read(&path)?)) })
}
fn read_string(
&self,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<String, dioxus_core::CapturedError>> + 'static>,
> {
let path = self.0.clone();
Box::pin(async move { Ok(std::fs::read_to_string(&path)?) })
}
fn inner(&self) -> &dyn std::any::Any {
&self.0
}
fn path(&self) -> PathBuf {
self.0.clone()
}
fn byte_stream(
&self,
) -> std::pin::Pin<
Box<
dyn futures_util::Stream<Item = Result<bytes::Bytes, dioxus_core::CapturedError>>
+ 'static
+ Send,
>,
> {
let path = self.0.clone();
Box::pin(futures_util::stream::once(async move {
Ok(bytes::Bytes::from(std::fs::read(&path)?))
}))
}
fn content_type(&self) -> Option<String> {
Some(
dioxus_asset_resolver::native::get_mime_from_ext(
self.0.extension().and_then(|ext| ext.to_str()),
)
.to_string(),
)
}
}
pub struct DesktopDataTransfer {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/edits.rs | packages/desktop/src/edits.rs | //! The internal edit queue facilitating native <-> webview communication.
//!
//! Originally, we used long-polling on the wry custom protocol to send edits to the webview.
//! Due to bugs in wry on android, we switched to a websocket connection that the webview connects to.
//! We use the sledgehammer crate to build batches of edits and send them through the websocket to
//! the webview.
//!
//! Using a websocket lets us send binary data to the webview quite efficiently and does encounter
//! many of the issues with regular request/response protocols. Note that the websocket max frame
//! size is quite large (9.22 exabytes), so we can have very large batches without issue.
//!
//! Using websockets does mean we need to handle security and content security policies ourselves.
//! The code here generates a random key that the webview must use to connect to the websocket.
//! We use the initialization script API to setup the websocket connection without leaking the key
//! to the webview itself in case there's untrusted content in the webview.
//!
//! Some operating systems (like iOS) will kill the websocket connection when the device goes to sleep.
//! If this happens, we will automatically switch to a new port and notify the webview of the new location
//! and key. The webview will then reconnect to the new port and continue receiving edits.
use dioxus_interpreter_js::MutationState;
use futures_channel::oneshot;
use futures_util::FutureExt;
use rand::{RngCore, SeedableRng};
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::net::{TcpListener, TcpStream};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::AtomicU32;
use std::sync::Mutex;
use std::{
net::IpAddr,
sync::{Arc, RwLock},
};
use tokio::sync::Notify;
/// This handles communication between the requests that the webview makes and the interpreter.
#[derive(Clone)]
pub(crate) struct WryQueue {
inner: Rc<RefCell<WryQueueInner>>,
}
impl WryQueue {
pub(crate) fn with_mutation_state_mut<O: 'static>(
&self,
callback: impl FnOnce(&mut MutationState) -> O,
) -> O {
let mut inner = self.inner.borrow_mut();
callback(&mut inner.mutation_state)
}
/// Send a list of mutations to the webview
pub(crate) fn send_edits(&self) {
let mut myself = self.inner.borrow_mut();
let webview_id = myself.location.webview_id;
let serialized_edits = myself.mutation_state.export_memory();
let receiver = myself.websocket.send_edits(webview_id, serialized_edits);
myself.edits_in_progress = Some(receiver);
}
/// Wait until all pending edits have been rendered in the webview
pub(crate) fn poll_edits_flushed(
&self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<()> {
let mut self_mut = self.inner.borrow_mut();
if let Some(receiver) = self_mut.edits_in_progress.as_mut() {
receiver.poll_unpin(cx).map(|_| ())
} else {
std::task::Poll::Ready(())
}
}
/// Check if there is a new location for the websocket edits server.
pub(crate) fn poll_new_edits_location(
&self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<()> {
let mut self_mut = self.inner.borrow_mut();
let poll = self_mut
.server_location_changed_future
.as_mut()
.poll_unpin(cx);
if poll.is_ready() {
// If the future is ready, we need to reset it to wait for the next change
self_mut.server_location_changed_future =
owned_notify_future(self_mut.server_location_changed.clone());
}
poll
}
/// Get the websocket path that the webview should connect to in order to receive edits
pub(crate) fn edits_path(&self) -> String {
let WebviewWebsocketLocation {
webview_id, server, ..
} = &self.inner.borrow().location;
let server = server.lock().unwrap();
let port = server.port;
let key = &server.client_key;
let key_hex = encode_key_string(key);
format!("ws://127.0.0.1:{port}/{webview_id}/{key_hex}")
}
/// Get the key the client should expect from the server when connecting to the websocket.
pub(crate) fn required_server_key(&self) -> String {
let server = &self.inner.borrow().location.server;
let server = server.lock().unwrap();
encode_key_string(&server.server_key)
}
}
pub(crate) struct WryQueueInner {
location: WebviewWebsocketLocation,
websocket: EditWebsocket,
// If this webview is currently waiting for an edit to be flushed. We don't run the virtual dom while this is true to avoid running effects before the dom has been updated
edits_in_progress: Option<oneshot::Receiver<()>>,
// The socket may be killed by the OS while running. If it does, this channel will receive the new server location
server_location_changed: Arc<Notify>,
server_location_changed_future: Pin<Box<dyn Future<Output = ()>>>,
mutation_state: MutationState,
}
/// The location of a webview websocket connection. This is used to identify the webview and the port it is connected to.
#[derive(Clone)]
pub(crate) struct WebviewWebsocketLocation {
/// The id of the webview that this websocket is connected to
webview_id: u32,
server: Arc<Mutex<ServerLocation>>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ServerLocation {
/// The port the websocket is on
port: u16,
/// A key that every websocket connection that originates from this application will use to identify itself.
/// We use this to make sure no external applications can connect to our websocket and receive UI updates.
client_key: [u8; KEY_SIZE],
/// The key that the server must respond with for the client to connect to the websocket
server_key: [u8; KEY_SIZE],
}
/// Start a new server on an available port on localhost. Return the server location and the TCP listener that is bound to the port.
pub(crate) fn start_server() -> (ServerLocation, TcpListener) {
let client_key = create_secure_key();
let server_key = create_secure_key();
let server = TcpListener::bind((IpAddr::from([127, 0, 0, 1]), 0))
.expect("Failed to bind local TCP listener for edit socket");
let port = server.local_addr().unwrap().port();
let location = ServerLocation {
port,
client_key,
server_key,
};
(location, server)
}
/// The websocket listener that the webview will connect to in order to receive edits and send requests. There
/// is only one websocket listener per application even if there are multiple windows so we don't use all the
/// open ports.
#[derive(Clone)]
pub(crate) struct EditWebsocket {
current_location: Arc<Mutex<ServerLocation>>,
max_webview_id: Arc<AtomicU32>,
connections: Arc<RwLock<HashMap<u32, WebviewConnectionState>>>,
server_location: Arc<Notify>,
}
impl EditWebsocket {
pub(crate) fn start() -> Self {
let connections = Arc::new(RwLock::new(HashMap::new()));
let notify = Arc::new(Notify::new());
let (location, server) = start_server();
let current_location = Arc::new(Mutex::new(location));
let connections_ = connections.clone();
let current_location_ = current_location.clone();
let notify_ = notify.clone();
std::thread::spawn(move || {
Self::accept_loop(notify_, server, current_location_, connections_)
});
Self {
connections,
max_webview_id: Default::default(),
current_location,
server_location: notify,
}
}
/// Accepts incoming websocket connections and handles them in a loop.
///
/// New sockets are accepted and then put in to a new thread to handle the connection.
/// This is implemented using traditional sync code to allow us to be independent of the async runtime.
fn accept_loop(
notify: Arc<Notify>,
mut server: TcpListener,
current_location: Arc<Mutex<ServerLocation>>,
connections: Arc<RwLock<HashMap<u32, WebviewConnectionState>>>,
) {
loop {
// Accept connections until we hit an error
while let Ok((stream, _)) = server.accept() {
Self::handle_connection(stream, current_location.clone(), connections.clone());
}
// Switch ports and reconnect on a different port if the server is killed by the OS. This
// will happen if an IOS device goes to sleep
//
// For security, it is important that the keys are also regenerated when the server is restarted.
// The client may try to reconnect to the old port that is now being used by an attacker who steals the client
// key and uses it to read the edits from the new port.
let (location, new_server) = start_server();
notify.notify_waiters();
*current_location.lock().unwrap() = location;
server = new_server;
}
}
fn handle_connection(
stream: TcpStream,
server_location: Arc<Mutex<ServerLocation>>,
connections: Arc<RwLock<HashMap<u32, WebviewConnectionState>>>,
) {
use tungstenite::handshake::server::{Request, Response};
let current_server_location = { *server_location.lock().unwrap() };
let hex_encoded_client_key = encode_key_string(¤t_server_location.client_key);
let hex_encoded_server_key = encode_key_string(¤t_server_location.server_key);
let mut location = None;
let on_request = |req: &Request, res| {
// Try to parse the webview id and key from the path
let path = req.uri().path();
// The path should have two parts `/webview_id/key`
let mut segments = path.trim_matches('/').split('/');
let webview_id = segments
.next()
.and_then(|s| s.parse::<u32>().ok())
.ok_or_else(|| {
Response::builder()
.status(400)
.body(Some("Bad Request: Invalid webview ID".to_string()))
.unwrap()
})?;
let key = segments.next().ok_or_else(|| {
Response::builder()
.status(400)
.body(Some("Bad Request: Missing key".to_string()))
.unwrap()
})?;
// Make sure the key matches the expected key.
// VERY IMPORTANT: We cannot use normal string comparison here because it reveals information
// about the key based on timing information. Instead we use a constant time comparison method.
let key_matches: bool =
subtle::ConstantTimeEq::ct_eq(hex_encoded_client_key.as_ref(), key.as_bytes())
.into();
if !key_matches {
return Err(Response::builder()
.status(403)
.body(Some("Forbidden: Invalid key".to_string()))
.unwrap());
}
location = Some(WebviewWebsocketLocation {
webview_id,
server: server_location,
});
Ok(res)
};
// Accept the websocket connection while reading the path and setting the location
let mut websocket = match tungstenite::accept_hdr(stream, on_request) {
Ok(ws) => ws,
Err(e) => {
tracing::error!("Error accepting websocket connection: {}", e);
return;
}
};
// Immediately send the key to authenticate the server
websocket
.send(tungstenite::Message::Text(hex_encoded_server_key.into()))
.unwrap();
let location = match location {
Some(loc) => loc,
None => {
tracing::error!("WebSocket connection without a valid webview ID");
return;
}
};
// Handle the websocket connection in a separate thread
let (edits_outgoing, edits_incoming_rx) = std::sync::mpsc::channel::<MsgPair>();
let connections_ = connections.clone();
// Spawn a task to handle the websocket connection
std::thread::spawn(move || {
let mut queued_message = None;
// Wait until there are edits ready to send
'connection: while let Ok(msg) = edits_incoming_rx.recv() {
let data = msg.edits.clone();
queued_message = Some(msg);
// Send the edits to the webview
if let Err(e) = websocket.send(tungstenite::Message::Binary(data.into())) {
tracing::error!("Error sending edits to webview: {}", e);
break 'connection;
}
// Wait for the webview to apply the edits
while let Ok(ws_msg) = websocket.read() {
match ws_msg {
// We expect the webview to send a binary message when it has applied the edits
// This is a signal that we can continue processing
tungstenite::Message::Binary(_) => break,
// If the websocket closes, switch back to the pending state and
// re-queue the edits that haven't been acknowledged yet
tungstenite::Message::Close(_) => {
break 'connection;
}
_ => {}
}
}
let msg = queued_message.take().expect("Message should be set here");
// Notify that the edits have been applied
if msg.response.send(()).is_err() {
tracing::error!("Error sending edits applied notification");
}
}
tracing::trace!("Webview {} closed the connection", location.webview_id);
let mut connection = WebviewConnectionState::default();
if let Some(msg) = queued_message {
connection.add_message_pair(msg);
}
connections_
.write()
.unwrap()
.insert(location.webview_id, connection);
});
let mut connections = connections.write().unwrap();
match connections.remove(&location.webview_id) {
// If there are pending edits, send them to the new connection
Some(WebviewConnectionState::Pending { mut pending }) => {
while let Some(pair) = pending.pop_front() {
_ = edits_outgoing.send(pair);
}
}
// If the webview was already connected, never send edits from the old connection to
// the new connection. This should never happen
Some(WebviewConnectionState::Connected { .. }) => {
tracing::error!(
"Webview {} was already connected. Rejecting new connection.",
location.webview_id
);
return;
}
None => {}
}
connections.insert(
location.webview_id,
WebviewConnectionState::Connected { edits_outgoing },
);
}
pub(crate) fn create_queue(&self) -> WryQueue {
let webview_id = self
.max_webview_id
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let server = self.current_location.clone();
let server_location = self.server_location.clone();
WryQueue {
inner: Rc::new(RefCell::new(WryQueueInner {
server_location_changed: server_location.clone(),
server_location_changed_future: owned_notify_future(server_location),
location: WebviewWebsocketLocation { webview_id, server },
websocket: self.clone(),
edits_in_progress: None,
mutation_state: MutationState::default(),
})),
}
}
fn send_edits(&mut self, webview: u32, edits: Vec<u8>) -> oneshot::Receiver<()> {
let mut connections_mut = self.connections.write().unwrap();
let connection = connections_mut.entry(webview).or_default();
connection.add_message(edits)
}
}
/// The state of a webview websocket connection. This may be pending while the webview is booting.
/// If it is, we queue up edits until the webview is ready to receive them.
enum WebviewConnectionState {
Pending {
pending: VecDeque<MsgPair>,
},
Connected {
edits_outgoing: std::sync::mpsc::Sender<MsgPair>,
},
}
impl Default for WebviewConnectionState {
fn default() -> Self {
WebviewConnectionState::Pending {
pending: VecDeque::new(),
}
}
}
impl WebviewConnectionState {
/// Add a message to the active connection or queue and return a receiver that will be resolved
/// when the webview has applied the edits.
fn add_message(&mut self, edits: Vec<u8>) -> oneshot::Receiver<()> {
let (response_sender, response_receiver) = oneshot::channel();
let pair = MsgPair {
edits,
response: response_sender,
};
self.add_message_pair(pair);
response_receiver
}
/// Add a message pair to the connection state. The receiver in the message pair will be resolved
/// when the webview has applied the edits.
fn add_message_pair(&mut self, pair: MsgPair) {
match self {
WebviewConnectionState::Pending { pending: queue } => {
queue.push_back(pair);
}
WebviewConnectionState::Connected { edits_outgoing } => {
_ = edits_outgoing.send(pair);
}
}
}
}
struct MsgPair {
edits: Vec<u8>,
response: oneshot::Sender<()>,
}
const KEY_SIZE: usize = 256;
type EncodedKey = [u8; KEY_SIZE];
/// Base64 encode the key to a string to be used in the websocket URL.
fn encode_key_string(key: &EncodedKey) -> String {
base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE, key)
}
/// Create a secure key for the websocket connection.
/// Returns the key as a byte array and a hex-encoded string representation of the key.
fn create_secure_key() -> EncodedKey {
// Helper function to assert that the RNG is a CryptoRng - make sure we use a secure RNG
fn assert_crypto_random<R: rand::CryptoRng>(val: R) -> R {
val
}
let mut secure_rng = assert_crypto_random(rand::rngs::StdRng::from_os_rng());
let mut expected_key: EncodedKey = [0u8; KEY_SIZE];
secure_rng.fill_bytes(&mut expected_key);
expected_key
}
#[test]
fn test_key_encoding_length() {
let mut rand = rand::rngs::StdRng::from_os_rng();
for _ in 0..100 {
let mut key: EncodedKey = [0u8; KEY_SIZE];
rand.fill_bytes(&mut key);
let encoded = encode_key_string(&key);
// The encoded key length should be the same regardless of the value of the key
assert_eq!(encoded.len(), 344);
}
}
// Take an Arc<Notify> and create a future that waits for the notify to be triggered.
fn owned_notify_future(notify: Arc<Notify>) -> Pin<Box<dyn Future<Output = ()>>> {
let mut notify_owned = Box::pin(async move {
let notified = notify.notified();
// The future should be after this statement once it is polled bellow
tokio::task::yield_now().await;
notified.await;
});
// Start tracking notify before the output future is polled
_ = (&mut notify_owned).now_or_never();
notify_owned
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/event_handlers.rs | packages/desktop/src/event_handlers.rs | use crate::{ipc::UserWindowEvent, window};
use slab::Slab;
use std::cell::RefCell;
use tao::{event::Event, event_loop::EventLoopWindowTarget, window::WindowId};
/// The unique identifier of a window event handler. This can be used to later remove the handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WryEventHandler(pub(crate) usize);
impl WryEventHandler {
/// Unregister this event handler from the window
pub fn remove(&self) {
window().shared.event_handlers.remove(*self)
}
}
#[derive(Default)]
pub struct WindowEventHandlers {
handlers: RefCell<Slab<WryWindowEventHandlerInner>>,
}
struct WryWindowEventHandlerInner {
window_id: WindowId,
#[allow(clippy::type_complexity)]
handler:
Box<dyn FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static>,
}
impl WindowEventHandlers {
pub(crate) fn add(
&self,
window_id: WindowId,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
WryEventHandler(
self.handlers
.borrow_mut()
.insert(WryWindowEventHandlerInner {
window_id,
handler: Box::new(handler),
}),
)
}
pub(crate) fn remove(&self, id: WryEventHandler) {
self.handlers.borrow_mut().try_remove(id.0);
}
pub fn apply_event(
&self,
event: &Event<UserWindowEvent>,
target: &EventLoopWindowTarget<UserWindowEvent>,
) {
for (_, handler) in self.handlers.borrow_mut().iter_mut() {
// if this event does not apply to the window this listener cares about, continue
if let Event::WindowEvent { window_id, .. } = event {
if *window_id != handler.window_id {
continue;
}
}
(handler.handler)(event, target)
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/hooks.rs | packages/desktop/src/hooks.rs | use std::rc::Rc;
use crate::{
assets::*, ipc::UserWindowEvent, shortcut::IntoAccelerator, window, DesktopContext,
HotKeyState, ShortcutHandle, ShortcutRegistryError, WryEventHandler,
};
use dioxus_core::{consume_context, use_hook, use_hook_with_cleanup, Runtime};
use dioxus_hooks::use_callback;
use tao::{event::Event, event_loop::EventLoopWindowTarget};
use wry::RequestAsyncResponder;
/// Get an imperative handle to the current window
pub fn use_window() -> DesktopContext {
use_hook(consume_context::<DesktopContext>)
}
/// Register an event handler that runs when a wry event is processed.
pub fn use_wry_event_handler(
mut handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
use dioxus_core::current_scope_id;
// Capture the current runtime and scope ID.
let runtime = Runtime::current();
let scope_id = current_scope_id();
use_hook_with_cleanup(
move || {
window().create_wry_event_handler(move |event, target| {
runtime.in_scope(scope_id, || handler(event, target))
})
},
move |handler| handler.remove(),
)
}
/// Register an event handler that runs when a muda event is processed.
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "windows", target_os = "linux", target_os = "macos")))
)]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn use_muda_event_handler(
mut handler: impl FnMut(&muda::MenuEvent) + 'static,
) -> WryEventHandler {
use_wry_event_handler(move |event, _| {
if let Event::UserEvent(UserWindowEvent::MudaMenuEvent(event)) = event {
handler(event);
}
})
}
/// Register an event handler that runs when a tray icon menu event is processed.
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "windows", target_os = "linux", target_os = "macos")))
)]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn use_tray_menu_event_handler(
mut handler: impl FnMut(&tray_icon::menu::MenuEvent) + 'static,
) -> WryEventHandler {
use_wry_event_handler(move |event, _| {
if let Event::UserEvent(UserWindowEvent::TrayMenuEvent(event)) = event {
handler(event);
}
})
}
/// Register an event handler that runs when a tray icon event is processed.
/// This is only for tray icon and not it's menus.
/// If you want to register tray icon menus handler use `use_tray_menu_event_handler` instead.
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "windows", target_os = "linux", target_os = "macos")))
)]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn use_tray_icon_event_handler(
mut handler: impl FnMut(&tray_icon::TrayIconEvent) + 'static,
) -> WryEventHandler {
use_wry_event_handler(move |event, _| {
if let Event::UserEvent(UserWindowEvent::TrayIconEvent(event)) = event {
handler(event);
}
})
}
/// Provide a callback to handle asset loading yourself.
///
/// The callback takes a path as requested by the web view, and it should return `Some(response)`
/// if you want to load the asset, and `None` if you want to fallback on the default behavior.
pub fn use_asset_handler(
name: &str,
mut handler: impl FnMut(AssetRequest, RequestAsyncResponder) + 'static,
) {
// wrap the user's handler in something that keeps it up to date
let cb = use_callback(move |(asset, responder)| handler(asset, responder));
use_hook_with_cleanup(
|| {
crate::window()
.asset_handlers
.register_handler(name.to_string(), cb);
Rc::new(name.to_string())
},
move |name| {
_ = crate::window().asset_handlers.remove_handler(name.as_ref());
},
);
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_global_shortcut(
accelerator: impl IntoAccelerator,
handler: impl FnMut(HotKeyState) + 'static,
) -> Result<ShortcutHandle, ShortcutRegistryError> {
// wrap the user's handler in something that keeps it up to date
let cb = use_callback(handler);
use_hook_with_cleanup(
#[allow(clippy::redundant_closure)]
move || window().create_shortcut(accelerator.accelerator(), move |state| cb(state)),
|handle| {
if let Ok(handle) = handle {
handle.remove();
}
},
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/android_sync_lock.rs | packages/desktop/src/android_sync_lock.rs | /// This is a hack to get around the fact that wry is currently not thread safe on android
///
/// We want to acquire this mutex before doing anything with the virtualdom directly
pub fn android_runtime_lock() -> std::sync::MutexGuard<'static, ()> {
use std::sync::{Mutex, OnceLock};
static RUNTIME_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
RUNTIME_LOCK.get_or_init(|| Mutex::new(())).lock().unwrap()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/menubar.rs | packages/desktop/src/menubar.rs | use tao::window::Window;
#[cfg(not(any(target_os = "ios", target_os = "android")))]
pub type DioxusMenu = muda::Menu;
#[cfg(any(target_os = "ios", target_os = "android"))]
pub type DioxusMenu = ();
/// Initializes the menu bar for the window.
#[allow(unused)]
pub fn init_menu_bar(menu: &DioxusMenu, window: &Window) {
#[cfg(not(any(target_os = "ios", target_os = "android")))]
{
desktop_platforms::init_menu_bar(menu, window);
}
}
/// Creates a standard menu bar depending on the users platform. It may be used as a starting point
/// to further customize the menu bar and pass it to a [`WindowBuilder`](tao::window::WindowBuilder).
/// > Note: The default menu bar enables macOS shortcuts like cut/copy/paste.
/// > The menu bar differs per platform because of constraints introduced
/// > by [`MenuItem`](muda::MenuItem).
#[allow(unused)]
pub fn default_menu_bar() -> DioxusMenu {
#[cfg(not(any(target_os = "ios", target_os = "android")))]
{
desktop_platforms::default_menu_bar()
}
}
#[cfg(not(any(target_os = "ios", target_os = "android")))]
mod desktop_platforms {
use super::*;
use muda::{Menu, MenuItem, PredefinedMenuItem, Submenu};
#[allow(unused)]
pub fn init_menu_bar(menu: &Menu, window: &Window) {
#[cfg(target_os = "windows")]
unsafe {
use tao::platform::windows::WindowExtWindows;
menu.init_for_hwnd(window.hwnd());
}
#[cfg(target_os = "linux")]
{
use tao::platform::unix::WindowExtUnix;
menu.init_for_gtk_window(window.gtk_window(), window.default_vbox())
.unwrap();
}
#[cfg(target_os = "macos")]
{
use tao::platform::macos::WindowExtMacOS;
menu.init_for_nsapp();
}
}
pub fn default_menu_bar() -> Menu {
let menu = Menu::new();
// since it is uncommon on windows to have an "application menu"
// we add a "window" menu to be more consistent across platforms with the standard menu
let window_menu = Submenu::new("Window", true);
window_menu
.append_items(&[
&PredefinedMenuItem::fullscreen(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::hide(None),
&PredefinedMenuItem::hide_others(None),
&PredefinedMenuItem::show_all(None),
&PredefinedMenuItem::maximize(None),
&PredefinedMenuItem::minimize(None),
&PredefinedMenuItem::close_window(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::quit(None),
])
.unwrap();
let edit_menu = Submenu::new("Edit", true);
edit_menu
.append_items(&[
&PredefinedMenuItem::undo(None),
&PredefinedMenuItem::redo(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::cut(None),
&PredefinedMenuItem::copy(None),
&PredefinedMenuItem::paste(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::select_all(None),
])
.unwrap();
menu.append_items(&[&window_menu, &edit_menu]).unwrap();
if cfg!(debug_assertions) {
let help_menu = Submenu::new("Help", true);
help_menu
.append_items(&[&MenuItem::with_id(
"dioxus-toggle-dev-tools",
"Toggle Developer Tools",
true,
None,
)])
.unwrap();
// By default we float the window on top in dev mode, but let the user disable it
help_menu
.append_items(&[&MenuItem::with_id(
"dioxus-float-top",
"Float on Top (dev mode only)",
true,
None,
)])
.unwrap();
_ = menu.append_items(&[&help_menu]);
#[cfg(target_os = "macos")]
{
help_menu.set_as_help_menu_for_nsapp();
}
}
#[cfg(target_os = "macos")]
{
window_menu.set_as_windows_menu_for_nsapp();
}
menu
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/waker.rs | packages/desktop/src/waker.rs | use crate::ipc::UserWindowEvent;
use futures_util::task::ArcWake;
use std::sync::Arc;
use tao::{event_loop::EventLoopProxy, window::WindowId};
/// Create a waker that will send a poll event to the event loop.
///
/// This lets the VirtualDom "come up for air" and process events while the main thread is blocked by the WebView.
///
/// All IO and multithreading lives on other threads. Thanks to tokio's work stealing approach, the main thread can never
/// claim a task while it's blocked by the event loop.
pub fn tao_waker(proxy: EventLoopProxy<UserWindowEvent>, id: WindowId) -> std::task::Waker {
struct DomHandle {
proxy: EventLoopProxy<UserWindowEvent>,
id: WindowId,
}
// this should be implemented by most platforms, but ios is missing this until
// https://github.com/tauri-apps/wry/issues/830 is resolved
unsafe impl Send for DomHandle {}
unsafe impl Sync for DomHandle {}
impl ArcWake for DomHandle {
fn wake_by_ref(arc_self: &Arc<Self>) {
_ = arc_self
.proxy
.send_event(UserWindowEvent::Poll(arc_self.id));
}
}
futures_util::task::waker(Arc::new(DomHandle { id, proxy }))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/query.rs | packages/desktop/src/query.rs | use crate::{DesktopContext, WeakDesktopContext};
use futures_util::{FutureExt, StreamExt};
use generational_box::Owner;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;
use slab::Slab;
use std::{cell::RefCell, rc::Rc};
use thiserror::Error;
/// Tracks what query ids are currently active
pub(crate) struct SharedSlab<T = ()> {
pub slab: Rc<RefCell<Slab<T>>>,
}
impl<T> Clone for SharedSlab<T> {
fn clone(&self) -> Self {
Self {
slab: self.slab.clone(),
}
}
}
impl<T> Default for SharedSlab<T> {
fn default() -> Self {
SharedSlab {
slab: Rc::new(RefCell::new(Slab::new())),
}
}
}
pub(crate) struct QueryEntry {
channel_sender: futures_channel::mpsc::UnboundedSender<Value>,
return_sender: Option<futures_channel::oneshot::Sender<Result<Value, String>>>,
pub owner: Option<Owner>,
}
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
#[derive(Clone, Default)]
pub(crate) struct QueryEngine {
pub active_requests: SharedSlab<QueryEntry>,
}
impl QueryEngine {
/// Creates a new query and returns a handle to it. The query will be resolved when the webview returns a result with the same id.
pub fn new_query<V: DeserializeOwned>(
&self,
script: &str,
context: DesktopContext,
) -> Query<V> {
let (tx, rx) = futures_channel::mpsc::unbounded();
let (return_tx, return_rx) = futures_channel::oneshot::channel();
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
channel_sender: tx,
return_sender: Some(return_tx),
owner: None,
});
// start the query
// We embed the return of the eval in a function so we can send it back to the main thread
if let Err(err) = context.webview.evaluate_script(&format!(
r#"(function(){{
let dioxus = window.createQuery({request_id});
let post_error = function(err) {{
let returned_value = {{
"method": "query",
"params": {{
"id": {request_id},
"data": {{
"data": err,
"method": "return_error"
}}
}}
}};
window.ipc.postMessage(
JSON.stringify(returned_value)
);
}};
try {{
const AsyncFunction = async function () {{}}.constructor;
let promise = (new AsyncFunction("dioxus", {script:?}))(dioxus);
promise
.then((result)=>{{
dioxus.close();
let returned_value = {{
"method": "query",
"params": {{
"id": {request_id},
"data": {{
"data": result,
"method": "return"
}}
}}
}};
window.ipc.postMessage(
JSON.stringify(returned_value)
);
}})
.catch(err => post_error(`Error running JS: ${{err}}`));
}} catch (error) {{
dioxus.close();
post_error(`Invalid JS: ${{error}}`);
}}
}})();"#
)) {
tracing::warn!("Query error: {err}");
}
Query {
id: request_id,
receiver: rx,
return_receiver: Some(return_rx),
desktop: Rc::downgrade(&context),
phantom: std::marker::PhantomData,
}
}
/// Send a query channel message to the correct query
pub fn send(&self, data: QueryResult) {
let QueryResult { id, data } = data;
let mut slab = self.active_requests.slab.borrow_mut();
if let Some(entry) = slab.get_mut(id) {
match data {
QueryResultData::Return { data } => {
if let Some(sender) = entry.return_sender.take() {
let _ = sender.send(Ok(data.unwrap_or_default()));
}
}
QueryResultData::ReturnError { data } => {
if let Some(sender) = entry.return_sender.take() {
let _ = sender.send(Err(data.to_string()));
}
}
QueryResultData::Drop => {
slab.remove(id);
}
QueryResultData::Send { data } => {
let _ = entry.channel_sender.unbounded_send(data);
}
}
}
}
}
pub(crate) struct Query<V: DeserializeOwned> {
desktop: WeakDesktopContext,
receiver: futures_channel::mpsc::UnboundedReceiver<Value>,
return_receiver: Option<futures_channel::oneshot::Receiver<Result<Value, String>>>,
pub id: usize,
phantom: std::marker::PhantomData<V>,
}
impl<V: DeserializeOwned> Query<V> {
/// Resolve the query
pub async fn resolve(mut self) -> Result<V, QueryError> {
let result = self.result().await?;
V::deserialize(result).map_err(QueryError::Deserialize)
}
/// Send a message to the query
pub fn send<S: ToString>(&self, message: S) -> Result<(), QueryError> {
let queue_id = self.id;
let data = message.to_string();
let script = format!(r#"window.getQuery({queue_id}).rustSend({data});"#);
let desktop = self.desktop.upgrade().ok_or(QueryError::Finished)?;
desktop
.webview
.evaluate_script(&script)
.map_err(|e| QueryError::Send(e.to_string()))?;
Ok(())
}
/// Poll the query for a message
pub fn poll_recv(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<Value, QueryError>> {
self.receiver
.poll_next_unpin(cx)
.map(|result| result.ok_or(QueryError::Recv(String::from("Receive channel closed"))))
}
/// Receive the result of the query
pub async fn result(&mut self) -> Result<Value, QueryError> {
match self.return_receiver.take() {
Some(receiver) => match receiver.await {
Ok(Ok(data)) => Ok(data),
Ok(Err(err)) => Err(QueryError::Recv(err)),
Err(err) => Err(QueryError::Recv(err.to_string())),
},
None => Err(QueryError::Finished),
}
}
/// Poll the query for a result
pub fn poll_result(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<Value, QueryError>> {
match self.return_receiver.as_mut() {
Some(receiver) => receiver.poll_unpin(cx).map(|result| match result {
Ok(Ok(data)) => Ok(data),
Ok(Err(err)) => Err(QueryError::Recv(err)),
Err(err) => Err(QueryError::Recv(err.to_string())),
}),
None => std::task::Poll::Ready(Err(QueryError::Finished)),
}
}
}
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum QueryError {
#[error("Error receiving query result: {0}")]
Recv(String),
#[error("Error sending message to query: {0}")]
Send(String),
#[error("Error deserializing query result: {0}")]
Deserialize(serde_json::Error),
#[error("Query has already been resolved")]
Finished,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct QueryResult {
id: usize,
data: QueryResultData,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "method")]
enum QueryResultData {
#[serde(rename = "return")]
Return { data: Option<Value> },
#[serde(rename = "return_error")]
ReturnError { data: Value },
#[serde(rename = "send")]
Send { data: Value },
#[serde(rename = "drop")]
Drop,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/protocol.rs | packages/desktop/src/protocol.rs | use std::path::PathBuf;
use crate::{assets::*, webview::WebviewEdits};
use crate::{document::NATIVE_EVAL_JS, file_upload::FileDialogRequest};
use base64::prelude::BASE64_STANDARD;
use dioxus_core::AnyhowContext;
use dioxus_html::{SerializedFileData, SerializedFormObject};
use dioxus_interpreter_js::unified_bindings::SLEDGEHAMMER_JS;
use dioxus_interpreter_js::NATIVE_JS;
use wry::{
http::{status::StatusCode, Request, Response},
RequestAsyncResponder,
};
#[cfg(target_os = "android")]
const BASE_URI: &str = "https://dioxus.index.html/";
#[cfg(target_os = "windows")]
const BASE_URI: &str = "http://dioxus.index.html/";
#[cfg(not(any(target_os = "android", target_os = "windows")))]
const BASE_URI: &str = "dioxus://index.html/";
#[cfg(debug_assertions)]
static DEFAULT_INDEX: &str = include_str!("./assets/dev.index.html");
#[cfg(not(debug_assertions))]
static DEFAULT_INDEX: &str = include_str!("./assets/prod.index.html");
#[allow(clippy::too_many_arguments)] // just for now, should fix this eventually
/// Handle a request from the webview
///
/// - Tries to stream edits if they're requested.
/// - If that doesn't match, tries a user provided asset handler
/// - If that doesn't match, tries to serve a file from the filesystem
pub(super) fn desktop_handler(
request: Request<Vec<u8>>,
asset_handlers: AssetHandlerRegistry,
responder: RequestAsyncResponder,
edit_state: &WebviewEdits,
custom_head: Option<String>,
custom_index: Option<String>,
root_name: &str,
headless: bool,
) {
// Try to serve the index file first
if let Some(index_bytes) = index_request(
&request,
custom_head,
custom_index,
root_name,
headless,
edit_state,
) {
return responder.respond(index_bytes);
}
// If the request is asking for edits (ie binary protocol streaming), do that
let trimmed_uri = request.uri().path().trim_matches('/');
// If the request is asking for an event response, do that
if trimmed_uri == "__events" {
return edit_state.handle_event(request, responder);
}
// If the request is asking for a file dialog, handle that, returning the list of files selected
if trimmed_uri == "__file_dialog" {
if let Err(err) = file_dialog_responder_sync(request, responder) {
tracing::error!("Failed to handle file dialog request: {err:?}");
}
return;
}
// todo: we want to move the custom assets onto a different protocol or something
if let Some(name) = request.uri().path().split('/').nth(1) {
if asset_handlers.has_handler(name) {
let _name = name.to_string();
return asset_handlers.handle_request(&_name, request, responder);
}
}
match dioxus_asset_resolver::native::serve_asset(request.uri().path()) {
Ok(res) => responder.respond(res),
Err(_e) => responder.respond(
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(String::from("Failed to serve asset").into_bytes())
.unwrap(),
),
}
}
/// Build the index.html file we use for bootstrapping a new app
///
/// We use wry/webview by building a special index.html that forms a bridge between the webview and your rust code
///
/// This is similar to tauri, except we give more power to your rust code and less power to your frontend code.
/// This lets us skip a build/bundle step - your code just works - but limits how your Rust code can actually
/// mess with UI elements. We make this decision since other renderers like LiveView are very separate and can
/// never properly bridge the gap. Eventually of course, the idea is to build a custom CSS/HTML renderer where you
/// *do* have native control over elements, but that still won't work with liveview.
fn index_request(
request: &Request<Vec<u8>>,
custom_head: Option<String>,
custom_index: Option<String>,
root_name: &str,
headless: bool,
edit_state: &WebviewEdits,
) -> Option<Response<Vec<u8>>> {
// If the request is for the root, we'll serve the index.html file.
if request.uri().path() != "/" {
return None;
}
// Load a custom index file if provided
let mut index = custom_index.unwrap_or_else(|| DEFAULT_INDEX.to_string());
// Insert a custom head if provided
// We look just for the closing head tag. If a user provided a custom index with weird syntax, this might fail
if let Some(head) = custom_head {
index.insert_str(index.find("</head>").expect("Head element to exist"), &head);
}
// Inject our module loader by looking for a body tag
// A failure mode here, obviously, is if the user provided a custom index without a body tag
// Might want to document this
index.insert_str(
index.find("</body>").expect("Body element to exist"),
&module_loader(root_name, headless, edit_state),
);
Response::builder()
.header("Content-Type", "text/html")
.header("Access-Control-Allow-Origin", "*")
.body(index.into())
.ok()
}
/// Construct the inline script that boots up the page and bridges the webview with rust code.
///
/// The arguments here:
/// - root_name: the root element (by Id) that we stream edits into
/// - headless: is this page being loaded but invisible? Important because not all windows are visible and the
/// interpreter can't connect until the window is ready.
/// - port: the port that the websocket server is listening on for edits
/// - webview_id: the id of the webview that we're loading this into. This is used to differentiate between
/// multiple webviews in the same application, so that we can send edits to the correct one.
fn module_loader(root_id: &str, headless: bool, edit_state: &WebviewEdits) -> String {
let edits_path = edit_state.wry_queue.edits_path();
let expected_key = edit_state.wry_queue.required_server_key();
format!(
r#"
<script type="module">
// Bring the sledgehammer code
{SLEDGEHAMMER_JS}
// And then extend it with our native bindings
{NATIVE_JS}
// The native interpreter extends the sledgehammer interpreter with a few extra methods that we use for IPC
window.interpreter = new NativeInterpreter("{BASE_URI}", {headless});
// Wait for the page to load before sending the initialize message
window.onload = function() {{
let root_element = window.document.getElementById("{root_id}");
if (root_element != null) {{
window.interpreter.initialize(root_element);
window.interpreter.sendIpcMessage("initialize");
}}
window.interpreter.waitForRequest("{edits_path}", "{expected_key}");
}}
</script>
<script type="module">
// Include the code for eval
{NATIVE_EVAL_JS}
</script>
"#
)
}
fn file_dialog_responder_sync(
request: wry::http::Request<Vec<u8>>,
responder: wry::RequestAsyncResponder,
) -> dioxus_core::Result<()> {
// Handle the file dialog request
// We can't use the body, just the headers
let header = request
.headers()
.get("x-dioxus-data")
.context("Failed to get x-dioxus-data header")?;
let data_from_header = base64::Engine::decode(&BASE64_STANDARD, header.as_bytes())
.context("Failed to decode x-dioxus-data header from base64")?;
let file_dialog: FileDialogRequest = serde_json::from_slice(&data_from_header)
.context("Failed to parse x-dioxus-data header as JSON")?;
#[cfg(feature = "tokio_runtime")]
tokio::spawn(async move {
let file_list = file_dialog.get_file_event_async().await;
_ = respond_to_file_dialog(file_dialog, file_list, responder);
});
#[cfg(not(feature = "tokio_runtime"))]
{
let file_list = file_dialog.get_file_event_sync();
respond_to_file_dialog(file_dialog, file_list, responder)?;
}
Ok(())
}
fn respond_to_file_dialog(
mut file_dialog: FileDialogRequest,
file_list: Vec<PathBuf>,
responder: wry::RequestAsyncResponder,
) -> dioxus_core::Result<()> {
// Get the position of the entry we're updating, so we can insert new entries in the same place
// If we can't find it, just append to the end. This is usually due to the input not being in a form element.
let position_of_entry = file_dialog
.values
.iter()
.position(|x| x.key == file_dialog.target_name)
.unwrap_or(file_dialog.values.len());
// Remove any existing entries
file_dialog
.values
.retain(|x| x.key != file_dialog.target_name);
// And then insert the new ones
for path in file_list {
let file = std::fs::metadata(&path).context("Failed to get file metadata")?;
file_dialog.values.insert(
position_of_entry,
SerializedFormObject {
key: file_dialog.target_name.clone(),
text: None,
file: Some(SerializedFileData {
size: file.len(),
last_modified: file
.modified()
.context("Failed to get file modified time")?
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or_default() as _,
content_type: Some(
dioxus_asset_resolver::native::get_mime_from_ext(
path.extension().and_then(|s| s.to_str()),
)
.to_string(),
),
contents: Default::default(),
path,
}),
},
);
}
// And then respond with the updated file dialog
let response_data = serde_json::to_vec(&file_dialog)
.context("Failed to serialize FileDialogRequest to JSON")?;
responder.respond(
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(response_data)
.context("Failed to build response")?,
);
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/events.rs | packages/desktop/src/events.rs | //! Convert a serialized event to an event trigger
use crate::{
element::DesktopElement,
file_upload::{DesktopFileDragEvent, DesktopFormData},
};
use dioxus_html::*;
pub(crate) struct SerializedHtmlEventConverter;
impl HtmlEventConverter for SerializedHtmlEventConverter {
/// This impl is special because it relies on the renderer to convert from serialized data to native data
/// as an intermediate step.
fn convert_drag_data(&self, event: &PlatformEventData) -> DragData {
event
.downcast::<DesktopFileDragEvent>()
.cloned()
.unwrap()
.into()
}
/// This impl is special because it relies on the renderer to convert from serialized data to native data
/// as an intermediate step.
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
event.downcast::<DesktopFormData>().cloned().unwrap().into()
}
/// This impl is special because it leverages the `DesktopElement` ref between the virtualdom and webview
fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData {
event.downcast::<DesktopElement>().cloned().unwrap().into()
}
fn convert_animation_data(&self, event: &PlatformEventData) -> AnimationData {
event
.downcast::<SerializedAnimationData>()
.cloned()
.unwrap()
.into()
}
fn convert_cancel_data(&self, event: &PlatformEventData) -> CancelData {
event
.downcast::<SerializedCancelData>()
.cloned()
.unwrap()
.into()
}
fn convert_clipboard_data(&self, event: &PlatformEventData) -> ClipboardData {
event
.downcast::<SerializedClipboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_composition_data(&self, event: &PlatformEventData) -> CompositionData {
event
.downcast::<SerializedCompositionData>()
.cloned()
.unwrap()
.into()
}
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData {
event
.downcast::<SerializedFocusData>()
.cloned()
.unwrap()
.into()
}
fn convert_image_data(&self, event: &PlatformEventData) -> ImageData {
event
.downcast::<SerializedImageData>()
.cloned()
.unwrap()
.into()
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
event
.downcast::<SerializedKeyboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_media_data(&self, event: &PlatformEventData) -> MediaData {
event
.downcast::<SerializedMediaData>()
.cloned()
.unwrap()
.into()
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
event
.downcast::<SerializedMouseData>()
.cloned()
.unwrap()
.into()
}
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
event
.downcast::<SerializedPointerData>()
.cloned()
.unwrap()
.into()
}
fn convert_resize_data(&self, event: &PlatformEventData) -> ResizeData {
event
.downcast::<SerializedResizeData>()
.cloned()
.unwrap()
.into()
}
fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData {
event
.downcast::<SerializedScrollData>()
.cloned()
.unwrap()
.into()
}
fn convert_selection_data(&self, event: &PlatformEventData) -> SelectionData {
event
.downcast::<SerializedSelectionData>()
.cloned()
.unwrap()
.into()
}
fn convert_toggle_data(&self, event: &PlatformEventData) -> ToggleData {
event
.downcast::<SerializedToggleData>()
.cloned()
.unwrap()
.into()
}
fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData {
event
.downcast::<SerializedTouchData>()
.cloned()
.unwrap()
.into()
}
fn convert_transition_data(&self, event: &PlatformEventData) -> TransitionData {
event
.downcast::<SerializedTransitionData>()
.cloned()
.unwrap()
.into()
}
fn convert_visible_data(&self, event: &PlatformEventData) -> VisibleData {
event
.downcast::<SerializedVisibleData>()
.cloned()
.unwrap()
.into()
}
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
event
.downcast::<SerializedWheelData>()
.cloned()
.unwrap()
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/mobile_shortcut.rs | packages/desktop/src/mobile_shortcut.rs | #![allow(unused)]
use super::*;
use std::str::FromStr;
use tao::event_loop::EventLoopWindowTarget;
use dioxus_html::input_data::keyboard_types::Modifiers;
#[derive(Clone, Debug)]
pub struct Accelerator;
#[derive(Clone, Copy)]
pub struct HotKey;
impl HotKey {
pub fn new(mods: Option<Modifiers>, key: Code) -> Self {
Self
}
pub fn id(&self) -> u32 {
0
}
}
impl FromStr for HotKey {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(HotKey)
}
}
pub struct GlobalHotKeyManager();
impl GlobalHotKeyManager {
pub fn new() -> Result<Self, HotkeyError> {
Ok(Self())
}
pub fn register(&self, accelerator: HotKey) -> Result<HotKey, HotkeyError> {
Ok(HotKey)
}
pub fn unregister(&self, id: HotKey) -> Result<(), HotkeyError> {
Ok(())
}
pub fn unregister_all(&self, _: &[HotKey]) -> Result<(), HotkeyError> {
Ok(())
}
}
use std::{error, fmt};
/// An error whose cause the `ShortcutManager` to fail.
#[non_exhaustive]
#[derive(Debug)]
pub enum HotkeyError {
AcceleratorAlreadyRegistered(Accelerator),
AcceleratorNotRegistered(Accelerator),
HotKeyParseError(String),
}
impl error::Error for HotkeyError {}
impl fmt::Display for HotkeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
HotkeyError::AcceleratorAlreadyRegistered(e) => {
f.pad(&format!("hotkey already registered: {:?}", e))
}
HotkeyError::AcceleratorNotRegistered(e) => {
f.pad(&format!("hotkey not registered: {:?}", e))
}
HotkeyError::HotKeyParseError(e) => e.fmt(f),
}
}
}
pub struct GlobalHotKeyEvent {
pub id: u32,
pub state: HotKeyState,
}
/// Describes the state of the hotkey.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum HotKeyState {
/// The hotkey is pressed.
Pressed,
/// The hotkey is released.
Released,
}
pub(crate) type Code = dioxus_html::input_data::keyboard_types::Code;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/assets.rs | packages/desktop/src/assets.rs | use dioxus_core::Callback;
use rustc_hash::FxHashMap;
use std::{cell::RefCell, rc::Rc};
use wry::{http::Request, RequestAsyncResponder};
/// A request for an asset within dioxus-desktop.
pub type AssetRequest = Request<Vec<u8>>;
pub struct AssetHandler {
f: Callback<(AssetRequest, RequestAsyncResponder)>,
}
#[derive(Clone)]
pub struct AssetHandlerRegistry {
handlers: Rc<RefCell<FxHashMap<String, AssetHandler>>>,
}
impl AssetHandlerRegistry {
pub fn new() -> Self {
AssetHandlerRegistry {
handlers: Default::default(),
}
}
pub fn has_handler(&self, name: &str) -> bool {
self.handlers.borrow().contains_key(name)
}
pub fn handle_request(
&self,
name: &str,
request: AssetRequest,
responder: RequestAsyncResponder,
) {
if let Some(handler) = self.handlers.borrow().get(name) {
// Avoid handler being already borrowed on android
#[cfg(target_os = "android")]
let _lock = crate::android_sync_lock::android_runtime_lock();
// And run the handler in the scope of the component that created it
handler.f.call((request, responder));
}
}
pub fn register_handler(
&self,
name: String,
f: Callback<(AssetRequest, RequestAsyncResponder)>,
) {
self.handlers.borrow_mut().insert(name, AssetHandler { f });
}
pub fn remove_handler(&self, name: &str) -> Option<AssetHandler> {
self.handlers.borrow_mut().remove(name)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/webview.rs | packages/desktop/src/webview.rs | use crate::file_upload::{DesktopFileData, DesktopFileDragEvent};
use crate::menubar::DioxusMenu;
use crate::PendingDesktopContext;
use crate::{
app::SharedContext, assets::AssetHandlerRegistry, edits::WryQueue,
file_upload::NativeFileHover, ipc::UserWindowEvent, protocol, waker::tao_waker, Config,
DesktopContext, DesktopService,
};
use crate::{document::DesktopDocument, WeakDesktopContext};
use crate::{element::DesktopElement, file_upload::DesktopFormData};
use base64::prelude::BASE64_STANDARD;
use dioxus_core::{consume_context, provide_context, Runtime, ScopeId, VirtualDom};
use dioxus_document::Document;
use dioxus_history::{History, MemoryHistory};
use dioxus_hooks::to_owned;
use dioxus_html::{FileData, FormValue, HtmlEvent, PlatformEventData};
use futures_util::{pin_mut, FutureExt};
use std::sync::{atomic::AtomicBool, Arc};
use std::{cell::OnceCell, time::Duration};
use std::{rc::Rc, task::Waker};
use wry::{DragDropEvent, RequestAsyncResponder, WebContext, WebViewBuilder, WebViewId};
#[derive(Clone)]
pub(crate) struct WebviewEdits {
runtime: Rc<Runtime>,
pub wry_queue: WryQueue,
desktop_context: Rc<OnceCell<WeakDesktopContext>>,
}
impl WebviewEdits {
fn new(runtime: Rc<Runtime>, wry_queue: WryQueue) -> Self {
Self {
runtime,
wry_queue,
desktop_context: Default::default(),
}
}
fn set_desktop_context(&self, context: WeakDesktopContext) {
_ = self.desktop_context.set(context);
}
pub fn handle_event(
&self,
request: wry::http::Request<Vec<u8>>,
responder: wry::RequestAsyncResponder,
) {
let body = self
.try_handle_event(request)
.expect("Writing bodies to succeed");
responder.respond(wry::http::Response::new(body))
}
pub fn try_handle_event(
&self,
request: wry::http::Request<Vec<u8>>,
) -> Result<Vec<u8>, serde_json::Error> {
use serde::de::Error;
// todo(jon):
//
// I'm a small bit worried about the size of the header being too big on some platforms.
// It's unlikely we'll hit the 256k limit (from 2010 browsers...) but it's important to think about
// https://stackoverflow.com/questions/3326210/can-http-headers-be-too-big-for-browsers
//
// Also important to remember here that we don't pass a body from the JavaScript side of things
let data = request
.headers()
.get("dioxus-data")
.ok_or_else(|| Error::custom("dioxus-data header not set"))?;
let as_utf = std::str::from_utf8(data.as_bytes())
.map_err(|_| Error::custom("dioxus-data header is not a valid (utf-8) string"))?;
let data_from_header = base64::Engine::decode(&BASE64_STANDARD, as_utf)
.map_err(|_| Error::custom("dioxus-data header is not a base64 string"))?;
let response = match serde_json::from_slice(&data_from_header) {
Ok(event) => {
// we need to wait for the mutex lock to let us munge the main thread..
let _lock = crate::android_sync_lock::android_runtime_lock();
self.handle_html_event(event)
}
Err(err) => {
tracing::error!(
"Error parsing user_event: {:?}. \n Contents: {:?}, \nraw: {:#?}",
err,
String::from_utf8(request.body().to_vec()),
request
);
SynchronousEventResponse::new(false)
}
};
serde_json::to_vec(&response).inspect_err(|err| {
tracing::error!("failed to serialize SynchronousEventResponse: {err:?}");
})
}
pub fn handle_html_event(&self, event: HtmlEvent) -> SynchronousEventResponse {
let HtmlEvent {
element,
name,
bubbles,
data,
} = event;
let Some(desktop_context) = self.desktop_context.get() else {
tracing::error!(
"Tried to handle event before setting the desktop context on the event handler"
);
return Default::default();
};
let desktop_context = desktop_context.upgrade().unwrap();
let query = desktop_context.query.clone();
let hovered_file = desktop_context.file_hover.clone();
// check for a mounted event placeholder and replace it with a desktop specific element
let as_any = match data {
dioxus_html::EventData::Mounted => {
let element = DesktopElement::new(element, desktop_context.clone(), query.clone());
Rc::new(PlatformEventData::new(Box::new(element)))
}
dioxus_html::EventData::Form(form) => {
Rc::new(PlatformEventData::new(Box::new(DesktopFormData {
value: form.value,
valid: form.valid,
values: form
.values
.into_iter()
.map(|obj| {
if let Some(text) = obj.text {
return (obj.key, FormValue::Text(text));
}
if let Some(file_data) = obj.file {
if file_data.path.capacity() == 0 {
return (obj.key, FormValue::File(None));
}
return (
obj.key,
FormValue::File(Some(FileData::new(DesktopFileData(
file_data.path,
)))),
);
};
(obj.key, FormValue::Text(String::new()))
})
.collect(),
})))
}
dioxus_html::EventData::Drag(ref drag) => {
// we want to override this with a native file engine, provided by the most recent drag event
let file_event = hovered_file.current();
let file_paths = match file_event {
Some(wry::DragDropEvent::Enter { paths, .. }) => paths,
Some(wry::DragDropEvent::Drop { paths, .. }) => paths,
_ => vec![],
};
Rc::new(PlatformEventData::new(Box::new(DesktopFileDragEvent {
mouse: drag.mouse.clone(),
data_transfer: drag.data_transfer.clone(),
files: file_paths,
})))
}
_ => data.into_any(),
};
let event = dioxus_core::Event::new(as_any, bubbles);
self.runtime.handle_event(&name, event.clone(), element);
// Get the response from the event
SynchronousEventResponse::new(!event.default_action_enabled())
}
}
pub(crate) struct WebviewInstance {
pub dom: VirtualDom,
pub edits: WebviewEdits,
pub desktop_context: DesktopContext,
pub waker: Waker,
// Wry assumes the webcontext is alive for the lifetime of the webview.
// We need to keep the webcontext alive, otherwise the webview will crash
_web_context: WebContext,
// Same with the menu.
// Currently it's a DioxusMenu because 1) we don't touch it and 2) we support a number of platforms
// like ios where muda does not give us a menu type. It sucks but alas.
//
// This would be a good thing for someone looking to contribute to fix.
_menu: Option<DioxusMenu>,
}
impl WebviewInstance {
pub(crate) fn new(
mut cfg: Config,
mut dom: VirtualDom,
shared: Rc<SharedContext>,
) -> WebviewInstance {
let mut window = cfg.window.clone();
// tao makes small windows for some reason, make them bigger on desktop
//
// on mobile, we want them to be `None` so tao makes them the size of the screen. Otherwise we
// get a window that is not the size of the screen and weird black bars.
#[cfg(not(any(target_os = "ios", target_os = "android")))]
{
if cfg.window.window.inner_size.is_none() {
window = window.with_inner_size(tao::dpi::LogicalSize::new(800.0, 600.0));
}
}
// We assume that if the icon is None in cfg, then the user just didnt set it
if cfg.window.window.window_icon.is_none() {
window = window.with_window_icon(Some(
tao::window::Icon::from_rgba(
include_bytes!("./assets/default_icon.bin").to_vec(),
460,
460,
)
.expect("image parse failed"),
));
}
let window = Arc::new(window.build(&shared.target).unwrap());
if let Some(on_build) = cfg.on_window.as_mut() {
on_build(window.clone(), &mut dom);
}
// https://developer.apple.com/documentation/appkit/nswindowcollectionbehavior/nswindowcollectionbehaviormanaged
#[cfg(target_os = "macos")]
#[allow(deprecated)]
{
use cocoa::appkit::NSWindowCollectionBehavior;
use cocoa::base::id;
use objc::{msg_send, sel, sel_impl};
use tao::platform::macos::WindowExtMacOS;
unsafe {
let window: id = window.ns_window() as id;
#[allow(unexpected_cfgs)]
let _: () = msg_send![window, setCollectionBehavior: NSWindowCollectionBehavior::NSWindowCollectionBehaviorManaged];
}
}
let mut web_context = WebContext::new(cfg.data_dir.clone());
let edit_queue = shared.websocket.create_queue();
let asset_handlers = AssetHandlerRegistry::new();
let edits = WebviewEdits::new(dom.runtime(), edit_queue.clone());
let file_hover = NativeFileHover::default();
let headless = !cfg.window.window.visible;
let request_handler = {
to_owned![
cfg.custom_head,
cfg.custom_index,
cfg.root_name,
asset_handlers,
edits
];
#[cfg(feature = "tokio_runtime")]
let tokio_rt = tokio::runtime::Handle::current();
move |_id: WebViewId, request, responder: RequestAsyncResponder| {
#[cfg(feature = "tokio_runtime")]
let _guard = tokio_rt.enter();
protocol::desktop_handler(
request,
asset_handlers.clone(),
responder,
&edits,
custom_head.clone(),
custom_index.clone(),
&root_name,
headless,
)
}
};
let ipc_handler = {
let window_id = window.id();
to_owned![shared.proxy];
move |payload: wry::http::Request<String>| {
// defer the event to the main thread
let body = payload.into_body();
if let Ok(msg) = serde_json::from_str(&body) {
_ = proxy.send_event(UserWindowEvent::Ipc { id: window_id, msg });
}
}
};
let file_drop_handler = {
to_owned![file_hover];
let (proxy, window_id) = (shared.proxy.to_owned(), window.id());
move |evt: DragDropEvent| {
if cfg!(not(windows)) {
// Update the most recent file drop event - when the event comes in from the webview we can use the
// most recent event to build a new event with the files in it.
file_hover.set(evt);
} else {
// Windows webview blocks HTML-native events when the drop handler is provided.
// The problem is that the HTML-native events don't provide the file, so we need this.
// Solution: this glue code to mimic drag drop events.
file_hover.set(evt.clone());
match evt {
wry::DragDropEvent::Drop {
paths: _,
position: _,
} => {
_ = proxy.send_event(UserWindowEvent::WindowsDragDrop(window_id));
}
wry::DragDropEvent::Over { position } => {
_ = proxy.send_event(UserWindowEvent::WindowsDragOver(
window_id, position.0, position.1,
));
}
wry::DragDropEvent::Leave => {
_ = proxy.send_event(UserWindowEvent::WindowsDragLeave(window_id));
}
_ => {}
}
}
false
}
};
let page_loaded = AtomicBool::new(false);
let mut webview = WebViewBuilder::new_with_web_context(&mut web_context)
.with_bounds(wry::Rect {
position: wry::dpi::Position::Logical(wry::dpi::LogicalPosition::new(0.0, 0.0)),
size: wry::dpi::Size::Physical(wry::dpi::PhysicalSize::new(
window.inner_size().width,
window.inner_size().height,
)),
})
.with_transparent(cfg.window.window.transparent)
.with_url("dioxus://index.html/")
.with_ipc_handler(ipc_handler)
.with_navigation_handler(move |var| {
// We don't want to allow any navigation
// We only want to serve the index file and assets
if var.starts_with("dioxus://")
|| var.starts_with("http://dioxus.")
|| var.starts_with("https://dioxus.")
{
// After the page has loaded once, don't allow any more navigation
let page_loaded = page_loaded.swap(true, std::sync::atomic::Ordering::SeqCst);
!page_loaded
} else {
if var.starts_with("http://")
|| var.starts_with("https://")
|| var.starts_with("mailto:")
{
_ = webbrowser::open(&var);
}
false
}
}) // prevent all navigations
.with_asynchronous_custom_protocol(String::from("dioxus"), request_handler);
// Enable https scheme on android, needed for secure context API, like the geolocation API
#[cfg(target_os = "android")]
{
use wry::WebViewBuilderExtAndroid as _;
webview = webview.with_https_scheme(true);
};
// Disable the webview default shortcuts to disable the reload shortcut
#[cfg(target_os = "windows")]
{
use wry::WebViewBuilderExtWindows;
webview = webview.with_browser_accelerator_keys(false);
}
if !cfg.disable_file_drop_handler {
webview = webview.with_drag_drop_handler(file_drop_handler);
}
if let Some(color) = cfg.background_color {
webview = webview.with_background_color(color);
}
for (name, handler) in cfg.protocols.drain(..) {
#[cfg(feature = "tokio_runtime")]
let tokio_rt = tokio::runtime::Handle::current();
webview = webview.with_custom_protocol(name, move |a, b| {
#[cfg(feature = "tokio_runtime")]
let _guard = tokio_rt.enter();
handler(a, b)
});
}
for (name, handler) in cfg.asynchronous_protocols.drain(..) {
#[cfg(feature = "tokio_runtime")]
let tokio_rt = tokio::runtime::Handle::current();
webview = webview.with_asynchronous_custom_protocol(name, move |a, b, c| {
#[cfg(feature = "tokio_runtime")]
let _guard = tokio_rt.enter();
handler(a, b, c)
});
}
const INITIALIZATION_SCRIPT: &str = r#"
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
window.event.returnValue = false;
});
}
"#;
if cfg.disable_context_menu {
// in release mode, we don't want to show the dev tool or reload menus
webview = webview.with_initialization_script(INITIALIZATION_SCRIPT)
} else {
// in debug, we are okay with the reload menu showing and dev tool
webview = webview.with_devtools(true);
}
let menu = if cfg!(not(any(target_os = "android", target_os = "ios"))) {
let menu_option = cfg.menu.into();
if let Some(menu) = &menu_option {
crate::menubar::init_menu_bar(menu, &window);
}
menu_option
} else {
None
};
#[cfg(target_os = "windows")]
{
use wry::WebViewBuilderExtWindows;
if let Some(additional_windows_args) = &cfg.additional_windows_args {
webview = webview.with_additional_browser_args(additional_windows_args);
}
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
))]
let webview = if cfg.as_child_window {
webview.build_as_child(&window)
} else {
webview.build(&window)
};
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
)))]
let webview = {
use tao::platform::unix::WindowExtUnix;
use wry::WebViewBuilderExtUnix;
let vbox = window.default_vbox().unwrap();
webview.build_gtk(vbox)
};
let webview = webview.unwrap();
let desktop_context = Rc::from(DesktopService::new(
webview,
window,
shared.clone(),
asset_handlers,
file_hover,
cfg.window_close_behavior,
));
// Provide the desktop context to the virtual dom and edit handler
edits.set_desktop_context(Rc::downgrade(&desktop_context));
let provider: Rc<dyn Document> = Rc::new(DesktopDocument::new(desktop_context.clone()));
let history_provider: Rc<dyn History> = Rc::new(MemoryHistory::default());
dom.in_scope(ScopeId::ROOT, || {
provide_context(desktop_context.clone());
provide_context(provider);
provide_context(history_provider);
});
// Request an initial redraw
desktop_context.window.request_redraw();
WebviewInstance {
dom,
edits,
waker: tao_waker(shared.proxy.clone(), desktop_context.window.id()),
desktop_context,
_menu: menu,
_web_context: web_context,
}
}
pub fn poll_vdom(&mut self) {
let mut cx = std::task::Context::from_waker(&self.waker);
// Continuously poll the virtualdom until it's pending
// Wait for work will return Ready when it has edits to be sent to the webview
// It will return Pending when it needs to be polled again - nothing is ready
loop {
// Check if there is a new edit channel we need to send. On IOS,
// the websocket will be killed when the device is put into sleep. If we
// find the socket has been closed, we create a new socket and send it to
// the webview to continue on
// https://github.com/DioxusLabs/dioxus/issues/4374
if self
.edits
.wry_queue
.poll_new_edits_location(&mut cx)
.is_ready()
{
_ = self.desktop_context.webview.evaluate_script(&format!(
"window.interpreter.waitForRequest(\"{edits_path}\", \"{expected_key}\");",
edits_path = self.edits.wry_queue.edits_path(),
expected_key = self.edits.wry_queue.required_server_key()
));
}
// If we're waiting for a render, wait for it to finish before we continue
let edits_flushed_poll = self.edits.wry_queue.poll_edits_flushed(&mut cx);
if edits_flushed_poll.is_pending() {
return;
}
{
// lock the hack-ed in lock sync wry has some thread-safety issues with event handlers and async tasks
let _lock = crate::android_sync_lock::android_runtime_lock();
let fut = self.dom.wait_for_work();
pin_mut!(fut);
match fut.poll_unpin(&mut cx) {
std::task::Poll::Ready(_) => {}
std::task::Poll::Pending => return,
}
}
// lock the hack-ed in lock sync wry has some thread-safety issues with event handlers
let _lock = crate::android_sync_lock::android_runtime_lock();
self.edits
.wry_queue
.with_mutation_state_mut(|f| self.dom.render_immediate(f));
self.edits.wry_queue.send_edits();
}
}
#[cfg(all(feature = "devtools", debug_assertions))]
pub fn kick_stylsheets(&self) {
// run eval in the webview to kick the stylesheets by appending a query string
// we should do something less clunky than this
_ = self
.desktop_context
.webview
.evaluate_script("window.interpreter.kickAllStylesheetsOnPage()");
}
/// Displays a toast to the developer.
pub(crate) fn show_toast(
&self,
header_text: &str,
message: &str,
level: &str,
duration: Duration,
after_reload: bool,
) {
let as_ms = duration.as_millis();
let js_fn_name = match after_reload {
true => "scheduleDXToast",
false => "showDXToast",
};
_ = self.desktop_context.webview.evaluate_script(&format!(
r#"
if (typeof {js_fn_name} !== "undefined") {{
window.{js_fn_name}("{header_text}", "{message}", "{level}", {as_ms});
}}
"#,
));
}
}
/// A synchronous response to a browser event which may prevent the default browser's action
#[derive(serde::Serialize, Default)]
pub struct SynchronousEventResponse {
#[serde(rename = "preventDefault")]
prevent_default: bool,
}
impl SynchronousEventResponse {
/// Create a new SynchronousEventResponse
#[allow(unused)]
pub fn new(prevent_default: bool) -> Self {
Self { prevent_default }
}
}
/// A webview that is queued to be created. We can't spawn webviews outside of the main event loop because it may
/// block on windows so we queue them into the shared context and then create them when the main event loop is ready.
pub(crate) struct PendingWebview {
dom: VirtualDom,
cfg: Config,
sender: futures_channel::oneshot::Sender<DesktopContext>,
}
impl PendingWebview {
pub(crate) fn new(dom: VirtualDom, cfg: Config) -> (Self, PendingDesktopContext) {
let (sender, receiver) = futures_channel::oneshot::channel();
let webview = Self { dom, cfg, sender };
let pending = PendingDesktopContext { receiver };
(webview, pending)
}
pub(crate) fn create_window(self, shared: &Rc<SharedContext>) -> WebviewInstance {
let window = WebviewInstance::new(self.cfg, self.dom, shared.clone());
let cx = window
.dom
.in_scope(ScopeId::ROOT, consume_context::<Rc<DesktopService>>);
_ = self.sender.send(cx);
window
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/desktop/src/ipc.rs | packages/desktop/src/ipc.rs | use serde::{Deserialize, Serialize};
use tao::window::WindowId;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum UserWindowEvent {
/// A global hotkey event
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
GlobalHotKeyEvent(global_hotkey::GlobalHotKeyEvent),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
MudaMenuEvent(muda::MenuEvent),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
TrayIconEvent(tray_icon::TrayIconEvent),
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
TrayMenuEvent(tray_icon::menu::MenuEvent),
/// Poll the virtualdom
Poll(WindowId),
/// Handle an ipc message eminating from the window.postMessage of a given webview
Ipc {
id: WindowId,
msg: IpcMessage,
},
/// Handle a hotreload event, basically telling us to update our templates
#[cfg(all(feature = "devtools", debug_assertions))]
HotReloadEvent(dioxus_devtools::DevserverMsg),
// Windows-only drag-n-drop fix events.
WindowsDragDrop(WindowId),
WindowsDragOver(WindowId, i32, i32),
WindowsDragLeave(WindowId),
/// Create a new window
NewWindow,
/// Close a given window (could be any window!)
CloseWindow(WindowId),
/// Gracefully shutdown the entire app
Shutdown,
}
/// A message struct that manages the communication between the webview and the eventloop code
///
/// This needs to be serializable across the JS boundary, so the method names and structs are sensitive.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct IpcMessage {
method: String,
params: serde_json::Value,
}
/// A set of known messages that we need to respond to
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum IpcMethod<'a> {
UserEvent,
Query,
BrowserOpen,
Initialize,
Other(&'a str),
}
impl IpcMessage {
pub(crate) fn method(&self) -> IpcMethod<'_> {
match self.method.as_str() {
"user_event" => IpcMethod::UserEvent,
"query" => IpcMethod::Query,
"browser_open" => IpcMethod::BrowserOpen,
"initialize" => IpcMethod::Initialize,
_ => IpcMethod::Other(&self.method),
}
}
pub(crate) fn params(self) -> serde_json::Value {
self.params
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/config.rs | packages/liveview/src/config.rs | use dioxus_core::{LaunchConfig, VirtualDom};
use crate::LiveviewRouter;
pub(crate) fn app_title() -> String {
dioxus_cli_config::app_title().unwrap_or_else(|| "Dioxus Liveview App".to_string())
}
/// A configuration for the LiveView server.
pub struct Config<R: LiveviewRouter> {
router: R,
address: std::net::SocketAddr,
route: String,
}
impl<R: LiveviewRouter + 'static> LaunchConfig for Config<R> {}
impl<R: LiveviewRouter> Default for Config<R> {
fn default() -> Self {
Self {
address: dioxus_cli_config::fullstack_address_or_localhost(),
router: R::create_default_liveview_router(),
route: "/".to_string(),
}
}
}
impl<R: LiveviewRouter> Config<R> {
/// Set the route to use for the LiveView server.
pub fn route(mut self, route: impl Into<String>) -> Self {
self.route = route.into();
self
}
/// Create a new configuration for the LiveView server.
pub fn with_app(mut self, app: fn() -> dioxus_core::Element) -> Self {
self.router = self.router.with_app(&self.route, app);
self
}
/// Create a new configuration for the LiveView server.
pub fn with_virtual_dom(
mut self,
virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
) -> Self {
self.router = self.router.with_virtual_dom(&self.route, virtual_dom);
self
}
/// Set the address to listen on.
pub fn address(mut self, address: impl Into<std::net::SocketAddr>) -> Self {
self.address = address.into();
self
}
/// Launch the LiveView server.
pub async fn launch(self) {
println!("{} started on http://{}", app_title(), self.address);
self.router.start(self.address).await
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/launch.rs | packages/liveview/src/launch.rs | use dioxus_core::*;
use std::any::Any;
pub type Config = crate::Config<axum::Router>;
/// Launches the WebView and runs the event loop, with configuration and root props.
pub fn launch(
root: fn() -> Element,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
platform_configs: Vec<Box<dyn Any>>,
) -> ! {
#[cfg(feature = "multi-thread")]
let mut builder = tokio::runtime::Builder::new_multi_thread();
#[cfg(not(feature = "multi-thread"))]
let mut builder = tokio::runtime::Builder::new_current_thread();
let config = platform_configs
.into_iter()
.find_map(|cfg| cfg.downcast::<Config>().ok().map(|cfg| *cfg))
.unwrap_or_default();
builder.enable_all().build().unwrap().block_on(async move {
config
.with_virtual_dom(move || {
let mut virtual_dom = VirtualDom::new(root);
for context in &contexts {
virtual_dom.insert_any_root_context(context());
}
virtual_dom
})
.launch()
.await;
});
panic!("Launching a liveview app should never return")
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/element.rs | packages/liveview/src/element.rs | use dioxus_core::ElementId;
use dioxus_html::{
geometry::{PixelsRect, PixelsSize, PixelsVector2D},
MountedResult, RenderedElementBacking,
};
use crate::query::QueryEngine;
/// A mounted element passed to onmounted events
#[derive(Clone)]
pub struct LiveviewElement {
id: ElementId,
query: QueryEngine,
}
impl LiveviewElement {
pub(crate) fn new(id: ElementId, query: QueryEngine) -> Self {
Self { id, query }
}
}
macro_rules! scripted_getter {
($meth_name:ident, $script:literal, $output_type:path) => {
fn $meth_name(
&self,
) -> std::pin::Pin<
Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<$output_type>>>,
> {
let script = format!($script, id = self.id.0);
let fut = self
.query
.new_query::<Option<$output_type>>(&script)
.resolve();
Box::pin(async move {
match fut.await {
Ok(Some(res)) => Ok(res),
Ok(None) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(err),
)),
}
})
}
};
}
impl RenderedElementBacking for LiveviewElement {
fn as_any(&self) -> &dyn std::any::Any {
self
}
scripted_getter!(
get_scroll_offset,
"return [window.interpreter.getScrollLeft({id}), window.interpreter.getScrollTop({id})]",
PixelsVector2D
);
scripted_getter!(
get_scroll_size,
"return [window.interpreter.getScrollWidth({id}), window.interpreter.getScrollHeight({id})]",
PixelsSize
);
scripted_getter!(
get_client_rect,
"return window.interpreter.getClientRect({id});",
PixelsRect
);
fn scroll_to(
&self,
options: dioxus_html::ScrollToOptions,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scrollTo({}, {});",
self.id.0,
serde_json::to_string(&options).expect("Failed to serialize ScrollToOptions")
);
let fut = self.query.new_query::<bool>(&script).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = MountedResult<()>>>> {
let script = format!(
"return window.interpreter.scroll({}, {}, {}, {});",
self.id.0,
coordinates.x,
coordinates.y,
serde_json::to_string(&behavior).expect("Failed to serialize ScrollBehavior")
);
let fut = self.query.new_query::<bool>(&script).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
fn set_focus(
&self,
focus: bool,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.setFocus({}, {});",
self.id.0, focus
);
let fut = self.query.new_query::<bool>(&script).resolve();
Box::pin(async move {
match fut.await {
Ok(true) => Ok(()),
Ok(false) => MountedResult::Err(dioxus_html::MountedError::OperationFailed(
Box::new(DesktopQueryError::FailedToQuery),
)),
Err(err) => {
MountedResult::Err(dioxus_html::MountedError::OperationFailed(Box::new(err)))
}
}
})
}
}
#[derive(Debug)]
enum DesktopQueryError {
FailedToQuery,
}
impl std::fmt::Display for DesktopQueryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DesktopQueryError::FailedToQuery => write!(f, "Failed to query the element"),
}
}
}
impl std::error::Error for DesktopQueryError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/lib.rs | packages/liveview/src/lib.rs | #![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 adapters;
#[allow(unused_imports)]
pub use adapters::*;
mod element;
pub mod pool;
mod query;
use dioxus_interpreter_js::NATIVE_JS;
use futures_util::{SinkExt, StreamExt};
pub use pool::*;
mod config;
mod document;
mod events;
mod history;
pub use config::*;
#[cfg(feature = "axum")]
pub mod launch;
pub trait WebsocketTx: SinkExt<String, Error = LiveViewError> {}
impl<T> WebsocketTx for T where T: SinkExt<String, Error = LiveViewError> {}
pub trait WebsocketRx: StreamExt<Item = Result<String, LiveViewError>> {}
impl<T> WebsocketRx for T where T: StreamExt<Item = Result<String, LiveViewError>> {}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LiveViewError {
#[error("Sending to client error")]
SendingFailed,
}
fn handle_edits_code() -> String {
use dioxus_interpreter_js::unified_bindings::SLEDGEHAMMER_JS;
let serialize_file_uploads = r#"if (
target.tagName === "INPUT" &&
(event.type === "change" || event.type === "input")
) {
const type = target.getAttribute("type");
if (type === "file") {
async function read_files() {
const files = target.files;
const file_contents = {};
for (let i = 0; i < files.length; i++) {
const file = files[i];
file_contents[file.name] = Array.from(
new Uint8Array(await file.arrayBuffer())
);
}
let file_engine = {
files: file_contents,
};
contents.files = file_engine;
if (realId === null) {
return;
}
const message = window.interpreter.sendSerializedEvent({
name: name,
element: parseInt(realId),
data: contents,
bubbles,
});
window.ipc.postMessage(message);
}
read_files();
return;
}
}"#;
let mut interpreter = format!(
r#"
// Bring the sledgehammer code
{SLEDGEHAMMER_JS}
// And then extend it with our native bindings
{NATIVE_JS}
"#
)
.replace("/*POST_EVENT_SERIALIZATION*/", serialize_file_uploads)
.replace("export", "");
while let Some(import_start) = interpreter.find("import") {
let import_end = interpreter[import_start..]
.find([';', '\n'])
.map(|i| i + import_start)
.unwrap_or_else(|| interpreter.len());
interpreter.replace_range(import_start..import_end, "");
}
let main_js = include_str!("./main.js");
let js = format!("{interpreter}\n{main_js}");
js
}
/// This script that gets injected into your app connects this page to the websocket endpoint
///
/// Once the endpoint is connected, it will send the initial state of the app, and then start
/// processing user events and returning edits to the liveview instance.
///
/// You can pass a relative path prefixed with "/", or enter a full URL including the protocol
/// (`ws:` or `wss:`) as an argument.
///
/// If you enter a relative path, the web client automatically prefixes the host address in
/// `window.location` when creating a web socket to LiveView.
///
/// ```rust
/// use dioxus_liveview::interpreter_glue;
///
/// // Creates websocket connection to same host as current page
/// interpreter_glue("/api/liveview");
///
/// // Creates websocket connection to specified url
/// interpreter_glue("ws://localhost:8080/api/liveview");
/// ```
pub fn interpreter_glue(url_or_path: &str) -> String {
// If the url starts with a `/`, generate glue which reuses current host
let get_ws_url = if url_or_path.starts_with('/') {
r#"
let loc = window.location;
let new_url = "";
if (loc.protocol === "https:") {{
new_url = "wss:";
}} else {{
new_url = "ws:";
}}
new_url += "//" + loc.host + path;
return new_url;
"#
} else {
"return path;"
};
let handle_edits = handle_edits_code();
format!(
r#"
<script>
function __dioxusGetWsUrl(path) {{
{get_ws_url}
}}
var WS_ADDR = __dioxusGetWsUrl("{url_or_path}");
{handle_edits}
</script>
"#
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/document.rs | packages/liveview/src/document.rs | use dioxus_core::queue_effect;
use dioxus_core::ScopeId;
use dioxus_document::{
create_element_in_head, Document, Eval, EvalError, Evaluator, LinkProps, MetaProps,
ScriptProps, StyleProps,
};
use dioxus_history::History;
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
use std::rc::Rc;
use crate::history::LiveviewHistory;
use crate::query::{Query, QueryEngine};
/// Represents a liveview-target's JavaScript evaluator.
pub(crate) struct LiveviewEvaluator {
query: Query<serde_json::Value>,
}
impl LiveviewEvaluator {
/// Creates a new evaluator for liveview-based targets.
pub fn create(query_engine: QueryEngine, js: String) -> GenerationalBox<Box<dyn Evaluator>> {
let query = query_engine.new_query(&js);
// We create a generational box that is owned by the query slot so that when we drop the query slot, the generational box is also dropped.
let owner = UnsyncStorage::owner();
let query_id = query.id;
let query = owner.insert(Box::new(LiveviewEvaluator { query }) as Box<dyn Evaluator>);
query_engine.active_requests.slab.borrow_mut()[query_id].owner = Some(owner);
query
}
}
impl Evaluator for LiveviewEvaluator {
/// # Panics
/// This will panic if the query is currently being awaited.
fn poll_join(
&mut self,
context: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
self.query
.poll_result(context)
.map_err(|e| EvalError::Communication(e.to_string()))
}
/// Sends a message to the evaluated JavaScript.
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
if let Err(e) = self.query.send(data) {
return Err(EvalError::Communication(e.to_string()));
}
Ok(())
}
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
///
/// # Panics
/// This will panic if the query is currently being awaited.
fn poll_recv(
&mut self,
context: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
self.query
.poll_recv(context)
.map_err(|e| EvalError::Communication(e.to_string()))
}
}
/// Provides the LiveviewDocument through [`dioxus_core::Runtime::provide_context`].
pub fn init_document() {
let rt = dioxus_core::Runtime::current();
let query = rt.consume_context::<QueryEngine>(ScopeId::ROOT).unwrap();
let provider: Rc<dyn Document> = Rc::new(LiveviewDocument {
query: query.clone(),
});
rt.provide_context(ScopeId::ROOT, provider);
let history = LiveviewHistory::new(Rc::new(move |script: &str| {
Eval::new(LiveviewEvaluator::create(query.clone(), script.to_string()))
}));
let history: Rc<dyn History> = Rc::new(history);
rt.provide_context(ScopeId::ROOT, history);
}
/// Reprints the liveview-target's provider of evaluators.
#[derive(Clone)]
pub struct LiveviewDocument {
query: QueryEngine,
}
impl Document for LiveviewDocument {
fn eval(&self, js: String) -> Eval {
Eval::new(LiveviewEvaluator::create(self.query.clone(), js))
}
/// Set the title of the document
fn set_title(&self, title: String) {
let myself = self.clone();
queue_effect(move || {
myself.eval(format!("document.title = {title:?};"));
});
}
/// Create a new meta tag in the head
fn create_meta(&self, props: MetaProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head("meta", &props.attributes(), None));
});
}
/// Create a new script tag in the head
fn create_script(&self, props: ScriptProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head(
"script",
&props.attributes(),
props.script_contents().ok(),
));
});
}
/// Create a new style tag in the head
fn create_style(&self, props: StyleProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head(
"style",
&props.attributes(),
props.style_contents().ok(),
));
});
}
/// Create a new link tag in the head
fn create_link(&self, props: LinkProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head("link", &props.attributes(), None));
});
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/history.rs | packages/liveview/src/history.rs | use dioxus_core::spawn;
use dioxus_document::Eval;
use dioxus_history::History;
use serde::{Deserialize, Serialize};
use std::rc::Rc;
use std::sync::{Mutex, RwLock};
use std::{collections::BTreeMap, sync::Arc};
/// A [`History`] that evaluates history through JS.
pub(crate) struct LiveviewHistory {
action_tx: tokio::sync::mpsc::UnboundedSender<Action>,
timeline: Arc<Mutex<Timeline>>,
updater_callback: Arc<RwLock<Arc<dyn Fn() + Send + Sync>>>,
}
struct Timeline {
current_index: usize,
routes: BTreeMap<usize, String>,
}
#[derive(Serialize, Deserialize, Debug)]
struct State {
index: usize,
}
#[derive(Serialize, Deserialize, Debug)]
struct Session {
#[serde(with = "routes")]
routes: BTreeMap<usize, String>,
last_visited: usize,
}
enum Action {
GoBack,
GoForward,
Push(String),
Replace(String),
External(String),
}
impl Timeline {
fn new(initial_path: String) -> Self {
Self {
current_index: 0,
routes: BTreeMap::from([(0, initial_path)]),
}
}
fn init(
&mut self,
route: String,
state: Option<State>,
session: Option<Session>,
depth: usize,
) -> State {
if let Some(session) = session {
self.routes = session.routes;
if state.is_none() {
// top of stack
let last_visited = session.last_visited;
self.routes.retain(|&lhs, _| lhs <= last_visited);
}
};
let state = match state {
Some(state) => {
self.current_index = state.index;
state
}
None => {
let index = depth - 1;
self.current_index = index;
State { index }
}
};
self.routes.insert(state.index, route);
state
}
fn update(&mut self, route: String, state: Option<State>) -> State {
if let Some(state) = state {
self.current_index = state.index;
self.routes.insert(self.current_index, route);
state
} else {
self.push(route)
}
}
fn push(&mut self, route: String) -> State {
// top of stack
let index = self.current_index + 1;
self.current_index = index;
self.routes.insert(index, route);
self.routes.retain(|&rhs, _| index >= rhs);
State {
index: self.current_index,
}
}
fn replace(&mut self, route: String) -> State {
self.routes.insert(self.current_index, route);
State {
index: self.current_index,
}
}
fn current_route(&self) -> &str {
&self.routes[&self.current_index]
}
fn session(&self) -> Session {
Session {
routes: self.routes.clone(),
last_visited: self.current_index,
}
}
}
impl LiveviewHistory {
/// Create a [`LiveviewHistory`] in the given scope.
/// When using a [`LiveviewHistory`] in combination with use_eval, history must be untampered with.
///
/// # Panics
///
/// Panics if the function is not called in a dioxus runtime with a Liveview context.
pub(crate) fn new(eval: Rc<dyn Fn(&str) -> Eval>) -> Self {
Self::new_with_initial_path(
"/".parse().unwrap_or_else(|err| {
panic!("index route does not exist:\n{}\n use LiveviewHistory::new_with_initial_path to set a custom path", err)
}),
eval
)
}
/// Create a [`LiveviewHistory`] in the given scope, starting at `initial_path`.
/// When using a [`LiveviewHistory`] in combination with use_eval, history must be untampered with.
///
/// # Panics
///
/// Panics if the function is not called in a dioxus runtime with a Liveview context.
fn new_with_initial_path(initial_path: String, eval: Rc<dyn Fn(&str) -> Eval>) -> Self {
let (action_tx, mut action_rx) = tokio::sync::mpsc::unbounded_channel::<Action>();
let timeline = Arc::new(Mutex::new(Timeline::new(initial_path)));
let updater_callback: Arc<RwLock<Arc<dyn Fn() + Send + Sync>>> =
Arc::new(RwLock::new(Arc::new(|| {})));
// Listen to server actions
spawn({
let timeline = timeline.clone();
let create_eval = eval.clone();
async move {
loop {
let eval = action_rx.recv().await.expect("sender to exist");
let _ = match eval {
Action::GoBack => create_eval(
r#"
// this triggers a PopState event
history.back();
"#,
),
Action::GoForward => create_eval(
r#"
// this triggers a PopState event
history.forward();
"#,
),
Action::Push(route) => {
let mut timeline = timeline.lock().expect("unpoisoned mutex");
let state = timeline.push(route.clone());
let state = serde_json::to_string(&state).expect("serializable state");
let session = serde_json::to_string(&timeline.session())
.expect("serializable session");
create_eval(&format!(
r#"
// this does not trigger a PopState event
history.pushState({state}, "", "{route}");
sessionStorage.setItem("liveview", '{session}');
"#
))
}
Action::Replace(route) => {
let mut timeline = timeline.lock().expect("unpoisoned mutex");
let state = timeline.replace(route.clone());
let state = serde_json::to_string(&state).expect("serializable state");
let session = serde_json::to_string(&timeline.session())
.expect("serializable session");
create_eval(&format!(
r#"
// this does not trigger a PopState event
history.replaceState({state}, "", "{route}");
sessionStorage.setItem("liveview", '{session}');
"#
))
}
Action::External(url) => create_eval(&format!(
r#"
location.href = "{url}";
"#
)),
};
}
}
});
// Listen to browser actions
spawn({
let updater = updater_callback.clone();
let timeline = timeline.clone();
let create_eval = eval.clone();
async move {
let mut popstate_eval = {
let init_eval = create_eval(
r#"
return [
document.location.pathname + "?" + document.location.search + "\#" + document.location.hash,
history.state,
JSON.parse(sessionStorage.getItem("liveview")),
history.length,
];
"#,
).await.expect("serializable state");
let (route, state, session, depth) =
serde_json::from_value::<(String, Option<State>, Option<Session>, usize)>(
init_eval,
)
.expect("serializable state");
let mut timeline = timeline.lock().expect("unpoisoned mutex");
let state = timeline.init(route.clone(), state, session, depth);
let state = serde_json::to_string(&state).expect("serializable state");
let session =
serde_json::to_string(&timeline.session()).expect("serializable session");
// Call the updater callback
(updater.read().unwrap())();
create_eval(&format!(
r#"
// this does not trigger a PopState event
history.replaceState({state}, "", "{route}");
sessionStorage.setItem("liveview", '{session}');
window.addEventListener("popstate", (event) => {{
dioxus.send([
document.location.pathname + "?" + document.location.search + "\#" + document.location.hash,
event.state,
]);
}});
"#
))
};
loop {
let event = match popstate_eval.recv().await {
Ok(event) => event,
Err(_) => continue,
};
let (route, state) = serde_json::from_value::<(String, Option<State>)>(event)
.expect("serializable state");
let mut timeline = timeline.lock().expect("unpoisoned mutex");
let state = timeline.update(route.clone(), state);
let state = serde_json::to_string(&state).expect("serializable state");
let session =
serde_json::to_string(&timeline.session()).expect("serializable session");
let _ = create_eval(&format!(
r#"
// this does not trigger a PopState event
history.replaceState({state}, "", "{route}");
sessionStorage.setItem("liveview", '{session}');
"#
));
// Call the updater callback
(updater.read().unwrap())();
}
}
});
Self {
action_tx,
timeline,
updater_callback,
}
}
}
impl History for LiveviewHistory {
fn go_back(&self) {
let _ = self.action_tx.send(Action::GoBack);
}
fn go_forward(&self) {
let _ = self.action_tx.send(Action::GoForward);
}
fn push(&self, route: String) {
let _ = self.action_tx.send(Action::Push(route));
}
fn replace(&self, route: String) {
let _ = self.action_tx.send(Action::Replace(route));
}
fn external(&self, url: String) -> bool {
let _ = self.action_tx.send(Action::External(url));
true
}
fn current_route(&self) -> String {
let timeline = self.timeline.lock().expect("unpoisoned mutex");
timeline.current_route().to_string()
}
fn can_go_back(&self) -> bool {
let timeline = self.timeline.lock().expect("unpoisoned mutex");
// Check if the one before is contiguous (i.e., not an external page)
let visited_indices: Vec<usize> = timeline.routes.keys().cloned().collect();
visited_indices
.iter()
.position(|&rhs| timeline.current_index == rhs)
.is_some_and(|index| {
index > 0 && visited_indices[index - 1] == timeline.current_index - 1
})
}
fn can_go_forward(&self) -> bool {
let timeline = self.timeline.lock().expect("unpoisoned mutex");
// Check if the one after is contiguous (i.e., not an external page)
let visited_indices: Vec<usize> = timeline.routes.keys().cloned().collect();
visited_indices
.iter()
.rposition(|&rhs| timeline.current_index == rhs)
.is_some_and(|index| {
index < visited_indices.len() - 1
&& visited_indices[index + 1] == timeline.current_index + 1
})
}
fn updater(&self, callback: Arc<dyn Fn() + Send + Sync>) {
let mut updater_callback = self.updater_callback.write().unwrap();
*updater_callback = callback;
}
fn include_prevent_default(&self) -> bool {
true
}
}
mod routes {
use serde::de::{MapAccess, Visitor};
use serde::{ser::SerializeMap, Deserializer, Serializer};
use std::collections::BTreeMap;
pub fn serialize<S>(routes: &BTreeMap<usize, String>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(routes.len()))?;
for (index, route) in routes.iter() {
map.serialize_entry(&index.to_string(), &route.to_string())?;
}
map.end()
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<BTreeMap<usize, String>, D::Error>
where
D: Deserializer<'de>,
{
struct BTreeMapVisitor {}
impl<'de> Visitor<'de> for BTreeMapVisitor {
type Value = BTreeMap<usize, String>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a map with indices and routable values")
}
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut routes = BTreeMap::new();
while let Some((index, route)) = map.next_entry::<String, String>()? {
let index = index.parse::<usize>().map_err(serde::de::Error::custom)?;
routes.insert(index, route);
}
Ok(routes)
}
}
deserializer.deserialize_map(BTreeMapVisitor {})
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/query.rs | packages/liveview/src/query.rs | use std::{cell::RefCell, rc::Rc};
use futures_util::FutureExt;
use generational_box::{Owner, UnsyncStorage};
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;
use slab::Slab;
use thiserror::Error;
use tokio::sync::broadcast::error::RecvError;
const DIOXUS_CODE: &str = r#"
let dioxus = {
recv: function () {
return new Promise((resolve, _reject) => {
// Ever 50 ms check for new data
let timeout = setTimeout(() => {
let __msg = null;
while (true) {
let __data = _message_queue.shift();
if (__data) {
__msg = __data;
break;
}
}
clearTimeout(timeout);
resolve(__msg);
}, 50);
});
},
send: function (value) {
window.ipc.postMessage(
JSON.stringify({
"method":"query",
"params": {
"id": _request_id,
"data": value,
"returned_value": false
}
})
);
}
}"#;
/// Tracks what query ids are currently active
pub(crate) struct SharedSlab<T = ()> {
pub(crate) slab: Rc<RefCell<Slab<T>>>,
}
impl<T> Clone for SharedSlab<T> {
fn clone(&self) -> Self {
Self {
slab: self.slab.clone(),
}
}
}
impl<T> Default for SharedSlab<T> {
fn default() -> Self {
SharedSlab {
slab: Rc::new(RefCell::new(Slab::new())),
}
}
}
pub(crate) struct QueryEntry {
channel_sender: tokio::sync::mpsc::UnboundedSender<Value>,
return_sender: Option<tokio::sync::oneshot::Sender<Value>>,
pub(crate) owner: Option<Owner<UnsyncStorage>>,
}
const QUEUE_NAME: &str = "__msg_queues";
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
#[derive(Clone)]
pub(crate) struct QueryEngine {
pub(crate) active_requests: SharedSlab<QueryEntry>,
query_tx: tokio::sync::mpsc::UnboundedSender<String>,
}
impl QueryEngine {
pub(crate) fn new(query_tx: tokio::sync::mpsc::UnboundedSender<String>) -> Self {
Self {
active_requests: Default::default(),
query_tx,
}
}
/// Creates a new query and returns a handle to it. The query will be resolved when the webview returns a result with the same id.
pub fn new_query<V: DeserializeOwned>(&self, script: &str) -> Query<V> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let (return_tx, return_rx) = tokio::sync::oneshot::channel();
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
channel_sender: tx,
return_sender: Some(return_tx),
owner: None,
});
// start the query
// We embed the return of the eval in a function so we can send it back to the main thread
if let Err(err) = self.query_tx.send(format!(
r#"(function(){{
(async (resolve, _reject) => {{
{DIOXUS_CODE}
if (!window.{QUEUE_NAME}) {{
window.{QUEUE_NAME} = [];
}}
let _request_id = {request_id};
if (!window.{QUEUE_NAME}[{request_id}]) {{
window.{QUEUE_NAME}[{request_id}] = [];
}}
let _message_queue = window.{QUEUE_NAME}[{request_id}];
{script}
}})().then((result)=>{{
let returned_value = {{
"method":"query",
"params": {{
"id": {request_id},
"data": result,
"returned_value": true
}}
}};
window.ipc.postMessage(
JSON.stringify(returned_value)
);
}})
}})();"#
)) {
tracing::warn!("Query error: {err}");
}
Query {
query_engine: self.clone(),
id: request_id,
receiver: rx,
return_receiver: Some(return_rx),
phantom: std::marker::PhantomData,
}
}
/// Send a query channel message to the correct query
pub fn send(&self, data: QueryResult) {
let QueryResult {
id,
data,
returned_value,
} = data;
let mut slab = self.active_requests.slab.borrow_mut();
if let Some(entry) = slab.get_mut(id) {
if returned_value {
if let Some(sender) = entry.return_sender.take() {
let _ = sender.send(data);
}
} else {
let _ = entry.channel_sender.send(data);
}
}
}
}
pub(crate) struct Query<V: DeserializeOwned> {
query_engine: QueryEngine,
pub receiver: tokio::sync::mpsc::UnboundedReceiver<Value>,
pub return_receiver: Option<tokio::sync::oneshot::Receiver<Value>>,
pub id: usize,
phantom: std::marker::PhantomData<V>,
}
impl<V: DeserializeOwned> Query<V> {
/// Resolve the query
pub async fn resolve(mut self) -> Result<V, QueryError> {
V::deserialize(self.result().await?).map_err(QueryError::Deserialize)
}
/// Send a message to the query
pub fn send<S: ToString>(&self, message: S) -> Result<(), QueryError> {
let queue_id = self.id;
let data = message.to_string();
let script = format!(
r#"
if (!window.{QUEUE_NAME}) {{
window.{QUEUE_NAME} = [];
}}
if (!window.{QUEUE_NAME}[{queue_id}]) {{
window.{QUEUE_NAME}[{queue_id}] = [];
}}
window.{QUEUE_NAME}[{queue_id}].push({data});
"#
);
self.query_engine
.query_tx
.send(script)
.map_err(|e| QueryError::Send(e.to_string()))?;
Ok(())
}
/// Poll the query for a message
pub fn poll_recv(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<Value, QueryError>> {
self.receiver
.poll_recv(cx)
.map(|result| result.ok_or(QueryError::Recv(RecvError::Closed)))
}
/// Receive the result of the query
pub async fn result(&mut self) -> Result<Value, QueryError> {
match self.return_receiver.take() {
Some(receiver) => receiver
.await
.map_err(|_| QueryError::Recv(RecvError::Closed)),
None => Err(QueryError::Finished),
}
}
/// Poll the query for a result
pub fn poll_result(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<Value, QueryError>> {
match self.return_receiver.as_mut() {
Some(receiver) => receiver
.poll_unpin(cx)
.map_err(|_| QueryError::Recv(RecvError::Closed)),
None => std::task::Poll::Ready(Err(QueryError::Finished)),
}
}
}
impl<V: DeserializeOwned> Drop for Query<V> {
fn drop(&mut self) {
self.query_engine
.active_requests
.slab
.borrow_mut()
.remove(self.id);
let queue_id = self.id;
_ = self.query_engine.query_tx.send(format!(
r#"
if (!window.{QUEUE_NAME}) {{
window.{QUEUE_NAME} = [];
}}
if (window.{QUEUE_NAME}[{queue_id}]) {{
window.{QUEUE_NAME}[{queue_id}] = [];
}}
"#
));
}
}
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum QueryError {
#[error("Error receiving query result: {0}")]
Recv(RecvError),
#[error("Error sending message to query: {0}")]
Send(String),
#[error("Error deserializing query result: {0}")]
Deserialize(serde_json::Error),
#[error("Query has already been resolved")]
Finished,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct QueryResult {
id: usize,
#[serde(default)]
data: Value,
#[serde(default)]
returned_value: bool,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/events.rs | packages/liveview/src/events.rs | //! Convert a serialized event to an event trigger
use dioxus_html::*;
use crate::element::LiveviewElement;
pub(crate) struct SerializedHtmlEventConverter;
impl HtmlEventConverter for SerializedHtmlEventConverter {
fn convert_animation_data(&self, event: &PlatformEventData) -> AnimationData {
event
.downcast::<SerializedAnimationData>()
.cloned()
.unwrap()
.into()
}
fn convert_cancel_data(&self, event: &PlatformEventData) -> CancelData {
event
.downcast::<SerializedCancelData>()
.cloned()
.unwrap()
.into()
}
fn convert_clipboard_data(&self, event: &PlatformEventData) -> ClipboardData {
event
.downcast::<SerializedClipboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_composition_data(&self, event: &PlatformEventData) -> CompositionData {
event
.downcast::<SerializedCompositionData>()
.cloned()
.unwrap()
.into()
}
fn convert_drag_data(&self, event: &PlatformEventData) -> DragData {
event
.downcast::<SerializedDragData>()
.cloned()
.unwrap()
.into()
}
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData {
event
.downcast::<SerializedFocusData>()
.cloned()
.unwrap()
.into()
}
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
event
.downcast::<SerializedFormData>()
.cloned()
.unwrap()
.into()
}
fn convert_image_data(&self, event: &PlatformEventData) -> ImageData {
event
.downcast::<SerializedImageData>()
.cloned()
.unwrap()
.into()
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
event
.downcast::<SerializedKeyboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_media_data(&self, event: &PlatformEventData) -> MediaData {
event
.downcast::<SerializedMediaData>()
.cloned()
.unwrap()
.into()
}
fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData {
event.downcast::<LiveviewElement>().cloned().unwrap().into()
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
event
.downcast::<SerializedMouseData>()
.cloned()
.unwrap()
.into()
}
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
event
.downcast::<SerializedPointerData>()
.cloned()
.unwrap()
.into()
}
fn convert_resize_data(&self, event: &PlatformEventData) -> ResizeData {
event
.downcast::<SerializedResizeData>()
.cloned()
.unwrap()
.into()
}
fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData {
event
.downcast::<SerializedScrollData>()
.cloned()
.unwrap()
.into()
}
fn convert_selection_data(&self, event: &PlatformEventData) -> SelectionData {
event
.downcast::<SerializedSelectionData>()
.cloned()
.unwrap()
.into()
}
fn convert_toggle_data(&self, event: &PlatformEventData) -> ToggleData {
event
.downcast::<SerializedToggleData>()
.cloned()
.unwrap()
.into()
}
fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData {
event
.downcast::<SerializedTouchData>()
.cloned()
.unwrap()
.into()
}
fn convert_transition_data(&self, event: &PlatformEventData) -> TransitionData {
event
.downcast::<SerializedTransitionData>()
.cloned()
.unwrap()
.into()
}
fn convert_visible_data(&self, event: &PlatformEventData) -> VisibleData {
event
.downcast::<SerializedVisibleData>()
.cloned()
.unwrap()
.into()
}
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
event
.downcast::<SerializedWheelData>()
.cloned()
.unwrap()
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/pool.rs | packages/liveview/src/pool.rs | use crate::{
document::init_document,
element::LiveviewElement,
events::SerializedHtmlEventConverter,
query::{QueryEngine, QueryResult},
LiveViewError,
};
use dioxus_core::{provide_context, Element, Event, ScopeId, VirtualDom};
use dioxus_html::{EventData, HtmlEvent, PlatformEventData};
use dioxus_interpreter_js::MutationState;
use futures_util::{pin_mut, SinkExt, StreamExt};
use serde::Serialize;
use std::{any::Any, rc::Rc};
use tokio_util::task::LocalPoolHandle;
#[derive(Clone)]
pub struct LiveViewPool {
pub(crate) pool: LocalPoolHandle,
}
impl Default for LiveViewPool {
fn default() -> Self {
Self::new()
}
}
impl LiveViewPool {
pub fn new() -> Self {
// Set the event converter
dioxus_html::set_event_converter(Box::new(SerializedHtmlEventConverter));
LiveViewPool {
pool: LocalPoolHandle::new(
std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
),
}
}
pub async fn launch(
&self,
ws: impl LiveViewSocket,
app: fn() -> Element,
) -> Result<(), LiveViewError> {
self.launch_with_props(ws, |app| app(), app).await
}
pub async fn launch_with_props<T: Clone + Send + 'static>(
&self,
ws: impl LiveViewSocket,
app: fn(T) -> Element,
props: T,
) -> Result<(), LiveViewError> {
self.launch_virtualdom(ws, move || VirtualDom::new_with_props(app, props))
.await
}
pub async fn launch_virtualdom<F: FnOnce() -> VirtualDom + Send + 'static>(
&self,
ws: impl LiveViewSocket,
make_app: F,
) -> Result<(), LiveViewError> {
match self.pool.spawn_pinned(move || run(make_app(), ws)).await {
Ok(Ok(_)) => Ok(()),
Ok(Err(e)) => Err(e),
Err(_) => Err(LiveViewError::SendingFailed),
}
}
}
/// A LiveViewSocket is a Sink and Stream of Strings that Dioxus uses to communicate with the client
///
/// Most websockets from most HTTP frameworks can be converted into a LiveViewSocket using the appropriate adapter.
///
/// You can also convert your own socket into a LiveViewSocket by implementing this trait. This trait is an auto trait,
/// meaning that as long as your type implements Stream and Sink, you can use it as a LiveViewSocket.
///
/// For example, the axum implementation is a really small transform:
///
/// ```rust, ignore
/// pub fn axum_socket(ws: WebSocket) -> impl LiveViewSocket {
/// ws.map(transform_rx)
/// .with(transform_tx)
/// .sink_map_err(|_| LiveViewError::SendingFailed)
/// }
///
/// fn transform_rx(message: Result<Message, axum::Error>) -> Result<String, LiveViewError> {
/// message
/// .map_err(|_| LiveViewError::SendingFailed)?
/// .into_text()
/// .map_err(|_| LiveViewError::SendingFailed)
/// }
///
/// async fn transform_tx(message: String) -> Result<Message, axum::Error> {
/// Ok(Message::Text(message))
/// }
/// ```
pub trait LiveViewSocket:
SinkExt<Vec<u8>, Error = LiveViewError>
+ StreamExt<Item = Result<Vec<u8>, LiveViewError>>
+ Send
+ 'static
{
}
impl<S> LiveViewSocket for S where
S: SinkExt<Vec<u8>, Error = LiveViewError>
+ StreamExt<Item = Result<Vec<u8>, LiveViewError>>
+ Send
+ 'static
{
}
/// The primary event loop for the VirtualDom waiting for user input
///
/// This function makes it easy to integrate Dioxus LiveView with any socket-based framework.
///
/// As long as your framework can provide a Sink and Stream of Bytes, you can use this function.
///
/// You might need to transform the error types of the web backend into the LiveView error type.
pub async fn run(mut vdom: VirtualDom, ws: impl LiveViewSocket) -> Result<(), LiveViewError> {
#[cfg(all(feature = "devtools", debug_assertions))]
let mut hot_reload_rx = {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
dioxus_devtools::connect(move |template| _ = tx.send(template));
rx
};
let mut mutations = MutationState::default();
// Create the a proxy for query engine
let (query_tx, mut query_rx) = tokio::sync::mpsc::unbounded_channel();
let query_engine = QueryEngine::new(query_tx);
vdom.runtime().in_scope(ScopeId::ROOT, || {
provide_context(query_engine.clone());
init_document();
});
// pin the futures so we can use select!
pin_mut!(ws);
if let Some(edits) = {
vdom.rebuild(&mut mutations);
take_edits(&mut mutations)
} {
// send the initial render to the client
ws.send(edits).await?;
}
// desktop uses this wrapper struct thing around the actual event itself
// this is sorta driven by tao/wry
#[derive(serde::Deserialize, Debug)]
#[serde(tag = "method", content = "params")]
enum IpcMessage {
#[serde(rename = "user_event")]
Event(Box<HtmlEvent>),
#[serde(rename = "query")]
Query(QueryResult),
}
loop {
#[cfg(all(feature = "devtools", debug_assertions))]
let hot_reload_wait = hot_reload_rx.recv();
#[cfg(not(all(feature = "devtools", debug_assertions)))]
let hot_reload_wait: std::future::Pending<Option<()>> = std::future::pending();
tokio::select! {
// poll any futures or suspense
_ = vdom.wait_for_work() => {}
evt = ws.next() => {
match evt.as_ref().map(|o| o.as_deref()) {
// respond with a pong every ping to keep the websocket alive
Some(Ok(b"__ping__")) => {
ws.send(text_frame("__pong__")).await?;
}
Some(Ok(evt)) => {
if let Ok(message) = serde_json::from_str::<IpcMessage>(&String::from_utf8_lossy(evt)) {
match message {
IpcMessage::Event(evt) => {
// Intercept the mounted event and insert a custom element type
let event = if let EventData::Mounted = &evt.data {
let element = LiveviewElement::new(evt.element, query_engine.clone());
Event::new(
Rc::new(PlatformEventData::new(Box::new(element))) as Rc<dyn Any>,
evt.bubbles,
)
} else {
Event::new(
evt.data.into_any(),
evt.bubbles,
)
};
vdom.runtime().handle_event(
&evt.name,
event,
evt.element,
);
}
IpcMessage::Query(result) => {
query_engine.send(result);
},
}
}
}
// log this I guess? when would we get an error here?
Some(Err(_e)) => {}
None => return Ok(()),
}
}
// handle any new queries
Some(query) = query_rx.recv() => {
ws.send(text_frame(&serde_json::to_string(&ClientUpdate::Query(query)).unwrap())).await?;
}
Some(msg) = hot_reload_wait => {
#[cfg(all(feature = "devtools", debug_assertions))]
match msg {
dioxus_devtools::DevserverMsg::HotReload(msg)=> {
dioxus_devtools::apply_changes(&vdom, &msg);
}
dioxus_devtools::DevserverMsg::Shutdown => {
std::process::exit(0);
},
dioxus_devtools::DevserverMsg::FullReloadCommand
| dioxus_devtools::DevserverMsg::FullReloadStart
| dioxus_devtools::DevserverMsg::FullReloadFailed => {
// usually only web gets this message - what are we supposed to do?
// Maybe we could just binary patch ourselves in place without losing window state?
},
_ => {}
}
#[cfg(not(all(feature = "devtools", debug_assertions)))]
let () = msg;
}
}
// render the vdom
vdom.render_immediate(&mut mutations);
if let Some(edits) = take_edits(&mut mutations) {
ws.send(edits).await?;
}
}
}
fn text_frame(text: &str) -> Vec<u8> {
let mut bytes = vec![0];
bytes.extend(text.as_bytes());
bytes
}
fn take_edits(mutations: &mut MutationState) -> Option<Vec<u8>> {
// Add an extra one at the beginning to tell the shim this is a binary frame
let mut bytes = vec![1];
mutations.write_memory_into(&mut bytes);
(bytes.len() > 1).then_some(bytes)
}
#[derive(Serialize)]
#[serde(tag = "type", content = "data")]
enum ClientUpdate {
#[serde(rename = "query")]
Query(String),
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/adapters/mod.rs | packages/liveview/src/adapters/mod.rs | use std::future::Future;
use dioxus_core::{Element, VirtualDom};
#[cfg(feature = "axum")]
pub mod axum_adapter;
#[cfg(feature = "axum")]
pub use axum_adapter::*;
/// A trait for servers that can be used to host a LiveView app.
pub trait LiveviewRouter {
/// Create a new router.
fn create_default_liveview_router() -> Self;
/// Add a liveview route to the server from a component
fn with_app(self, route: &str, app: fn() -> Element) -> Self
where
Self: Sized,
{
self.with_virtual_dom(route, move || VirtualDom::new(app))
}
/// Add a liveview route to the server from a virtual dom.
fn with_virtual_dom(
self,
route: &str,
app: impl Fn() -> VirtualDom + Send + Sync + 'static,
) -> Self;
/// Start the server on an address.
fn start(self, address: impl Into<std::net::SocketAddr>) -> impl Future<Output = ()>;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/src/adapters/axum_adapter.rs | packages/liveview/src/adapters/axum_adapter.rs | use std::sync::Arc;
use crate::{interpreter_glue, LiveViewError, LiveViewSocket, LiveviewRouter};
use axum::{
extract::{
ws::{Message, WebSocket},
WebSocketUpgrade,
},
response::Html,
routing::*,
Router,
};
use futures_util::{SinkExt, StreamExt};
/// Convert an Axum WebSocket into a `LiveViewSocket`.
///
/// This is required to launch a LiveView app using the Axum web framework.
pub fn axum_socket(ws: WebSocket) -> impl LiveViewSocket {
ws.map(transform_rx)
.with(transform_tx)
.sink_map_err(|_| LiveViewError::SendingFailed)
}
fn transform_rx(message: Result<Message, axum::Error>) -> Result<Vec<u8>, LiveViewError> {
message
.map_err(|_| LiveViewError::SendingFailed)?
.into_text()
.map(|s| s.as_str().into())
.map_err(|_| LiveViewError::SendingFailed)
}
async fn transform_tx(message: Vec<u8>) -> Result<Message, axum::Error> {
Ok(Message::Binary(message.into()))
}
impl LiveviewRouter for Router {
fn create_default_liveview_router() -> Self {
Router::new()
}
fn with_virtual_dom(
self,
route: &str,
app: impl Fn() -> dioxus_core::VirtualDom + Send + Sync + 'static,
) -> Self {
let view = crate::LiveViewPool::new();
let ws_path = format!("{}/ws", route.trim_start_matches('/'));
let title = crate::app_title();
let index_page_with_glue = move |glue: &str| {
Html(format!(
r#"
<!DOCTYPE html>
<html>
<head><title>{title}</title></head>
<body><div id="main"></div></body>
{glue}
</html>
"#,
))
};
let app = Arc::new(app);
// Add an extra catch all segment to the route
let mut route = route.trim_matches('/').to_string();
if route.is_empty() {
route = "/{*route}".to_string();
} else {
route = format!("/{route}/{{*route}}");
}
self.route(
&ws_path,
get(move |ws: WebSocketUpgrade| async move {
let app = app.clone();
ws.on_upgrade(move |socket| async move {
_ = view
.launch_virtualdom(axum_socket(socket), move || app())
.await;
})
}),
)
.route(
&route,
get(move || async move { index_page_with_glue(&interpreter_glue(&ws_path)) }),
)
}
async fn start(self, address: impl Into<std::net::SocketAddr>) {
let listener = tokio::net::TcpListener::bind(address.into()).await.unwrap();
if let Err(err) = axum::serve(listener, self.into_make_service()).await {
eprintln!("Failed to start axum server: {}", err);
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/examples/axum_stress.rs | packages/liveview/examples/axum_stress.rs | use axum::{extract::ws::WebSocketUpgrade, response::Html, routing::get, Router};
use dioxus::prelude::*;
fn app() -> Element {
let mut state = use_signal(|| 0);
use_future(move || async move {
loop {
state += 1;
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
});
rsx! {
for _ in 0..10000 {
div {
"hello axum! {state}"
}
}
}
}
#[tokio::main]
async fn main() {
dioxus::logger::initialize_default();
let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
let view = dioxus_liveview::LiveViewPool::new();
let app = Router::new()
.route(
"/",
get(move || async move {
Html(format!(
r#"
<!DOCTYPE html>
<html>
<head> <title>Dioxus LiveView with axum</title> </head>
<body> <div id="main"></div> </body>
{glue}
</html>
"#,
glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws"))
))
}),
)
.route(
"/ws",
get(move |ws: WebSocketUpgrade| async move {
ws.on_upgrade(move |socket| async move {
_ = view.launch(dioxus_liveview::axum_socket(socket), app).await;
})
}),
);
println!("Listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/liveview/examples/axum.rs | packages/liveview/examples/axum.rs | use axum::Router;
use dioxus::prelude::*;
use dioxus_liveview::LiveviewRouter;
fn app() -> Element {
let mut num = use_signal(|| 0);
rsx! {
div {
"hello axum! {num}"
button { onclick: move |_| num += 1, "Increment" }
}
}
}
#[tokio::main]
async fn main() {
dioxus::logger::initialize_default();
let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
let app = Router::new().with_app("/", app);
println!("Listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_effect.rs | packages/hooks/src/use_effect.rs | use std::{cell::Cell, rc::Rc};
use dioxus_core::*;
use futures_util::StreamExt;
use crate::use_callback;
#[doc = include_str!("../docs/side_effects.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[track_caller]
pub fn use_effect(mut callback: impl FnMut() + 'static) -> Effect {
let callback = use_callback(move |_| callback());
let location = std::panic::Location::caller();
use_hook(|| {
// Inside the effect, we track any reads so that we can rerun the effect if a value the effect reads changes
let (rc, mut changed) = ReactiveContext::new_with_origin(location);
// Deduplicate queued effects
let effect_queued = Rc::new(Cell::new(false));
// Spawn a task that will run the effect when:
// 1) The component is first run
// 2) The effect is rerun due to an async read at any time
// 3) The effect is rerun in the same tick that the component is rerun: we need to wait for the component to rerun before we can run the effect again
let queue_effect_for_next_render = move || {
if effect_queued.get() {
return;
}
effect_queued.set(true);
let effect_queued = effect_queued.clone();
queue_effect(move || {
rc.reset_and_run_in(|| callback(()));
effect_queued.set(false);
});
};
queue_effect_for_next_render();
spawn(async move {
loop {
// Wait for context to change
let _ = changed.next().await;
// Run the effect
queue_effect_for_next_render();
}
});
Effect { rc }
})
}
/// A handle to an effect.
#[derive(Clone, Copy)]
pub struct Effect {
rc: ReactiveContext,
}
impl Effect {
/// Marks the effect as dirty, causing it to rerun on the next render.
pub fn mark_dirty(&mut self) {
self.rc.mark_dirty();
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_waker.rs | packages/hooks/src/use_waker.rs | use dioxus_core::use_hook;
use dioxus_signals::{ReadableExt, Signal, WritableExt};
use futures_channel::oneshot::{Canceled, Receiver, Sender};
use futures_util::{future::Shared, FutureExt};
/// A hook that provides a waker for other hooks to provide async/await capabilities.
///
/// This hook is a reactive wrapper over the `Shared<T>` future from the `futures` crate.
/// It allows multiple awaiters to wait on the same value, similar to a broadcast channel from Tokio.
///
/// Calling `.await` on the waker will consume the waker, so you'll need to call `.wait()` on the
/// source to get a new waker.
pub fn use_waker<T: Clone + 'static>() -> UseWaker<T> {
// We use a oneshot channel to send the value to the awaiter.
// The shared future allows multiple awaiters to wait on the same value.
let (task_tx, task_rx) = use_hook(|| {
let (tx, rx) = futures_channel::oneshot::channel::<T>();
let shared = rx.shared();
(Signal::new(tx), Signal::new(shared))
});
UseWaker { task_tx, task_rx }
}
#[derive(Debug)]
pub struct UseWaker<T: 'static> {
task_tx: Signal<Sender<T>>,
task_rx: Signal<Shared<Receiver<T>>>,
}
impl<T: Clone + 'static> UseWaker<T> {
/// Wake the current task with the provided value.
/// All awaiters will receive a clone of the value.
pub fn wake(&mut self, value: T) {
// We ignore the error because it means the task has already been woken.
let (tx, rx) = futures_channel::oneshot::channel::<T>();
let shared = rx.shared();
// Swap out the old sender and receiver with the new ones.
let tx = self.task_tx.replace(tx);
let _rx = self.task_rx.replace(shared);
// And then send out the oneshot value, waking up all awaiters.
let _ = tx.send(value);
}
/// Returns a future that resolves when the task is woken.
pub async fn wait(&self) -> Result<T, Canceled> {
self.task_rx.cloned().await
}
}
// Can await the waker to be woken.
// We use `.peek()` here to avoid reacting to changes in the underlying task_rx which could lead
// to an effect/future loop.
impl<T: Clone + 'static> std::future::Future for UseWaker<T> {
type Output = Result<T, Canceled>;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
self.task_rx.peek().clone().poll_unpin(cx)
}
}
impl<T> Copy for UseWaker<T> {}
impl<T> Clone for UseWaker<T> {
fn clone(&self) -> Self {
*self
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_callback.rs | packages/hooks/src/use_callback.rs | use dioxus_core::{use_hook, Callback};
/// Create a callback that's always up to date. Whenever this hook is called the inner callback will be replaced with the new callback but the handle will remain.
///
/// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
///
/// This API is in flux and might not remain.
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_callback<T: 'static, O: 'static>(f: impl FnMut(T) -> O + 'static) -> Callback<T, O> {
let mut callback = Some(f);
// Create a copyvalue with no contents
// This copyvalue is generic over F so that it can be sized properly
let mut inner = use_hook(|| {
Callback::new(
callback
.take()
.expect("Callback cannot be None on first call"),
)
});
if let Some(callback) = callback.take() {
// Every time this hook is called replace the inner callback with the new callback
inner.replace(Box::new(callback));
}
inner
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_action.rs | packages/hooks/src/use_action.rs | use crate::{use_callback, use_signal};
use dioxus_core::{use_hook, Callback, CapturedError, Result, Task};
use dioxus_signals::{ReadSignal, ReadableBoxExt, ReadableExt, Signal, WritableExt};
use futures_channel::oneshot::Receiver;
use futures_util::{future::Shared, FutureExt};
use std::{marker::PhantomData, pin::Pin, prelude::rust_2024::Future, task::Poll};
pub fn use_action<E, C, M>(mut user_fn: C) -> Action<C::Input, C::Output>
where
E: Into<CapturedError> + 'static,
C: ActionCallback<M, E>,
M: 'static,
C::Input: 'static,
C::Output: 'static,
C: 'static,
{
let mut value = use_signal(|| None as Option<C::Output>);
let mut error = use_signal(|| None as Option<CapturedError>);
let mut task = use_signal(|| None as Option<Task>);
let mut state = use_signal(|| ActionState::Unset);
let callback = use_callback(move |input: C::Input| {
// Cancel any existing task
if let Some(task) = task.take() {
task.cancel();
}
let (tx, rx) = futures_channel::oneshot::channel();
let rx = rx.shared();
// Spawn a new task, and *then* fire off the async
let result = user_fn.call(input);
let new_task = dioxus_core::spawn(async move {
// Set the state to pending
state.set(ActionState::Pending);
// Create a new task
let result = result.await;
match result {
Ok(res) => {
error.set(None);
value.set(Some(res));
state.set(ActionState::Ready);
}
Err(err) => {
error.set(Some(err.into()));
value.set(None);
state.set(ActionState::Errored);
}
}
tx.send(()).ok();
});
task.set(Some(new_task));
rx
});
// Create a reader that maps the Option<T> to T, unwrapping the Option
// This should only be handed out if we know the value is Some. We never set the value back to None, only modify the state of the action
let reader = use_hook(|| value.boxed().map(|v| v.as_ref().unwrap()).boxed());
Action {
value,
error,
task,
callback,
reader,
_phantom: PhantomData,
state,
}
}
pub struct Action<I, T: 'static> {
reader: ReadSignal<T>,
error: Signal<Option<CapturedError>>,
value: Signal<Option<T>>,
task: Signal<Option<Task>>,
callback: Callback<I, Shared<Receiver<()>>>,
state: Signal<ActionState>,
_phantom: PhantomData<*const I>,
}
impl<I: 'static, O: 'static> Action<I, O> {
pub fn value(&self) -> Option<Result<ReadSignal<O>, CapturedError>> {
if !matches!(
*self.state.read(),
ActionState::Ready | ActionState::Errored
) {
return None;
}
if let Some(err) = self.error.cloned() {
return Some(Err(err));
}
if self.value.read().is_none() {
return None;
}
Some(Ok(self.reader))
}
pub fn pending(&self) -> bool {
*self.state.read() == ActionState::Pending
}
/// Clear the current value and error, setting the state to Reset
pub fn reset(&mut self) {
self.state.set(ActionState::Reset);
if let Some(t) = self.task.take() {
t.cancel()
}
}
pub fn cancel(&mut self) {
if let Some(t) = self.task.take() {
t.cancel()
}
self.state.set(ActionState::Reset);
}
}
impl<I, T> std::fmt::Debug for Action<I, T>
where
T: std::fmt::Debug + 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
f.debug_struct("Action")
.field("state", &self.state.read())
.field("value", &self.value.read())
.field("error", &self.error.read())
.finish()
} else {
std::fmt::Debug::fmt(&self.value.read().as_ref(), f)
}
}
}
pub struct Dispatching<I> {
_phantom: PhantomData<*const I>,
receiver: Shared<Receiver<()>>,
}
impl<T> Dispatching<T> {
pub(crate) fn new(receiver: Shared<Receiver<()>>) -> Self {
Self {
_phantom: PhantomData,
receiver,
}
}
}
impl<T> std::future::Future for Dispatching<T> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
match self.receiver.poll_unpin(_cx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
impl<I, T> Copy for Action<I, T> {}
impl<I, T> Clone for Action<I, T> {
fn clone(&self) -> Self {
*self
}
}
/// The state of an action
///
/// We can never reset the state to Unset, only to Reset, otherwise the value reader would panic.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
enum ActionState {
Unset,
Pending,
Ready,
Errored,
Reset,
}
pub trait ActionCallback<M, E> {
type Input;
type Output;
fn call(
&mut self,
input: Self::Input,
) -> impl Future<Output = Result<Self::Output, E>> + 'static;
}
impl<F, O, G, E> ActionCallback<(O,), E> for F
where
F: FnMut() -> G,
G: Future<Output = Result<O, E>> + 'static,
{
type Input = ();
type Output = O;
fn call(
&mut self,
_input: Self::Input,
) -> impl Future<Output = Result<Self::Output, E>> + 'static {
(self)()
}
}
impl<F, O, A, G, E> ActionCallback<(A, O), E> for F
where
F: FnMut(A) -> G,
G: Future<Output = Result<O, E>> + 'static,
{
type Input = (A,);
type Output = O;
fn call(
&mut self,
input: Self::Input,
) -> impl Future<Output = Result<Self::Output, E>> + 'static {
let (a,) = input;
(self)(a)
}
}
impl<O, A, B, F, G, E> ActionCallback<(A, B, O), E> for F
where
F: FnMut(A, B) -> G,
G: Future<Output = Result<O, E>> + 'static,
{
type Input = (A, B);
type Output = O;
fn call(
&mut self,
input: Self::Input,
) -> impl Future<Output = Result<Self::Output, E>> + 'static {
let (a, b) = input;
(self)(a, b)
}
}
impl<O, A, B, C, F, G, E> ActionCallback<(A, B, C, O), E> for F
where
F: FnMut(A, B, C) -> G,
G: Future<Output = Result<O, E>> + 'static,
{
type Input = (A, B, C);
type Output = O;
fn call(
&mut self,
input: Self::Input,
) -> impl Future<Output = Result<Self::Output, E>> + 'static {
let (a, b, c) = input;
(self)(a, b, c)
}
}
impl<O> Action<(), O> {
pub fn call(&mut self) -> Dispatching<()> {
Dispatching::new((self.callback).call(()))
}
}
impl<A: 'static, O> Action<(A,), O> {
pub fn call(&mut self, _a: A) -> Dispatching<()> {
Dispatching::new((self.callback).call((_a,)))
}
}
impl<A: 'static, B: 'static, O> Action<(A, B), O> {
pub fn call(&mut self, _a: A, _b: B) -> Dispatching<()> {
Dispatching::new((self.callback).call((_a, _b)))
}
}
impl<A: 'static, B: 'static, C: 'static, O> Action<(A, B, C), O> {
pub fn call(&mut self, _a: A, _b: B, _c: C) -> Dispatching<()> {
Dispatching::new((self.callback).call((_a, _b, _c)))
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_signal.rs | packages/hooks/src/use_signal.rs | use dioxus_core::use_hook;
use dioxus_signals::{Signal, SignalData, Storage, SyncStorage, UnsyncStorage};
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_signals::*;
///
/// fn App() -> Element {
/// let mut count = use_signal(|| 0);
///
/// // Because signals have automatic dependency tracking, if you never read them in a component, that component will not be re-rended when the signal is updated.
/// // The app component will never be rerendered in this example.
/// rsx! { Child { state: count } }
/// }
///
/// #[component]
/// fn Child(state: Signal<u32>) -> Element {
/// use_future(move || async move {
/// // Because the signal is a Copy type, we can use it in an async block without cloning it.
/// *state.write() += 1;
/// });
///
/// rsx! {
/// button {
/// onclick: move |_| *state.write() += 1,
/// "{state}"
/// }
/// }
/// }
/// ```
///
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_state")]
#[track_caller]
#[must_use]
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage> {
use_maybe_signal_sync(f)
}
/// Creates a new `Send + Sync`` Signal. Signals are a Copy state management solution with automatic dependency tracking.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_signals::*;
///
/// fn App() -> Element {
/// let mut count = use_signal_sync(|| 0);
///
/// // Because signals have automatic dependency tracking, if you never read them in a component, that component will not be re-rended when the signal is updated.
/// // The app component will never be rerendered in this example.
/// rsx! { Child { state: count } }
/// }
///
/// #[component]
/// fn Child(state: Signal<u32, SyncStorage>) -> Element {
/// use_future(move || async move {
/// // This signal is Send + Sync, so we can use it in an another thread
/// tokio::spawn(async move {
/// // Because the signal is a Copy type, we can use it in an async block without cloning it.
/// *state.write() += 1;
/// }).await;
/// });
///
/// rsx! {
/// button {
/// onclick: move |_| *state.write() += 1,
/// "{state}"
/// }
/// }
/// }
/// ```
#[doc(alias = "use_rw")]
#[must_use]
#[track_caller]
pub fn use_signal_sync<T: Send + Sync + 'static>(f: impl FnOnce() -> T) -> Signal<T, SyncStorage> {
use_maybe_signal_sync(f)
}
#[must_use]
#[track_caller]
fn use_maybe_signal_sync<T: 'static, U: Storage<SignalData<T>>>(
f: impl FnOnce() -> T,
) -> Signal<T, U> {
let caller = std::panic::Location::caller();
// todo: (jon)
// By default, we want to unsubscribe the current component from the signal on every render
// any calls to .read() in the body will re-subscribe the component to the signal
// use_before_render(move || signal.unsubscribe(current_scope_id().unwrap()));
use_hook(|| Signal::new_with_caller(f(), caller))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/lib.rs | packages/hooks/src/lib.rs | #![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")]
#[macro_export]
/// A helper macro for cloning multiple values at once
///
/// # Usage
///
///
/// ```
/// # use dioxus::prelude::*;
/// #
/// # #[derive(Props, PartialEq, Clone)]
/// # struct Props {
/// # prop: String,
/// # }
/// # fn Component(props: Props) -> Element {
///
/// let (data) = use_signal(|| {});
///
/// let handle_thing = move |_| {
/// to_owned![data, props.prop];
/// spawn(async move {
/// // do stuff
/// });
/// };
/// # handle_thing(());
/// # VNode::empty() }
/// ```
macro_rules! to_owned {
// Rule matching simple symbols without a path
($es:ident $(, $($rest:tt)*)?) => {
#[allow(unused_mut)]
let mut $es = $es.to_owned();
$( to_owned![$($rest)*] )?
};
// We need to find the last element in a path, for this we need to unstack the path part by
// part using, separating what we have with a '@'
($($deref:ident).* $(, $($rest:tt)*)?) => {
to_owned![@ $($deref).* $(, $($rest)*)?]
};
// Take the head of the path and add it to the list of $deref
($($deref:ident)* @ $head:ident $( . $tail:ident)+ $(, $($rest:tt)*)?) => {
to_owned![$($deref)* $head @ $($tail).+ $(, $($rest)*)?]
};
// We have exhausted the path, use the last as a name
($($deref:ident)* @ $last:ident $(, $($rest:tt)*)? ) => {
#[allow(unused_mut)]
let mut $last = $($deref .)* $last .to_owned();
$(to_owned![$($rest)*])?
};
}
mod use_callback;
pub use use_callback::*;
mod use_on_destroy;
pub use use_on_destroy::*;
mod use_context;
pub use use_context::*;
mod use_coroutine;
pub use use_coroutine::*;
mod use_future;
pub use use_future::*;
mod use_reactive;
pub use use_reactive::*;
// mod use_sorted;
// pub use use_sorted::*;
mod use_resource;
pub use use_resource::*;
mod use_effect;
pub use use_effect::*;
mod use_memo;
pub use use_memo::*;
mod use_root_context;
pub use use_root_context::*;
mod use_hook_did_run;
pub use use_hook_did_run::*;
mod use_signal;
pub use use_signal::*;
mod use_set_compare;
pub use use_set_compare::*;
mod use_after_suspense_resolved;
pub use use_after_suspense_resolved::*;
mod use_action;
pub use use_action::*;
mod use_waker;
pub use use_waker::*;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_collection.rs | packages/hooks/src/use_collection.rs | /*
a form of use_signal explicitly for map-style collections (BTreeMap, HashMap, etc).
Why?
---
Traditionally, it's possible to use the "use_state" hook for collections in the React world.
Adding a new entry would look something similar to:
```js
let (map, set_map) = useState({});
set_map({ ...map, [key]: value });
```
The new value then causes the appropriate update when passed into children.
This is moderately efficient because the fields of the map are moved, but the data itself is not cloned.
However, if you used similar approach with Dioxus:
```rust
let (map, set_map) = use_signal(|| HashMap::new());
set_map({
let mut newmap = map.clone();
newmap.set(key, value);
newmap
})
```
Unfortunately, you'd be cloning the entire state every time a value is changed. The obvious solution is to
wrap every element in the HashMap with an Rc. That way, cloning the HashMap is on par with its JS equivalent.
Fortunately, we can make this operation even more efficient in Dioxus, leveraging the borrow rules of Rust.
This hook provides a memoized collection, memoized setters, and memoized getters. This particular hook is
extremely powerful for implementing lists and supporting core state management needs for small apps.
If you need something even more powerful, check out the dedicated atomic state management Dioxus Dataflow, which
uses the same memoization on top of the use_context API.
Here's a fully-functional todo app using the use_map API:
```rust
static TodoList: Component = |cx| {
let todos = use_map(|| HashMap::new());
let input = use_signal(|| None);
rsx! {
div {
button {
"Add todo"
onclick: move |_| {
let new_todo = TodoItem::new(input.contents());
todos.insert(new_todo.id.clone(), new_todo);
input.clear();
}
}
button {
"Clear todos"
onclick: move |_| todos.clear()
}
input {
placeholder: "What needs to be done?"
ref: input
}
ul {
{todos.iter().map(|todo| rsx!(
li {
key: todo.id
span { "{todo.content}" }
button {"x", onclick: move |_| todos.remove(todo.key.clone())}
}
))}
}
}
})
}
```
*/
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_reactive.rs | packages/hooks/src/use_reactive.rs | use dioxus_signals::{ReadableExt, WritableExt};
use crate::use_signal;
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`Dependency` is not implemented for `{Self}`",
label = "Dependency",
note = "Dependency is automatically implemented for all tuples with less than 8 references to element that implement `PartialEq` and `Clone`. For example, `(&A, &B, &C)` implements `Dependency` automatically as long as `A`, `B`, and `C` implement `PartialEq` and `Clone`.",
)
)]
pub trait Dependency: Sized + Clone {
/// The output of the dependency
type Out: Clone + PartialEq + 'static;
/// Returns the output of the dependency.
fn out(&self) -> Self::Out;
/// Returns true if the dependency has changed.
fn changed(&self, other: &Self::Out) -> bool {
self.out() != *other
}
}
impl Dependency for () {
type Out = ();
fn out(&self) -> Self::Out {}
}
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`DependencyElement` is not implemented for `{Self}`",
label = "dependency element",
note = "DependencyElement is automatically implemented for types that implement `PartialEq` and `Clone`",
)
)]
pub trait DependencyElement: 'static + PartialEq + Clone {}
impl<T> DependencyElement for T where T: 'static + PartialEq + Clone {}
impl<A: DependencyElement> Dependency for &A {
type Out = A;
fn out(&self) -> Self::Out {
(*self).clone()
}
}
macro_rules! impl_dep {
(
$($el:ident=$name:ident $other:ident,)*
) => {
impl< $($el),* > Dependency for ($(&$el,)*)
where
$(
$el: DependencyElement
),*
{
type Out = ($($el,)*);
fn out(&self) -> Self::Out {
let ($($name,)*) = self;
($((*$name).clone(),)*)
}
fn changed(&self, other: &Self::Out) -> bool {
let ($($name,)*) = self;
let ($($other,)*) = other;
$(
if *$name != $other {
return true;
}
)*
false
}
}
};
}
impl_dep!(A = a1 a2,);
impl_dep!(A = a1 a2, B = b1 b2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2,);
impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G = g1 g2, H = h1 h2,);
/// Takes some non-reactive data, and a closure and returns a closure that will subscribe to that non-reactive data as if it were reactive.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
///
/// let data = 5;
///
/// use_effect(use_reactive((&data,), |(data,)| {
/// println!("Data changed: {}", data);
/// }));
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_reactive<O, D: Dependency>(
non_reactive_data: D,
mut closure: impl FnMut(D::Out) -> O + 'static,
) -> impl FnMut() -> O + 'static {
let mut first_run = false;
let mut last_state = use_signal(|| {
first_run = true;
non_reactive_data.out()
});
if !first_run && non_reactive_data.changed(&*last_state.peek()) {
last_state.set(non_reactive_data.out())
}
move || closure(last_state())
}
/// A helper macro for `use_reactive` that merges uses the closure syntax to elaborate the dependency array
///
/// Takes some non-reactive data, and a closure and returns a closure that will subscribe to that non-reactive data as if it were reactive.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
///
/// let data = 5;
///
/// use_effect(use_reactive!(|data| {
/// println!("Data changed: {}", data);
/// }));
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[macro_export]
macro_rules! use_reactive {
(|| $($rest:tt)*) => { use_reactive( (), move |_| $($rest)* ) };
(| $($args:tt),* | $($rest:tt)*) => {
use_reactive(
($(&$args),*),
move |($($args),*)| $($rest)*
)
};
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_on_destroy.rs | packages/hooks/src/use_on_destroy.rs | use dioxus_core::use_drop;
#[deprecated(note = "Use `use_drop` instead, which has the same functionality.")]
pub fn use_on_unmount<D: FnOnce() + 'static>(destroy: D) {
use_drop(destroy);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_sorted.rs | packages/hooks/src/use_sorted.rs | use std::cmp::Ordering;
use std::ops::DerefMut;
use crate::use_memo;
use dioxus_signals::{ReadSignal, Signal};
pub fn use_sorted<V: 'static, T: PartialEq>(
collection: impl FnMut() -> Signal<V>,
) -> ReadSignal<Vec<T>>
// pub fn use_sorted<S, I, T>(iterable: impl FnMut() -> Signal<V>) -> ReadSignal<T>
// where
// S: Into<MaybeSignal<I>>,
// T: Ord,
// I: DerefMut<Target = [T]> + Clone + PartialEq,
{
use_memo(move || {
unimplemented!()
// let mut iterable = collection();
// iterable.sort();
// iterable
})
// let iterable = iterable.into();
// // use_memo(f)
// create_memo(move |_| {
// let mut iterable = iterable.get();
// iterable.sort();
// iterable
// })
// .into()
}
// /// Version of [`use_sorted`] with a compare function.
// pub fn use_sorted_by<S, I, T, F>(iterable: S, cmp_fn: F) -> Signal<I>
// where
// S: Into<MaybeSignal<I>>,
// I: DerefMut<Target = [T]> + Clone + PartialEq,
// F: FnMut(&T, &T) -> Ordering + Clone + 'static,
// {
// let iterable = iterable.into();
// create_memo(move |_| {
// let mut iterable = iterable.get();
// iterable.sort_by(cmp_fn.clone());
// iterable
// })
// .into()
// }
// /// Version of [`use_sorted`] by key.
// pub fn use_sorted_by_key<S, I, T, K, F>(iterable: S, key_fn: F) -> Signal<I>
// where
// S: Into<MaybeSignal<I>>,
// I: DerefMut<Target = [T]> + Clone + PartialEq,
// K: Ord,
// F: FnMut(&T) -> K + Clone + 'static,
// {
// let iterable = iterable.into();
// create_memo(move |_| {
// let mut iterable = iterable.get();
// iterable.sort_by_key(key_fn.clone());
// iterable
// })
// .into()
// }
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_hook_did_run.rs | packages/hooks/src/use_hook_did_run.rs | use dioxus_core::{use_after_render, use_before_render, use_hook};
use dioxus_signals::{CopyValue, WritableExt};
/// A utility lifecycle hook that is intended to be used inside other hooks to determine if the outer hook has ran this render.
/// The provided callback is executed after each render.
/// The value will only be true if the containing outer hook is executed.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_hook_did_run(mut handler: impl FnMut(bool) + 'static) {
let mut did_run_ = use_hook(|| CopyValue::new(false));
// Before render always set the value to false
use_before_render(move || did_run_.set(false));
// Only when the outer hook is run do we want to set the value to true
did_run_.set(true);
// After render, we can check if the outer hook was run
use_after_render(move || handler(did_run_()));
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_future.rs | packages/hooks/src/use_future.rs | #![allow(missing_docs)]
use crate::{use_callback, use_hook_did_run, use_signal};
use dioxus_core::{use_hook, Callback, Subscribers, Task};
use dioxus_signals::*;
use std::future::Future;
use std::ops::Deref;
/// A hook that allows you to spawn a future the first time you render a component.
///
///
/// This future will **not** run on the server. To run a future on the server, you should use [`dioxus_core::spawn_isomorphic`] directly.
///
///
/// `use_future` **won't return a value**. If you want to return a value from a future, use [`crate::use_resource()`] instead.
///
/// ## Example
///
/// ```rust
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn app() -> Element {
/// let mut count = use_signal(|| 0);
/// let mut running = use_signal(|| true);
/// // `use_future` will spawn an infinitely running future that can be started and stopped
/// use_future(move || async move {
/// loop {
/// if running() {
/// count += 1;
/// }
/// tokio::time::sleep(Duration::from_millis(400)).await;
/// }
/// });
/// rsx! {
/// div {
/// h1 { "Current count: {count}" }
/// button { onclick: move |_| running.toggle(), "Start/Stop the count"}
/// button { onclick: move |_| count.set(0), "Reset the count" }
/// }
/// }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_async")]
pub fn use_future<F>(mut future: impl FnMut() -> F + 'static) -> UseFuture
where
F: Future + 'static,
{
let mut state = use_signal(|| UseFutureState::Pending);
let callback = use_callback(move |_| {
let fut = future();
dioxus_core::spawn(async move {
state.set(UseFutureState::Pending);
fut.await;
state.set(UseFutureState::Ready);
})
});
// Create the task inside a CopyValue so we can reset it in-place later
let task = use_hook(|| CopyValue::new(callback(())));
// Early returns in dioxus have consequences for use_memo, use_resource, and use_future, etc
// We *don't* want futures to be running if the component early returns. It's a rather weird behavior to have
// use_memo running in the background even if the component isn't hitting those hooks anymore.
//
// React solves this by simply not having early returns interleave with hooks.
// However, since dioxus allows early returns (since we use them for suspense), we need to solve this problem
use_hook_did_run(move |did_run| match did_run {
true => task.peek().resume(),
false => task.peek().pause(),
});
UseFuture {
task,
state,
callback,
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct UseFuture {
task: CopyValue<Task>,
state: Signal<UseFutureState>,
callback: Callback<(), Task>,
}
/// A signal that represents the state of a future
// we might add more states (panicked, etc)
#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
pub enum UseFutureState {
/// The future is still running
Pending,
/// The future has been forcefully stopped
Stopped,
/// The future has been paused, tempoarily
Paused,
/// The future has completed
Ready,
}
impl UseFuture {
/// Restart the future with new dependencies.
///
/// Will not cancel the previous future, but will ignore any values that it
/// generates.
pub fn restart(&mut self) {
self.task.write().cancel();
let new_task = self.callback.call(());
self.task.set(new_task);
}
/// Forcefully cancel a future
pub fn cancel(&mut self) {
self.state.set(UseFutureState::Stopped);
self.task.write().cancel();
}
/// Pause the future
pub fn pause(&mut self) {
self.state.set(UseFutureState::Paused);
self.task.write().pause();
}
/// Resume the future
pub fn resume(&mut self) {
if self.finished() {
return;
}
self.state.set(UseFutureState::Pending);
self.task.write().resume();
}
/// Get a handle to the inner task backing this future
/// Modify the task through this handle will cause inconsistent state
pub fn task(&self) -> Task {
self.task.cloned()
}
/// Is the future currently finished running?
///
/// Reading this does not subscribe to the future's state
pub fn finished(&self) -> bool {
matches!(
*self.state.peek(),
UseFutureState::Ready | UseFutureState::Stopped
)
}
/// Get the current state of the future.
pub fn state(&self) -> ReadSignal<UseFutureState> {
self.state.into()
}
}
impl From<UseFuture> for ReadSignal<UseFutureState> {
fn from(val: UseFuture) -> Self {
val.state.into()
}
}
impl Readable for UseFuture {
type Target = UseFutureState;
type Storage = UnsyncStorage;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
self.state.try_read_unchecked()
}
#[track_caller]
fn try_peek_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
self.state.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers {
self.state.subscribers()
}
}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
impl Deref for UseFuture {
type Target = dyn Fn() -> UseFutureState;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_set_compare.rs | packages/hooks/src/use_set_compare.rs | use dioxus_core::use_hook;
use dioxus_signals::{ReadSignal, SetCompare};
use std::hash::Hash;
/// Creates a new SetCompare which efficiently tracks when a value changes to check if it is equal to a set of values.
///
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_memo()`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn App() -> Element {
/// let mut count = use_signal(|| 0);
/// let compare = use_set_compare(move || count());
///
/// rsx! {
/// for i in 0..10 {
/// // Child will only re-render when i == count
/// Child { compare, i }
/// }
/// button {
/// // This will only rerender the child with the old and new value of i == count
/// // Because we are using a set compare, this will be O(1) instead of the O(n) performance of a selector
/// onclick: move |_| count += 1,
/// "Increment"
/// }
/// }
/// }
///
/// #[component]
/// fn Child(i: usize, compare: SetCompare<usize>) -> Element {
/// let active = use_set_compare_equal(i, compare);
/// if active() {
/// rsx! { "Active" }
/// } else {
/// rsx! { "Inactive" }
/// }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_set_compare<R: Eq + Hash + 'static>(f: impl FnMut() -> R + 'static) -> SetCompare<R> {
use_hook(move || SetCompare::new(f))
}
/// A hook that returns true if the value is equal to the value in the set compare.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_set_compare_equal<R: Eq + Hash + 'static>(
value: R,
mut compare: SetCompare<R>,
) -> ReadSignal<bool> {
use_hook(move || compare.equal(value))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_after_suspense_resolved.rs | packages/hooks/src/use_after_suspense_resolved.rs | use dioxus_core::{use_hook, Runtime};
/// Run a closure after the suspense boundary this is under is resolved. The
/// closure will be run immediately if the suspense boundary is already resolved
/// or the scope is not under a suspense boundary.
pub fn use_after_suspense_resolved(suspense_resolved: impl FnOnce() + 'static) {
use_hook(|| {
// If this is under a suspense boundary, we need to check if it is resolved
match Runtime::current().suspense_context() {
Some(context) => {
// If it is suspended, run the closure after the suspense is resolved
context.after_suspense_resolved(suspense_resolved)
}
None => {
// Otherwise, just run the resolved closure immediately
suspense_resolved();
}
}
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_root_context.rs | packages/hooks/src/use_root_context.rs | use dioxus_core::{provide_root_context, try_consume_context, use_hook};
/// Try to get a value from the root of the virtual dom, if it doesn't exist, create a new one with the closure provided.
///
/// This is useful for global context inside of libraries. Instead of having the user provide context in the root of their app, you can use this hook to create a context at the root automatically.
///
/// # Example
/// ```rust
/// # #[derive(Clone)]
/// # struct Logger;
/// use dioxus::prelude::*;
///
/// fn use_logger() -> Logger {
/// // We want one logger per app in the root. Instead of forcing the user to always provide a logger, we can insert a default logger if one doesn't exist.
/// use_root_context(|| Logger)
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
use_hook(|| {
try_consume_context::<T>()
// If no context is provided, create a new one at the root
.unwrap_or_else(|| provide_root_context(new()))
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_coroutine.rs | packages/hooks/src/use_coroutine.rs | use crate::{use_context_provider, use_future, UseFuture};
use dioxus_core::Task;
use dioxus_core::{consume_context, use_hook};
use dioxus_signals::*;
pub use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
use std::future::Future;
/// Maintain a handle over a future that can be paused, resumed, and canceled.
///
/// This is an upgraded form of [`crate::use_future()`] with an integrated channel system.
/// Specifically, the coroutine generated here comes with an [`futures_channel::mpsc::UnboundedSender`]
/// built into it - saving you the hassle of building your own.
///
/// Additionally, coroutines are automatically injected as shared contexts, so
/// downstream components can tap into a coroutine's channel and send messages
/// into a singular async event loop.
///
/// This makes it effective for apps that need to interact with an event loop or
/// some asynchronous code without thinking too hard about state.
///
/// ## Global State
///
/// Typically, writing apps that handle concurrency properly can be difficult,
/// so the intention of this hook is to make it easy to join and poll async tasks
/// concurrently in a centralized place. You'll find that you can have much better
/// control over your app's state if you centralize your async actions, even under
/// the same concurrent context. This makes it easier to prevent undeseriable
/// states in your UI while various async tasks are already running.
///
/// This hook is especially powerful when combined with Fermi. We can store important
/// global data in a coroutine, and then access display-level values from the rest
/// of our app through atoms.
///
/// ## UseCallback instead
///
/// However, you must plan out your own concurrency and synchronization. If you
/// don't care about actions in your app being synchronized, you can use [`crate::use_callback()`]
/// hook to spawn multiple tasks and run them concurrently.
///
/// ### Notice
/// In order to use ``rx.next().await``, you will need to extend the ``Stream`` trait (used by ``UnboundedReceiver``)
/// by adding the ``futures-util`` crate as a dependency and adding ``StreamExt`` into scope via ``use futures_util::stream::StreamExt;``
///
/// ## Example
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// use futures_util::StreamExt;
/// enum Action {
/// Start,
/// Stop,
/// }
///
/// let chat_client = use_coroutine(|mut rx: UnboundedReceiver<Action>| async move {
/// while let Some(action) = rx.next().await {
/// match action {
/// Action::Start => {}
/// Action::Stop => {},
/// }
/// }
/// });
///
///
/// rsx! {
/// button {
/// onclick: move |_| chat_client.send(Action::Start),
/// "Start Chat Service"
/// }
/// };
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_coroutine<M, G, F>(mut init: G) -> Coroutine<M>
where
M: 'static,
G: FnMut(UnboundedReceiver<M>) -> F + 'static,
F: Future<Output = ()> + 'static,
{
let mut tx_copy_value = use_hook(|| CopyValue::new(None));
let future = use_future(move || {
let (tx, rx) = futures_channel::mpsc::unbounded();
tx_copy_value.set(Some(tx));
init(rx)
});
use_context_provider(|| Coroutine {
tx: tx_copy_value,
future,
})
}
/// Get a handle to a coroutine higher in the tree
/// Analogous to use_context_provider and use_context,
/// but used for coroutines specifically
/// See the docs for [`use_coroutine`] for more details.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[must_use]
pub fn use_coroutine_handle<M: 'static>() -> Coroutine<M> {
use_hook(consume_context::<Coroutine<M>>)
}
pub struct Coroutine<T: 'static> {
tx: CopyValue<Option<UnboundedSender<T>>>,
future: UseFuture,
}
impl<T> Coroutine<T> {
/// Get the underlying task handle
pub fn task(&self) -> Task {
self.future.task()
}
/// Send a message to the coroutine
pub fn send(&self, msg: T) {
let _ = self.tx.read().as_ref().unwrap().unbounded_send(msg);
}
pub fn tx(&self) -> UnboundedSender<T> {
self.tx.read().as_ref().unwrap().clone()
}
/// Restart this coroutine
pub fn restart(&mut self) {
self.future.restart();
}
}
// manual impl since deriving doesn't work with generics
impl<T> Copy for Coroutine<T> {}
impl<T> Clone for Coroutine<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> PartialEq for Coroutine<T> {
fn eq(&self, other: &Self) -> bool {
self.tx == other.tx && self.future == other.future
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_resource.rs | packages/hooks/src/use_resource.rs | #![allow(missing_docs)]
use crate::{use_callback, use_signal, use_waker, UseWaker};
use dioxus_core::{
spawn, use_hook, Callback, IntoAttributeValue, IntoDynNode, ReactiveContext, RenderError,
Subscribers, SuspendedFuture, Task,
};
use dioxus_signals::*;
use futures_util::{
future::{self},
pin_mut, FutureExt, StreamExt,
};
use std::{cell::Cell, future::Future, rc::Rc};
use std::{fmt::Debug, ops::Deref};
#[doc = include_str!("../docs/use_resource.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_async_memo")]
#[doc(alias = "use_memo_async")]
#[track_caller]
pub fn use_resource<T, F>(mut future: impl FnMut() -> F + 'static) -> Resource<T>
where
T: 'static,
F: Future<Output = T> + 'static,
{
let location = std::panic::Location::caller();
let mut value = use_signal(|| None);
let mut state = use_signal(|| UseResourceState::Pending);
let (rc, changed) = use_hook(|| {
let (rc, changed) = ReactiveContext::new_with_origin(location);
(rc, Rc::new(Cell::new(Some(changed))))
});
let mut waker = use_waker::<()>();
let cb = use_callback(move |_| {
// Set the state to Pending when the task is restarted
state.set(UseResourceState::Pending);
// Create the user's task
let fut = rc.reset_and_run_in(&mut future);
// Spawn a wrapper task that polls the inner future and watches its dependencies
spawn(async move {
// Move the future here and pin it so we can poll it
let fut = fut;
pin_mut!(fut);
// Run each poll in the context of the reactive scope
// This ensures the scope is properly subscribed to the future's dependencies
let res = future::poll_fn(|cx| {
rc.run_in(|| {
tracing::trace_span!("polling resource", location = %location)
.in_scope(|| fut.poll_unpin(cx))
})
})
.await;
// Set the value and state
state.set(UseResourceState::Ready);
value.set(Some(res));
// Notify that the value has changed
waker.wake(());
})
});
let mut task = use_hook(|| Signal::new(cb(())));
use_hook(|| {
let mut changed = changed.take().unwrap();
spawn(async move {
loop {
// Wait for the dependencies to change
let _ = changed.next().await;
// Stop the old task
task.write().cancel();
// Start a new task
task.set(cb(()));
}
})
});
Resource {
task,
value,
state,
waker,
callback: cb,
}
}
/// A handle to a reactive future spawned with [`use_resource`] that can be used to modify or read the result of the future.
///
/// ## Example
///
/// Reading the result of a resource:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // Since our resource may not be ready yet, the value is an Option. Our request may also fail, so the get function returns a Result
/// // The complete type we need to match is `Option<Result<String, reqwest::Error>>`
/// // We can use `read_unchecked` to keep our matching code in one statement while avoiding a temporary variable error (this is still completely safe because dioxus checks the borrows at runtime)
/// match &*resource.read_unchecked() {
/// Some(Ok(value)) => rsx! { "{value:?}" },
/// Some(Err(err)) => rsx! { "Error: {err}" },
/// None => rsx! { "Loading..." },
/// }
/// }
/// ```
#[derive(Debug)]
pub struct Resource<T: 'static> {
waker: UseWaker<()>,
value: Signal<Option<T>>,
task: Signal<Task>,
state: Signal<UseResourceState>,
callback: Callback<(), Task>,
}
impl<T> PartialEq for Resource<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
&& self.state == other.state
&& self.task == other.task
&& self.callback == other.callback
}
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Resource<T> {}
/// A signal that represents the state of the resource
// we might add more states (panicked, etc)
#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
pub enum UseResourceState {
/// The resource's future is still running
Pending,
/// The resource's future has been forcefully stopped
Stopped,
/// The resource's future has been paused, tempoarily
Paused,
/// The resource's future has completed
Ready,
}
impl<T> Resource<T> {
/// Restart the resource's future.
///
/// This will cancel the current future and start a new one.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can get a signal with the value of the resource with the `value` method
/// onclick: move |_| resource.restart(),
/// "Restart resource"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn restart(&mut self) {
self.task.write().cancel();
let new_task = self.callback.call(());
self.task.set(new_task);
}
/// Forcefully cancel the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can cancel the resource before it finishes with the `cancel` method
/// onclick: move |_| resource.cancel(),
/// "Cancel resource"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn cancel(&mut self) {
self.state.set(UseResourceState::Stopped);
self.task.write().cancel();
}
/// Pause the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can pause the future with the `pause` method
/// onclick: move |_| resource.pause(),
/// "Pause"
/// }
/// button {
/// // And resume it with the `resume` method
/// onclick: move |_| resource.resume(),
/// "Resume"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn pause(&mut self) {
self.state.set(UseResourceState::Paused);
self.task.write().pause();
}
/// Resume the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can pause the future with the `pause` method
/// onclick: move |_| resource.pause(),
/// "Pause"
/// }
/// button {
/// // And resume it with the `resume` method
/// onclick: move |_| resource.resume(),
/// "Resume"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn resume(&mut self) {
if self.finished() {
return;
}
self.state.set(UseResourceState::Pending);
self.task.write().resume();
}
/// Clear the resource's value. This will just reset the value. It will not modify any running tasks.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We clear the value without modifying any running tasks with the `clear` method
/// onclick: move |_| resource.clear(),
/// "Clear"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn clear(&mut self) {
self.value.write().take();
}
/// Get a handle to the inner task backing this resource
/// Modify the task through this handle will cause inconsistent state
pub fn task(&self) -> Task {
self.task.cloned()
}
/// Is the resource's future currently running?
pub fn pending(&self) -> bool {
matches!(*self.state.peek(), UseResourceState::Pending)
}
/// Is the resource's future currently finished running?
///
/// Reading this does not subscribe to the future's state
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can use the `finished` method to check if the future is finished
/// if resource.finished() {
/// rsx! {
/// "The resource is finished"
/// }
/// } else {
/// rsx! {
/// "The resource is still running"
/// }
/// }
/// }
/// ```
pub fn finished(&self) -> bool {
matches!(
*self.state.peek(),
UseResourceState::Ready | UseResourceState::Stopped
)
}
/// Get the current state of the resource's future. This method returns a [`ReadSignal`] which can be read to get the current state of the resource or passed to other hooks and components.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can read the current state of the future with the `state` method
/// match resource.state().cloned() {
/// UseResourceState::Pending => rsx! {
/// "The resource is still pending"
/// },
/// UseResourceState::Paused => rsx! {
/// "The resource has been paused"
/// },
/// UseResourceState::Stopped => rsx! {
/// "The resource has been stopped"
/// },
/// UseResourceState::Ready => rsx! {
/// "The resource is ready!"
/// },
/// }
/// }
/// ```
pub fn state(&self) -> ReadSignal<UseResourceState> {
self.state.into()
}
/// Get the current value of the resource's future. This method returns a [`ReadSignal`] which can be read to get the current value of the resource or passed to other hooks and components.
///
/// ## Example
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can get a signal with the value of the resource with the `value` method
/// let value = resource.value();
///
/// // Since our resource may not be ready yet, the value is an Option. Our request may also fail, so the get function returns a Result
/// // The complete type we need to match is `Option<Result<String, reqwest::Error>>`
/// // We can use `read_unchecked` to keep our matching code in one statement while avoiding a temporary variable error (this is still completely safe because dioxus checks the borrows at runtime)
/// match &*value.read_unchecked() {
/// Some(Ok(value)) => rsx! { "{value:?}" },
/// Some(Err(err)) => rsx! { "Error: {err}" },
/// None => rsx! { "Loading..." },
/// }
/// }
/// ```
pub fn value(&self) -> ReadSignal<Option<T>> {
self.value.into()
}
/// Suspend the resource's future and only continue rendering when the future is ready
pub fn suspend(&self) -> std::result::Result<MappedSignal<T, Signal<Option<T>>>, RenderError> {
match self.state.cloned() {
UseResourceState::Stopped | UseResourceState::Paused | UseResourceState::Pending => {
let task = self.task();
if task.paused() {
Ok(self.value.map(|v| v.as_ref().unwrap()))
} else {
Err(RenderError::Suspended(SuspendedFuture::new(task)))
}
}
_ => Ok(self.value.map(|v| v.as_ref().unwrap())),
}
}
}
impl<T, E> Resource<Result<T, E>> {
/// Convert the `Resource<Result<T, E>>` into an `Option<Result<MappedSignal<T>, MappedSignal<E>>>`
#[allow(clippy::type_complexity)]
pub fn result(
&self,
) -> Option<
Result<
MappedSignal<T, Signal<Option<Result<T, E>>>>,
MappedSignal<E, Signal<Option<Result<T, E>>>>,
>,
> {
let value: MappedSignal<T, Signal<Option<Result<T, E>>>> = self.value.map(|v| match v {
Some(Ok(ref res)) => res,
_ => panic!("Resource is not ready"),
});
let error: MappedSignal<E, Signal<Option<Result<T, E>>>> = self.value.map(|v| match v {
Some(Err(ref err)) => err,
_ => panic!("Resource is not ready"),
});
match &*self.value.peek() {
Some(Ok(_)) => Some(Ok(value)),
Some(Err(_)) => Some(Err(error)),
None => None,
}
}
}
impl<T> From<Resource<T>> for ReadSignal<Option<T>> {
fn from(val: Resource<T>) -> Self {
val.value.into()
}
}
impl<T> Readable for Resource<T> {
type Target = Option<T>;
type Storage = UnsyncStorage;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
self.value.try_read_unchecked()
}
#[track_caller]
fn try_peek_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
self.value.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers {
self.value.subscribers()
}
}
impl<T> Writable for Resource<T> {
type WriteMetadata = <Signal<Option<T>> as Writable>::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError>
where
Self::Target: 'static,
{
self.value.try_write_unchecked()
}
}
impl<T> IntoAttributeValue for Resource<T>
where
T: Clone + IntoAttributeValue,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<T> IntoDynNode for Resource<T>
where
T: Clone + IntoDynNode,
{
fn into_dyn_node(self) -> dioxus_core::DynamicNode {
self().into_dyn_node()
}
}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
impl<T: Clone> Deref for Resource<T> {
type Target = dyn Fn() -> Option<T>;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
impl<T> std::future::Future for Resource<T> {
type Output = ();
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
match self.waker.clone().poll_unpin(cx) {
std::task::Poll::Ready(_) => std::task::Poll::Ready(()),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_memo.rs | packages/hooks/src/use_memo.rs | use crate::use_callback;
use dioxus_core::use_hook;
use dioxus_signals::Memo;
#[doc = include_str!("../docs/derived_state.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[track_caller]
pub fn use_memo<R: PartialEq + 'static>(mut f: impl FnMut() -> R + 'static) -> Memo<R> {
let callback = use_callback(move |_| f());
let caller = std::panic::Location::caller();
#[allow(clippy::redundant_closure)]
use_hook(|| Memo::new_with_location(move || callback(()), caller))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/src/use_context.rs | packages/hooks/src/use_context.rs | use dioxus_core::{consume_context, provide_context, try_consume_context, use_hook};
/// Consume some context in the tree, providing a sharable handle to the value
///
/// Does not regenerate the value if the value is changed at the parent.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
use_hook(|| try_consume_context::<T>())
}
/// Consume some context in the tree, providing a sharable handle to the value
///
/// Does not regenerate the value if the value is changed at the parent.
/// ```rust
/// # use dioxus::prelude::*;
/// # #[derive(Clone, Copy, PartialEq, Debug)]
/// # enum Theme { Dark, Light }
/// fn Parent() -> Element {
/// use_context_provider(|| Theme::Dark);
/// rsx! { Child {} }
/// }
/// #[component]
/// fn Child() -> Element {
/// //gets context provided by parent element with use_context_provider
/// let user_theme = use_context::<Theme>();
/// rsx! { "user using dark mode: {user_theme == Theme::Dark}" }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_context<T: 'static + Clone>() -> T {
use_hook(|| consume_context::<T>())
}
/// Provide some context via the tree and return a reference to it
///
/// Once the context has been provided, it is immutable. Mutations should be done via interior mutability.
/// Context can be read by any child components of the context provider, and is a solution to prop
/// drilling, using a context provider with a Signal inside is a good way to provide global/shared
/// state in your app:
/// ```rust
/// # use dioxus::prelude::*;
///fn app() -> Element {
/// use_context_provider(|| Signal::new(0));
/// rsx! { Child {} }
///}
/// // This component does read from the signal, so when the signal changes it will rerun
///#[component]
///fn Child() -> Element {
/// let mut signal: Signal<i32> = use_context();
/// rsx! {
/// button { onclick: move |_| signal += 1, "increment context" }
/// p {"{signal}"}
/// }
///}
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_context_provider<T: 'static + Clone>(f: impl FnOnce() -> T) -> T {
use_hook(|| provide_context(f()))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/tests/effect.rs | packages/hooks/tests/effect.rs | #![allow(unused, non_upper_case_globals, non_snake_case)]
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
use dioxus::prelude::*;
use dioxus_core::ElementId;
use dioxus_signals::*;
#[tokio::test]
async fn effects_rerun() {
#[derive(Default)]
struct RunCounter {
component: usize,
effect: usize,
}
let counter = Rc::new(RefCell::new(RunCounter::default()));
let mut dom = VirtualDom::new_with_props(
|counter: Rc<RefCell<RunCounter>>| {
counter.borrow_mut().component += 1;
let mut signal = use_signal(|| 0);
use_effect({
to_owned![counter];
move || {
counter.borrow_mut().effect += 1;
// This will subscribe the effect to the signal
println!("Signal: {:?}", signal);
// Stop the wait for work manually
dioxus_core::needs_update();
}
});
signal += 1;
rsx! {
div {}
}
},
counter.clone(),
);
dom.rebuild_in_place();
tokio::select! {
_ = dom.wait_for_work() => {}
_ = tokio::time::sleep(Duration::from_millis(500)) => panic!("timed out")
};
let current_counter = counter.borrow();
assert_eq!(current_counter.component, 1);
assert_eq!(current_counter.effect, 1);
}
// https://github.com/DioxusLabs/dioxus/issues/2347
// Effects should rerun when the signal changes if there are no changes to the component
#[tokio::test]
async fn effects_rerun_without_rerender() {
#[derive(Default)]
struct RunCounter {
component: usize,
effect: usize,
}
let counter = Rc::new(RefCell::new(RunCounter::default()));
let mut dom = VirtualDom::new_with_props(
|counter: Rc<RefCell<RunCounter>>| {
counter.borrow_mut().component += 1;
println!("component {}", counter.borrow().component);
let mut signal = use_signal(|| 0);
use_effect({
to_owned![counter];
move || {
counter.borrow_mut().effect += 1;
// This will subscribe the effect to the signal
println!("Signal: {}", signal);
}
});
use_future(move || async move {
for i in 0..10 {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
println!("future {}", i);
signal += 1;
}
});
rsx! {
div {}
}
},
counter.clone(),
);
dom.rebuild_in_place();
tokio::select! {
_ = dom.wait_for_work() => {}
_ = tokio::time::sleep(Duration::from_millis(500)) => {}
};
let current_counter = counter.borrow();
assert_eq!(current_counter.component, 1);
assert_eq!(current_counter.effect, 11);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/hooks/tests/memo.rs | packages/hooks/tests/memo.rs | use dioxus_core::generation;
#[tokio::test]
async fn memo_updates() {
use std::cell::RefCell;
use dioxus::prelude::*;
thread_local! {
static VEC_SIGNAL: RefCell<Option<Signal<Vec<usize>, SyncStorage>>> = const { RefCell::new(None) };
}
fn app() -> Element {
let mut vec = use_signal_sync(|| vec![0, 1, 2]);
// Signals should update if they are changed from another thread
use_hook(|| {
VEC_SIGNAL.with(|cell| {
*cell.borrow_mut() = Some(vec);
});
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
vec.push(5);
});
});
let len = vec.len();
let len_memo = use_memo(move || vec.len());
// Make sure memos that update in the middle of a component work
if generation() < 2 {
vec.push(len);
}
// The memo should always be up to date
assert_eq!(vec.len(), len_memo());
rsx! {
for i in 0..len {
Child { index: i, vec }
}
}
}
#[component]
fn Child(index: usize, vec: Signal<Vec<usize>, SyncStorage>) -> Element {
// This memo should not rerun after the element is removed
let item = use_memo(move || vec.read()[index]);
rsx! {
div { "Item: {item}" }
}
}
let race = async move {
let mut dom = VirtualDom::new(app);
dom.rebuild_in_place();
let mut signal = VEC_SIGNAL.with(|cell| (*cell.borrow()).unwrap());
// Wait for the signal to update
for _ in 0..2 {
dom.wait_for_work().await;
dom.render_immediate(&mut dioxus::dioxus_core::NoOpMutations);
}
assert_eq!(signal(), vec![0, 1, 2, 3, 4, 5]);
// Remove each element from the vec
for _ in 0..6 {
signal.pop();
dom.wait_for_work().await;
dom.render_immediate(&mut dioxus::dioxus_core::NoOpMutations);
println!("Signal: {signal:?}");
}
};
tokio::select! {
_ = race => {},
_ = tokio::time::sleep(std::time::Duration::from_millis(1000)) => panic!("timed out")
};
}
#[tokio::test]
async fn use_memo_only_triggers_one_update() {
use dioxus::prelude::*;
use std::cell::RefCell;
thread_local! {
static VEC_SIGNAL: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };
}
fn app() -> Element {
let mut count = use_signal(|| 0);
let memorized = use_memo(move || dbg!(count() * 2));
use_memo(move || {
println!("reading doubled");
let doubled = memorized();
VEC_SIGNAL.with_borrow_mut(|v| v.push(doubled))
});
// Writing to count many times in a row should not cause the memo to update other subscribers multiple times
use_hook(move || {
for _ in 0..10 {
count += 1;
// Reading the memo each time will trigger the memo to rerun immediately, but the VEC_SIGNAL should still only rerun once
println!("doubled {memorized}");
}
});
rsx! {}
}
let mut dom = VirtualDom::new(app);
dom.rebuild_in_place();
tokio::select! {
_ = dom.wait_for_work() => {},
_ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {}
};
dom.render_immediate(&mut dioxus::dioxus_core::NoOpMutations);
assert_eq!(VEC_SIGNAL.with(|v| v.borrow().clone()), vec![0, 20]);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/depinfo/src/lib.rs | packages/depinfo/src/lib.rs | //! Parse the output of rustc's `.d` dep-info file.
//!
//! Used by the hot-reloading engine and other libraries to provide higher quality dependency analysis
//! for the user's project.
use std::path::{Path, PathBuf};
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum DepInfoParseError {
/// The input was malformed - maybe this `.d` format is no longer supported?
#[error("Malformed input")]
MalformedInput,
/// An env var could not be escaped or parsed - this might be a bug in rustc.
#[error("Failed to parse env var name")]
InvalidEnvVarName,
}
#[non_exhaustive]
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct RustcDepInfo {
/// The list of files that the main target in the dep-info file depends on.
pub files: Vec<PathBuf>,
/// The list of environment variables we found that the rustc compilation
/// depends on.
///
/// The first element of the pair is the name of the env var and the second
/// item is the value. `Some` means that the env var was set, and `None`
/// means that the env var wasn't actually set and the compilation depends
/// on it not being set.
pub env: Vec<(String, Option<String>)>,
}
impl std::str::FromStr for RustcDepInfo {
type Err = DepInfoParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
impl RustcDepInfo {
pub fn from_file(path: &Path) -> Result<RustcDepInfo, DepInfoParseError> {
let contents =
std::fs::read_to_string(path).map_err(|_| DepInfoParseError::MalformedInput)?;
RustcDepInfo::new(&contents)
}
/// Parse the `.d` dep-info file generated by rustc.
pub fn new(contents: &str) -> Result<RustcDepInfo, DepInfoParseError> {
let mut ret = RustcDepInfo::default();
let mut found_deps = false;
for line in contents.lines() {
if let Some(rest) = line.strip_prefix("# env-dep:") {
let mut parts = rest.splitn(2, '=');
let env_var = match parts.next() {
Some(s) => s,
None => continue,
};
let env_val = match parts.next() {
Some(s) => Some(unescape_env(s)?),
None => None,
};
ret.env.push((unescape_env(env_var)?, env_val));
} else if let Some(pos) = line.find(": ") {
if found_deps {
continue;
}
found_deps = true;
let mut deps = line[pos + 2..].split_whitespace();
while let Some(s) = deps.next() {
let mut file = s.to_string();
while file.ends_with('\\') {
file.pop();
file.push(' ');
file.push_str(deps.next().ok_or(DepInfoParseError::MalformedInput)?);
}
ret.files.push(file.into());
}
}
}
return Ok(ret);
// rustc tries to fit env var names and values all on a single line, which
// means it needs to escape `\r` and `\n`. The escape syntax used is "\n"
// which means that `\` also needs to be escaped.
fn unescape_env(s: &str) -> Result<String, DepInfoParseError> {
let mut ret = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c != '\\' {
ret.push(c);
continue;
}
match chars.next() {
Some('\\') => ret.push('\\'),
Some('n') => ret.push('\n'),
Some('r') => ret.push('\r'),
Some(_) => return Err(DepInfoParseError::InvalidEnvVarName),
None => return Err(DepInfoParseError::InvalidEnvVarName),
}
}
Ok(ret)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_from_path() {
let contents = include_str!("./dx.d");
let info: RustcDepInfo = contents.parse().unwrap();
let answer = vec![
"/dioxus/packages/autofmt/README.md",
"/dioxus/packages/autofmt/src/buffer.rs",
"/dioxus/packages/autofmt/src/collect_macros.rs",
"/dioxus/packages/autofmt/src/indent.rs",
"/dioxus/packages/autofmt/src/lib.rs",
"/dioxus/packages/autofmt/src/prettier_please.rs",
"/dioxus/packages/autofmt/src/writer.rs",
"/dioxus/packages/check/README.md",
"/dioxus/packages/check/src/check.rs",
"/dioxus/packages/check/src/issues.rs",
"/dioxus/packages/check/src/lib.rs",
"/dioxus/packages/check/src/metadata.rs",
"/dioxus/packages/cli/README.md",
"/dioxus/packages/cli/assets/android/MainActivity.kt.hbs",
"/dioxus/packages/cli/assets/android/gen/app/build.gradle.kts.hbs",
"/dioxus/packages/cli/assets/android/gen/app/proguard-rules.pro",
"/dioxus/packages/cli/assets/android/gen/app/src/main/AndroidManifest.xml.hbs",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/drawable/ic_launcher_background.xml",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/drawable-v24/ic_launcher_foreground.xml",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-hdpi/ic_launcher.webp",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-mdpi/ic_launcher.webp",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-xhdpi/ic_launcher.webp",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/values/colors.xml",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/values/strings.xml.hbs",
"/dioxus/packages/cli/assets/android/gen/app/src/main/res/values/styles.xml",
"/dioxus/packages/cli/assets/android/gen/build.gradle.kts",
"/dioxus/packages/cli/assets/android/gen/gradle/wrapper/gradle-wrapper.jar",
"/dioxus/packages/cli/assets/android/gen/gradle/wrapper/gradle-wrapper.properties",
"/dioxus/packages/cli/assets/android/gen/gradle.properties",
"/dioxus/packages/cli/assets/android/gen/gradlew",
"/dioxus/packages/cli/assets/android/gen/gradlew.bat",
"/dioxus/packages/cli/assets/android/gen/settings.gradle",
"/dioxus/packages/cli/assets/dioxus.toml",
"/dioxus/packages/cli/assets/ios/ios.plist.hbs",
"/dioxus/packages/cli/assets/macos/mac.plist.hbs",
"/dioxus/packages/cli/assets/web/index.html",
"/dioxus/packages/cli/assets/web/loading.html",
"/dioxus/packages/cli/assets/web/toast.html",
"/dioxus/packages/cli/build.rs",
"/dioxus/packages/cli/src/build/builder.rs",
"/dioxus/packages/cli/src/build/bundle.rs",
"/dioxus/packages/cli/src/build/mod.rs",
"/dioxus/packages/cli/src/build/prerender.rs",
"/dioxus/packages/cli/src/build/progress.rs",
"/dioxus/packages/cli/src/build/request.rs",
"/dioxus/packages/cli/src/build/templates.rs",
"/dioxus/packages/cli/src/build/verify.rs",
"/dioxus/packages/cli/src/build/web.rs",
"/dioxus/packages/cli/src/bundle_utils.rs",
"/dioxus/packages/cli/src/cli/autoformat.rs",
"/dioxus/packages/cli/src/cli/build.rs",
"/dioxus/packages/cli/src/cli/bundle.rs",
"/dioxus/packages/cli/src/cli/check.rs",
"/dioxus/packages/cli/src/cli/clean.rs",
"/dioxus/packages/cli/src/cli/config.rs",
"/dioxus/packages/cli/src/cli/create.rs",
"/dioxus/packages/cli/src/cli/init.rs",
"/dioxus/packages/cli/src/cli/link.rs",
"/dioxus/packages/cli/src/cli/mod.rs",
"/dioxus/packages/cli/src/cli/run.rs",
"/dioxus/packages/cli/src/cli/serve.rs",
"/dioxus/packages/cli/src/cli/target.rs",
"/dioxus/packages/cli/src/cli/translate.rs",
"/dioxus/packages/cli/src/cli/verbosity.rs",
"/dioxus/packages/cli/src/config/app.rs",
"/dioxus/packages/cli/src/config/bundle.rs",
"/dioxus/packages/cli/src/config/desktop.rs",
"/dioxus/packages/cli/src/config/dioxus_config.rs",
"/dioxus/packages/cli/src/config/serve.rs",
"/dioxus/packages/cli/src/config/web.rs",
"/dioxus/packages/cli/src/config.rs",
"/dioxus/packages/cli/src/dioxus_crate.rs",
"/dioxus/packages/cli/src/dx_build_info.rs",
"/dioxus/packages/cli/src/error.rs",
"/dioxus/packages/cli/src/fastfs.rs",
"/dioxus/packages/cli/src/filemap.rs",
"/dioxus/packages/cli/src/logging.rs",
"/dioxus/packages/cli/src/main.rs",
"/dioxus/packages/cli/src/metadata.rs",
"/dioxus/packages/cli/src/platform.rs",
"/dioxus/packages/cli/src/rustc.rs",
"/dioxus/packages/cli/src/serve/ansi_buffer.rs",
"/dioxus/packages/cli/src/serve/detect.rs",
"/dioxus/packages/cli/src/serve/handle.rs",
"/dioxus/packages/cli/src/serve/mod.rs",
"/dioxus/packages/cli/src/serve/output.rs",
"/dioxus/packages/cli/src/serve/proxy.rs",
"/dioxus/packages/cli/src/serve/runner.rs",
"/dioxus/packages/cli/src/serve/server.rs",
"/dioxus/packages/cli/src/serve/update.rs",
"/dioxus/packages/cli/src/serve/watcher.rs",
"/dioxus/packages/cli/src/settings.rs",
"/dioxus/packages/cli/src/wasm_bindgen.rs",
"/dioxus/packages/cli-config/src/lib.rs",
"/dioxus/packages/cli-opt/src/css.rs",
"/dioxus/packages/cli-opt/src/file.rs",
"/dioxus/packages/cli-opt/src/folder.rs",
"/dioxus/packages/cli-opt/src/image/jpg.rs",
"/dioxus/packages/cli-opt/src/image/mod.rs",
"/dioxus/packages/cli-opt/src/image/png.rs",
"/dioxus/packages/cli-opt/src/js.rs",
"/dioxus/packages/cli-opt/src/json.rs",
"/dioxus/packages/cli-opt/src/lib.rs",
"/dioxus/packages/config-macro/README.md",
"/dioxus/packages/config-macro/src/lib.rs",
"/dioxus/packages/const-serialize/README.md",
"/dioxus/packages/const-serialize/src/const_buffers.rs",
"/dioxus/packages/const-serialize/src/const_vec.rs",
"/dioxus/packages/const-serialize/src/lib.rs",
"/dioxus/packages/const-serialize-macro/src/lib.rs",
"/dioxus/packages/core/README.md",
"/dioxus/packages/core/docs/common_spawn_errors.md",
"/dioxus/packages/core/docs/reactivity.md",
"/dioxus/packages/core/src/any_props.rs",
"/dioxus/packages/core/src/arena.rs",
"/dioxus/packages/core/src/diff/component.rs",
"/dioxus/packages/core/src/diff/iterator.rs",
"/dioxus/packages/core/src/diff/mod.rs",
"/dioxus/packages/core/src/diff/node.rs",
"/dioxus/packages/core/src/effect.rs",
"/dioxus/packages/core/src/error_boundary.rs",
"/dioxus/packages/core/src/events.rs",
"/dioxus/packages/core/src/fragment.rs",
"/dioxus/packages/core/src/generational_box.rs",
"/dioxus/packages/core/src/global_context.rs",
"/dioxus/packages/core/src/hotreload_utils.rs",
"/dioxus/packages/core/src/launch.rs",
"/dioxus/packages/core/src/lib.rs",
"/dioxus/packages/core/src/mutations.rs",
"/dioxus/packages/core/src/nodes.rs",
"/dioxus/packages/core/src/properties.rs",
"/dioxus/packages/core/src/reactive_context.rs",
"/dioxus/packages/core/src/render_error.rs",
"/dioxus/packages/core/src/root_wrapper.rs",
"/dioxus/packages/core/src/runtime.rs",
"/dioxus/packages/core/src/scheduler.rs",
"/dioxus/packages/core/src/scope_arena.rs",
"/dioxus/packages/core/src/scope_context.rs",
"/dioxus/packages/core/src/scopes.rs",
"/dioxus/packages/core/src/suspense/component.rs",
"/dioxus/packages/core/src/suspense/mod.rs",
"/dioxus/packages/core/src/tasks.rs",
"/dioxus/packages/core/src/virtual_dom.rs",
"/dioxus/packages/core-macro/README.md",
"/dioxus/packages/core-macro/docs/component.md",
"/dioxus/packages/core-macro/docs/props.md",
"/dioxus/packages/core-macro/docs/rsx.md",
"/dioxus/packages/core-macro/src/component.rs",
"/dioxus/packages/core-macro/src/lib.rs",
"/dioxus/packages/core-macro/src/props/mod.rs",
"/dioxus/packages/core-macro/src/utils.rs",
"/dioxus/packages/core-types/src/bubbles.rs",
"/dioxus/packages/core-types/src/bundled.rs",
"/dioxus/packages/core-types/src/formatter.rs",
"/dioxus/packages/core-types/src/hr_context.rs",
"/dioxus/packages/core-types/src/lib.rs",
"/dioxus/packages/devtools/src/lib.rs",
"/dioxus/packages/devtools-types/src/lib.rs",
"/dioxus/packages/dioxus-lib/README.md",
"/dioxus/packages/dioxus-lib/src/lib.rs",
"/dioxus/packages/document/build.rs",
"/dioxus/packages/document/docs/eval.md",
"/dioxus/packages/document/docs/head.md",
"/dioxus/packages/document/src/document.rs",
"/dioxus/packages/document/src/elements/link.rs",
"/dioxus/packages/document/src/elements/meta.rs",
"/dioxus/packages/document/src/elements/mod.rs",
"/dioxus/packages/document/src/elements/script.rs",
"/dioxus/packages/document/src/elements/style.rs",
"/dioxus/packages/document/src/elements/stylesheet.rs",
"/dioxus/packages/document/src/elements/title.rs",
"/dioxus/packages/document/src/error.rs",
"/dioxus/packages/document/src/eval.rs",
"/dioxus/packages/document/src/js/head.js",
"/dioxus/packages/document/src/lib.rs",
"/dioxus/packages/document/./src/ts/eval.ts",
"/dioxus/packages/document/./src/ts/head.ts",
"/dioxus/packages/dx-wire-format/src/lib.rs",
"/dioxus/packages/fullstack/README.md",
"/dioxus/packages/fullstack/src/document/mod.rs",
"/dioxus/packages/fullstack/src/hooks/mod.rs",
"/dioxus/packages/fullstack/src/hooks/server_cached.rs",
"/dioxus/packages/fullstack/src/hooks/server_future.rs",
"/dioxus/packages/fullstack/src/html_storage/mod.rs",
"/dioxus/packages/fullstack/src/lib.rs",
"/dioxus/packages/generational-box/README.md",
"/dioxus/packages/generational-box/src/entry.rs",
"/dioxus/packages/generational-box/src/error.rs",
"/dioxus/packages/generational-box/src/lib.rs",
"/dioxus/packages/generational-box/src/references.rs",
"/dioxus/packages/generational-box/src/sync.rs",
"/dioxus/packages/generational-box/src/unsync.rs",
"/dioxus/packages/history/src/lib.rs",
"/dioxus/packages/history/src/memory.rs",
"/dioxus/packages/hooks/README.md",
"/dioxus/packages/hooks/docs/derived_state.md",
"/dioxus/packages/hooks/docs/moving_state_around.md",
"/dioxus/packages/hooks/docs/rules_of_hooks.md",
"/dioxus/packages/hooks/docs/side_effects.md",
"/dioxus/packages/hooks/docs/use_resource.md",
"/dioxus/packages/hooks/src/lib.rs",
"/dioxus/packages/hooks/src/use_callback.rs",
"/dioxus/packages/hooks/src/use_context.rs",
"/dioxus/packages/hooks/src/use_coroutine.rs",
"/dioxus/packages/hooks/src/use_effect.rs",
"/dioxus/packages/hooks/src/use_future.rs",
"/dioxus/packages/hooks/src/use_hook_did_run.rs",
"/dioxus/packages/hooks/src/use_memo.rs",
"/dioxus/packages/hooks/src/use_on_destroy.rs",
"/dioxus/packages/hooks/src/use_reactive.rs",
"/dioxus/packages/hooks/src/use_resource.rs",
"/dioxus/packages/hooks/src/use_root_context.rs",
"/dioxus/packages/hooks/src/use_set_compare.rs",
"/dioxus/packages/hooks/src/use_signal.rs",
"/dioxus/packages/html/README.md",
"/dioxus/packages/html/docs/common_event_handler_errors.md",
"/dioxus/packages/html/docs/event_handlers.md",
"/dioxus/packages/html/src/attribute_groups.rs",
"/dioxus/packages/html/src/elements.rs",
"/dioxus/packages/html/src/events/animation.rs",
"/dioxus/packages/html/src/events/clipboard.rs",
"/dioxus/packages/html/src/events/composition.rs",
"/dioxus/packages/html/src/events/drag.rs",
"/dioxus/packages/html/src/events/focus.rs",
"/dioxus/packages/html/src/events/form.rs",
"/dioxus/packages/html/src/events/image.rs",
"/dioxus/packages/html/src/events/keyboard.rs",
"/dioxus/packages/html/src/events/media.rs",
"/dioxus/packages/html/src/events/mod.rs",
"/dioxus/packages/html/src/events/mounted.rs",
"/dioxus/packages/html/src/events/mouse.rs",
"/dioxus/packages/html/src/events/pointer.rs",
"/dioxus/packages/html/src/events/resize.rs",
"/dioxus/packages/html/src/events/scroll.rs",
"/dioxus/packages/html/src/events/selection.rs",
"/dioxus/packages/html/src/events/toggle.rs",
"/dioxus/packages/html/src/events/touch.rs",
"/dioxus/packages/html/src/events/transition.rs",
"/dioxus/packages/html/src/events/visible.rs",
"/dioxus/packages/html/src/events/wheel.rs",
"/dioxus/packages/html/src/file_data.rs",
"/dioxus/packages/html/src/geometry.rs",
"/dioxus/packages/html/src/input_data.rs",
"/dioxus/packages/html/src/lib.rs",
"/dioxus/packages/html/src/point_interaction.rs",
"/dioxus/packages/html/src/render_template.rs",
"/dioxus/packages/html-internal-macro/src/lib.rs",
"/dioxus/packages/lazy-js-bundle/src/lib.rs",
"/dioxus/packages/manganis/manganis/README.md",
"/dioxus/packages/manganis/manganis/src/hash.rs",
"/dioxus/packages/manganis/manganis/src/lib.rs",
"/dioxus/packages/manganis/manganis/src/macro_helpers.rs",
"/dioxus/packages/manganis/manganis-core/src/asset.rs",
"/dioxus/packages/manganis/manganis-core/src/css.rs",
"/dioxus/packages/manganis/manganis-core/src/folder.rs",
"/dioxus/packages/manganis/manganis-core/src/hash.rs",
"/dioxus/packages/manganis/manganis-core/src/images.rs",
"/dioxus/packages/manganis/manganis-core/src/js.rs",
"/dioxus/packages/manganis/manganis-core/src/lib.rs",
"/dioxus/packages/manganis/manganis-core/src/linker.rs",
"/dioxus/packages/manganis/manganis-core/src/options.rs",
"/dioxus/packages/manganis/manganis-macro/README.md",
"/dioxus/packages/manganis/manganis-macro/src/asset.rs",
"/dioxus/packages/manganis/manganis-macro/src/lib.rs",
"/dioxus/packages/manganis/manganis-macro/src/linker.rs",
"/dioxus/packages/rsx/src/assign_dyn_ids.rs",
"/dioxus/packages/rsx/src/attribute.rs",
"/dioxus/packages/rsx/src/component.rs",
"/dioxus/packages/rsx/src/diagnostics.rs",
"/dioxus/packages/rsx/src/element.rs",
"/dioxus/packages/rsx/src/expr_node.rs",
"/dioxus/packages/rsx/src/forloop.rs",
"/dioxus/packages/rsx/src/ifchain.rs",
"/dioxus/packages/rsx/src/ifmt.rs",
"/dioxus/packages/rsx/src/lib.rs",
"/dioxus/packages/rsx/src/literal.rs",
"/dioxus/packages/rsx/src/location.rs",
"/dioxus/packages/rsx/src/node.rs",
"/dioxus/packages/rsx/src/partial_closure.rs",
"/dioxus/packages/rsx/src/raw_expr.rs",
"/dioxus/packages/rsx/src/rsx_block.rs",
"/dioxus/packages/rsx/src/rsx_call.rs",
"/dioxus/packages/rsx/src/template_body.rs",
"/dioxus/packages/rsx/src/text_node.rs",
"/dioxus/packages/rsx/src/util.rs",
"/dioxus/packages/rsx-hotreload/src/collect.rs",
"/dioxus/packages/rsx-hotreload/src/diff.rs",
"/dioxus/packages/rsx-hotreload/src/extensions.rs",
"/dioxus/packages/rsx-hotreload/src/last_build_state.rs",
"/dioxus/packages/rsx-hotreload/src/lib.rs",
"/dioxus/packages/rsx-rosetta/README.md",
"/dioxus/packages/rsx-rosetta/src/lib.rs",
"/dioxus/packages/server-macro/src/lib.rs",
"/dioxus/packages/signals/README.md",
"/dioxus/packages/signals/docs/hoist/error.rs",
"/dioxus/packages/signals/docs/hoist/fixed_list.rs",
"/dioxus/packages/signals/docs/memo.md",
"/dioxus/packages/signals/docs/signals.md",
"/dioxus/packages/signals/src/copy_value.rs",
"/dioxus/packages/signals/src/global/memo.rs",
"/dioxus/packages/signals/src/global/mod.rs",
"/dioxus/packages/signals/src/global/signal.rs",
"/dioxus/packages/signals/src/impls.rs",
"/dioxus/packages/signals/src/lib.rs",
"/dioxus/packages/signals/src/map.rs",
"/dioxus/packages/signals/src/memo.rs",
"/dioxus/packages/signals/src/props.rs",
"/dioxus/packages/signals/src/read.rs",
"/dioxus/packages/signals/src/set_compare.rs",
"/dioxus/packages/signals/src/signal.rs",
"/dioxus/packages/signals/src/warnings.rs",
"/dioxus/packages/signals/src/write.rs",
"/dioxus/target/debug/build/dioxus-cli-90993e55e02b7cee/out/built.rs",
];
assert_eq!(
answer.iter().map(PathBuf::from).collect::<Vec<_>>(),
info.files
);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/lazy-js-bundle/src/lib.rs | packages/lazy-js-bundle/src/lib.rs | use std::collections::hash_map::DefaultHasher;
use std::path::{Path, PathBuf};
use std::{hash::Hasher, process::Command};
struct Binding {
input_path: PathBuf,
output_path: PathBuf,
}
/// A builder for generating TypeScript bindings lazily
#[derive(Default)]
pub struct LazyTypeScriptBindings {
binding: Vec<Binding>,
minify_level: MinifyLevel,
watching: Vec<PathBuf>,
}
impl LazyTypeScriptBindings {
/// Create a new builder for generating TypeScript bindings that inputs from the given path and outputs javascript to the given path
pub fn new() -> Self {
Self::default()
}
/// Add a binding to generate
pub fn with_binding(
mut self,
input_path: impl AsRef<Path>,
output_path: impl AsRef<Path>,
) -> Self {
let input_path = input_path.as_ref();
let output_path = output_path.as_ref();
self.binding.push(Binding {
input_path: input_path.to_path_buf(),
output_path: output_path.to_path_buf(),
});
self
}
/// Set the minify level for the bindings
pub fn with_minify_level(mut self, minify_level: MinifyLevel) -> Self {
self.minify_level = minify_level;
self
}
/// Watch any .js or .ts files in a directory and re-generate the bindings when they change
// TODO: we should watch any files that get bundled by bun by reading the source map
pub fn with_watching(mut self, path: impl AsRef<Path>) -> Self {
let path = path.as_ref();
self.watching.push(path.to_path_buf());
self
}
/// Run the bindings
pub fn run(&self) {
// If any TS changes, re-run the build script
let mut watching_paths = Vec::new();
for path in &self.watching {
if let Ok(dir) = std::fs::read_dir(path) {
for entry in dir.flatten() {
let path = entry.path();
if path
.extension()
.map(|ext| ext == "ts" || ext == "js")
.unwrap_or(false)
{
watching_paths.push(path);
}
}
} else {
watching_paths.push(path.to_path_buf());
}
}
for path in &watching_paths {
println!("cargo:rerun-if-changed={}", path.display());
}
// Compute the hash of the input files
let hashes = hash_files(watching_paths);
let hash_location = PathBuf::from("./src/js/");
std::fs::create_dir_all(&hash_location).unwrap_or_else(|err| {
panic!(
"Failed to create directory for hash file: {} in {}",
err,
hash_location.display()
)
});
let hash_location = hash_location.join("hash.txt");
// If the hash matches the one on disk, we're good and don't need to update bindings
let fs_hash_string = std::fs::read_to_string(&hash_location);
let expected = fs_hash_string
.as_ref()
.map(|s| s.trim())
.unwrap_or_default();
let hashes_string = format!("{hashes:?}");
if expected == hashes_string {
return;
}
// Otherwise, generate the bindings and write the new hash to disk
for path in &self.binding {
gen_bindings(&path.input_path, &path.output_path, self.minify_level);
}
std::fs::write(hash_location, hashes_string).unwrap();
}
}
/// The level of minification to apply to the bindings
#[derive(Copy, Clone, Debug, Default)]
pub enum MinifyLevel {
/// Don't minify the bindings
None,
/// Minify whitespace
Whitespace,
/// Minify whitespace and syntax
#[default]
Syntax,
/// Minify whitespace, syntax, and identifiers
Identifiers,
}
impl MinifyLevel {
fn as_args(&self) -> &'static [&'static str] {
match self {
MinifyLevel::None => &[],
MinifyLevel::Whitespace => &["--minify-whitespace"],
MinifyLevel::Syntax => &["--minify-whitespace", "--minify-syntax"],
MinifyLevel::Identifiers => &[
"--minify-whitespace",
"--minify-syntax",
"--minify-identifiers",
],
}
}
}
/// Hashes the contents of a directory
fn hash_files(mut files: Vec<PathBuf>) -> Vec<u64> {
// Different systems will read the files in different orders, so we sort them to make sure the hash is consistent
files.sort();
let mut hashes = Vec::new();
for file in files {
let mut hash = DefaultHasher::new();
let Ok(contents) = std::fs::read_to_string(file) else {
continue;
};
// windows + git does a weird thing with line endings, so we need to normalize them
for line in contents.lines() {
hash.write(line.as_bytes());
}
hashes.push(hash.finish());
}
hashes
}
// okay...... so bun might fail if the user doesn't have it installed
// we don't really want to fail if that's the case
// but if you started *editing* the .ts files, you're gonna have a bad time
// so.....
// we need to hash each of the .ts files and add that hash to the JS files
// if the hashes don't match, we need to fail the build
// that way we also don't need
fn gen_bindings(input_path: &Path, output_path: &Path, minify_level: MinifyLevel) {
// If the file is generated, and the hash is different, we need to generate it
let status = Command::new("bun")
.arg("build")
.arg(input_path)
.arg("--outfile")
.arg(output_path)
.args(minify_level.as_args())
.status();
let status = match status {
Ok(status) => status,
Err(error) => {
if Command::new("bun").status().is_ok() {
panic!(
"Bun failed to generated bindings for {:?}. Error:\n{:?}",
input_path, error
);
} else {
panic!("Make sure you have Bun installed. Failed to generate bindings for {:?}. Error:\n{:?}", input_path, error);
}
}
};
if !status.success() {
panic!("Bun failed to generate bindings for {:?}.", input_path);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/dx-wire-format/src/lib.rs | packages/dx-wire-format/src/lib.rs | use cargo_metadata::{diagnostic::Diagnostic, CompilerMessage};
use manganis_core::BundledAsset;
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::HashSet, path::PathBuf};
use subsecond_types::JumpTable;
pub use cargo_metadata;
/// The structured output for the CLI
///
/// This is designed such that third party tools can reliably consume the output of the CLI when
/// outputting json.
///
/// Not every log outputted will be parsable, but all structured logs should be.
///
/// This means the debug format of this log needs to be parsable json, not the default debug format.
///
/// We guarantee that the last line of the command represents the success of the command, such that
/// tools can simply parse the last line of the output.
///
/// There might be intermediate lines that are parseable as structured logs (which you can put here)
/// but they are not guaranteed to be, such that we can provide better error messages for the user.
#[allow(clippy::large_enum_variant)]
#[non_exhaustive]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum StructuredOutput {
BuildsFinished {
client: StructuredBuildArtifacts,
server: Option<StructuredBuildArtifacts>,
},
PrintCargoArgs {
args: Vec<String>,
env: Vec<(Cow<'static, str>, String)>,
},
BuildFinished {
artifacts: StructuredBuildArtifacts,
},
BuildUpdate {
stage: BuildStage,
},
Hotpatch {
jump_table: JumpTable,
artifacts: StructuredBuildArtifacts,
},
CargoOutput {
message: CompilerMessage,
},
RustcOutput {
message: Diagnostic,
},
BundleOutput {
bundles: Vec<PathBuf>,
client: StructuredBuildArtifacts,
server: Option<StructuredBuildArtifacts>,
},
HtmlTranslate {
html: String,
},
Success,
Error {
message: String,
},
}
impl std::fmt::Display for StructuredOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&serde_json::to_string(self).map_err(|_e| std::fmt::Error)?)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StructuredBuildArtifacts {
pub path: PathBuf,
pub exe: PathBuf,
pub rustc_args: Vec<String>,
pub rustc_envs: Vec<(String, String)>,
pub link_args: Vec<String>,
pub assets: HashSet<BundledAsset>, // the serialized asset manifest
}
/// The current stage of the ongoing build
///
/// This is a perma-unstable interface that is subject to change at any time.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BuildStage {
Initializing,
Starting {
crate_count: usize,
patch: bool,
},
InstallingTooling,
Compiling {
current: usize,
total: usize,
krate: String,
},
RunningBindgen,
SplittingBundle,
OptimizingWasm,
Linking,
Hotpatching,
ExtractingAssets,
CopyingAssets {
current: usize,
total: usize,
path: PathBuf,
},
Bundling,
RunningGradle,
CodeSigning,
Success,
Failed,
Aborted,
Restarting,
CompressingAssets,
Prerendering,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/lib.rs | packages/stores/src/lib.rs | #![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)]
#![allow(clippy::type_complexity)]
mod impls;
mod store;
mod subscriptions;
pub use impls::*;
pub use store::*;
pub mod scope;
#[cfg(feature = "macro")]
pub use dioxus_stores_macro::{store, Store};
/// Re-exports for the store derive macro
#[doc(hidden)]
pub mod macro_helpers {
pub use dioxus_core;
pub use dioxus_signals;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/store.rs | packages/stores/src/store.rs | use crate::{
scope::SelectorScope,
subscriptions::{StoreSubscriptions, TinyVec},
};
use dioxus_core::{
use_hook, AttributeValue, DynamicNode, IntoAttributeValue, IntoDynNode, Subscribers, SuperInto,
};
use dioxus_signals::{
read_impls, write_impls, BorrowError, BorrowMutError, BoxedSignalStorage, CopyValue,
CreateBoxedSignalStorage, Global, InitializeFromFunction, MappedMutSignal, ReadSignal,
Readable, ReadableExt, ReadableRef, Storage, SyncStorage, UnsyncStorage, Writable, WritableExt,
WritableRef, WriteSignal,
};
use std::marker::PhantomData;
/// A type alias for a store that has been mapped with a function
pub(crate) type MappedStore<
T,
Lens,
F = fn(&<Lens as Readable>::Target) -> &T,
FMut = fn(&mut <Lens as Readable>::Target) -> &mut T,
> = Store<T, MappedMutSignal<T, Lens, F, FMut>>;
/// A type alias for a boxed read-only store.
pub type ReadStore<T, S = UnsyncStorage> = Store<T, ReadSignal<T, S>>;
/// A type alias for a boxed writable-only store.
pub type WriteStore<T, S = UnsyncStorage> = Store<T, WriteSignal<T, S>>;
/// A type alias for a store backed by SyncStorage.
pub type SyncStore<T> = Store<T, CopyValue<T, SyncStorage>>;
/// Stores are a reactive type built for nested data structures. Each store will lazily create signals
/// for each field/member of the data structure as needed.
///
/// By default stores act a lot like [`dioxus_signals::Signal`]s, but they provide more granular
/// subscriptions without requiring nested signals. You should derive [`Store`](dioxus_stores_macro::Store) on your data
/// structures to generate selectors that let you scope the store to a specific part of your data.
///
/// You can also use the [`#[store]`](dioxus_stores_macro::store) macro on an impl block to add any additional methods to your store
/// with an extension trait. This lets you add methods to the store even though the type is not defined in your crate.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// fn main() {
/// dioxus::launch(app);
/// }
///
/// // Deriving the store trait provides methods to scope the store to specific parts of your data structure.
/// // The `Store` macro generates a `count` and `children` method for the `CounterTree` struct.
/// #[derive(Store, Default)]
/// struct CounterTree {
/// count: i32,
/// children: Vec<CounterTree>,
/// }
///
/// // The store macro generates an extension trait with additional methods for the store based on the impl block.
/// #[store]
/// impl<Lens> Store<CounterTree, Lens> {
/// // Methods that take &self automatically require the lens to implement `Readable` which lets you read the store.
/// fn sum(&self) -> i32 {
/// self.count().cloned() + self.children().iter().map(|c| c.sum()).sum::<i32>()
/// }
/// }
///
/// fn app() -> Element {
/// let value = use_store(Default::default);
///
/// rsx! {
/// Tree {
/// value
/// }
/// }
/// }
///
/// #[component]
/// fn Tree(value: Store<CounterTree>) -> Element {
/// // Calling the generated `count` method returns a new store that can only
/// // read and write the count field
/// let mut count = value.count();
/// let mut children = value.children();
/// rsx! {
/// button {
/// // Incrementing the count will only rerun parts of the app that have read the count field
/// onclick: move |_| count += 1,
/// "Increment"
/// }
/// button {
/// // Stores are aware of data structures like `Vec` and `Hashmap`. When we push an item to the vec
/// // it will only rerun the parts of the app that depend on the length of the vec
/// onclick: move |_| children.push(Default::default()),
/// "Push child"
/// }
/// "sum: {value.sum()}"
/// ul {
/// // Iterating over the children gives us stores scoped to each child.
/// for value in children.iter() {
/// li {
/// Tree { value }
/// }
/// }
/// }
/// }
/// }
/// ```
pub struct Store<T: ?Sized, Lens = WriteSignal<T>> {
selector: SelectorScope<Lens>,
_phantom: PhantomData<Box<T>>,
}
impl<T: 'static, S: Storage<T>> Store<T, CopyValue<T, S>> {
/// Creates a new `Store` that might be sync. This allocates memory in the current scope, so this should only be called
/// inside of an initialization closure like the closure passed to [`use_hook`].
#[track_caller]
pub fn new_maybe_sync(value: T) -> Self {
let store = StoreSubscriptions::new();
let value = CopyValue::new_maybe_sync(value);
let path = TinyVec::new();
let selector = SelectorScope::new(path, store, value);
selector.into()
}
}
impl<T: 'static> Store<T> {
/// Creates a new `Store`. This allocates memory in the current scope, so this should only be called
/// inside of an initialization closure like the closure passed to [`use_hook`].
#[track_caller]
pub fn new(value: T) -> Self {
let store = StoreSubscriptions::new();
let value = CopyValue::new_maybe_sync(value);
let value = value.into();
let path = TinyVec::new();
let selector = SelectorScope::new(path, store, value);
selector.into()
}
}
impl<T: ?Sized, Lens> Store<T, Lens> {
/// Get the underlying selector for this store. The selector provides low level access to the lazy tracking system
/// of the store. This can be useful to create selectors for custom data structures in libraries. For most applications
/// the selectors generated by the [`Store`](dioxus_stores_macro::Store) macro provide all the functionality you need.
pub fn selector(&self) -> &SelectorScope<Lens> {
&self.selector
}
/// Convert the store into the underlying selector
pub fn into_selector(self) -> SelectorScope<Lens> {
self.selector
}
}
impl<T: ?Sized, Lens> From<SelectorScope<Lens>> for Store<T, Lens> {
fn from(selector: SelectorScope<Lens>) -> Self {
Self {
selector,
_phantom: PhantomData,
}
}
}
impl<T: ?Sized, Lens> PartialEq for Store<T, Lens>
where
Lens: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.selector == other.selector
}
}
impl<T: ?Sized, Lens> Clone for Store<T, Lens>
where
Lens: Clone,
{
fn clone(&self) -> Self {
Self {
selector: self.selector.clone(),
_phantom: ::std::marker::PhantomData,
}
}
}
impl<T: ?Sized, Lens> Copy for Store<T, Lens> where Lens: Copy {}
impl<__F, __FMut, T: ?Sized, S, Lens> ::std::convert::From<MappedStore<T, Lens, __F, __FMut>>
for WriteStore<T, S>
where
Lens: Writable<Storage = S> + 'static,
__F: Fn(&Lens::Target) -> &T + 'static,
__FMut: Fn(&mut Lens::Target) -> &mut T + 'static,
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<MappedMutSignal<T, Lens, __F, __FMut>>,
T: 'static,
{
fn from(value: MappedStore<T, Lens, __F, __FMut>) -> Self {
Store {
selector: value.selector.map_writer(::std::convert::Into::into),
_phantom: ::std::marker::PhantomData,
}
}
}
impl<__F, __FMut, T: ?Sized, S, Lens> ::std::convert::From<MappedStore<T, Lens, __F, __FMut>>
for ReadStore<T, S>
where
Lens: Writable<Storage = S> + 'static,
__F: Fn(&Lens::Target) -> &T + 'static,
__FMut: Fn(&mut Lens::Target) -> &mut T + 'static,
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<MappedMutSignal<T, Lens, __F, __FMut>>,
T: 'static,
{
fn from(value: MappedStore<T, Lens, __F, __FMut>) -> Self {
Store {
selector: value.selector.map_writer(::std::convert::Into::into),
_phantom: ::std::marker::PhantomData,
}
}
}
impl<T, S> ::std::convert::From<WriteStore<T, S>> for ReadStore<T, S>
where
T: ?Sized + 'static,
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<WriteSignal<T, S>>,
{
fn from(value: Store<T, WriteSignal<T, S>>) -> Self {
Self {
selector: value.selector.map_writer(::std::convert::Into::into),
_phantom: ::std::marker::PhantomData,
}
}
}
impl<T, S> ::std::convert::From<Store<T, CopyValue<T, S>>> for ReadStore<T, S>
where
T: 'static,
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<CopyValue<T, S>> + Storage<T>,
{
fn from(value: Store<T, CopyValue<T, S>>) -> Self {
Self {
selector: value.selector.map_writer(::std::convert::Into::into),
_phantom: ::std::marker::PhantomData,
}
}
}
impl<T, S> ::std::convert::From<Store<T, CopyValue<T, S>>> for WriteStore<T, S>
where
T: 'static,
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<CopyValue<T, S>> + Storage<T>,
{
fn from(value: Store<T, CopyValue<T, S>>) -> Self {
Self {
selector: value.selector.map_writer(::std::convert::Into::into),
_phantom: ::std::marker::PhantomData,
}
}
}
#[doc(hidden)]
pub struct SuperIntoReadSignalMarker;
impl<T, S, Lens> SuperInto<ReadSignal<T, S>, SuperIntoReadSignalMarker> for Store<T, Lens>
where
T: ?Sized + 'static,
Lens: Readable<Target = T, Storage = S> + 'static,
S: CreateBoxedSignalStorage<Store<T, Lens>> + BoxedSignalStorage<T>,
{
fn super_into(self) -> ReadSignal<T, S> {
ReadSignal::new_maybe_sync(self)
}
}
#[doc(hidden)]
pub struct SuperIntoWriteSignalMarker;
impl<T, S, Lens> SuperInto<WriteSignal<T, S>, SuperIntoWriteSignalMarker> for Store<T, Lens>
where
T: ?Sized + 'static,
Lens: Writable<Target = T, Storage = S> + 'static,
S: CreateBoxedSignalStorage<Store<T, Lens>> + BoxedSignalStorage<T>,
{
fn super_into(self) -> WriteSignal<T, S> {
WriteSignal::new_maybe_sync(self)
}
}
impl<T: ?Sized, Lens> Readable for Store<T, Lens>
where
Lens: Readable<Target = T>,
T: 'static,
{
type Storage = Lens::Storage;
type Target = T;
fn try_read_unchecked(&self) -> Result<ReadableRef<'static, Self>, BorrowError> {
self.selector.try_read_unchecked()
}
fn try_peek_unchecked(&self) -> Result<ReadableRef<'static, Self>, BorrowError> {
self.selector.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers {
self.selector.subscribers()
}
}
impl<T: ?Sized, Lens> Writable for Store<T, Lens>
where
Lens: Writable<Target = T>,
T: 'static,
{
type WriteMetadata = Lens::WriteMetadata;
fn try_write_unchecked(&self) -> Result<WritableRef<'static, Self>, BorrowMutError> {
self.selector.try_write_unchecked()
}
}
impl<T, Lens> IntoAttributeValue for Store<T, Lens>
where
Self: Readable<Target = T>,
T: ::std::clone::Clone + IntoAttributeValue + 'static,
{
fn into_value(self) -> AttributeValue {
ReadableExt::cloned(&self).into_value()
}
}
impl<T, Lens> IntoDynNode for Store<T, Lens>
where
Self: Readable<Target = T>,
T: ::std::clone::Clone + IntoDynNode + 'static,
{
fn into_dyn_node(self) -> DynamicNode {
ReadableExt::cloned(&self).into_dyn_node()
}
}
impl<T, Lens> ::std::ops::Deref for Store<T, Lens>
where
Self: Readable<Target = T> + 'static,
T: ::std::clone::Clone + 'static,
{
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
read_impls!(Store<T, Lens> where Lens: Readable<Target = T>);
write_impls!(Store<T, Lens> where Lens: Writable<Target = T>);
/// Create a new [`Store`]. Stores are a reactive type built for nested data structures.
///
///
/// By default stores act a lot like [`dioxus_signals::Signal`]s, but they provide more granular
/// subscriptions without requiring nested signals. You should derive [`Store`](dioxus_stores_macro::Store) on your data
/// structures to generate selectors that let you scope the store to a specific part of your data structure.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// fn main() {
/// dioxus::launch(app);
/// }
///
/// // Deriving the store trait provides methods to scope the store to specific parts of your data structure.
/// // The `Store` macro generates a `count` and `children` method for `Store<CounterTree>`.
/// #[derive(Store, Default)]
/// struct CounterTree {
/// count: i32,
/// children: Vec<CounterTree>,
/// }
///
/// fn app() -> Element {
/// let value = use_store(Default::default);
///
/// rsx! {
/// Tree {
/// value
/// }
/// }
/// }
///
/// #[component]
/// fn Tree(value: Store<CounterTree>) -> Element {
/// // Calling the generated `count` method returns a new store that can only
/// // read and write the count field
/// let mut count = value.count();
/// let mut children = value.children();
/// rsx! {
/// button {
/// // Incrementing the count will only rerun parts of the app that have read the count field
/// onclick: move |_| count += 1,
/// "Increment"
/// }
/// button {
/// // Stores are aware of data structures like `Vec` and `Hashmap`. When we push an item to the vec
/// // it will only rerun the parts of the app that depend on the length of the vec
/// onclick: move |_| children.push(Default::default()),
/// "Push child"
/// }
/// ul {
/// // Iterating over the children gives us stores scoped to each child.
/// for value in children.iter() {
/// li {
/// Tree { value }
/// }
/// }
/// }
/// }
/// }
/// ```
pub fn use_store<T: 'static>(init: impl FnOnce() -> T) -> Store<T> {
use_hook(move || Store::new(init()))
}
/// Create a new [`SyncStore`]. Stores are a reactive type built for nested data structures.
/// `SyncStore` is a Store backed by `SyncStorage`.
///
/// Like [`use_store`], but produces `SyncStore<T>` instead of `Store<T>`
pub fn use_store_sync<T: Send + Sync + 'static>(init: impl FnOnce() -> T) -> SyncStore<T> {
use_hook(|| Store::new_maybe_sync(init()))
}
/// A type alias for global stores
///
/// # Example
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// #[derive(Store)]
/// struct Counter {
/// count: i32,
/// }
///
/// static COUNTER: GlobalStore<Counter> = Global::new(|| Counter { count: 0 });
///
/// fn app() -> Element {
/// let mut count = COUNTER.resolve().count();
///
/// rsx! {
/// button {
/// onclick: move |_| count += 1,
/// "{count}"
/// }
/// }
/// }
/// ```
pub type GlobalStore<T> = Global<Store<T>, T>;
impl<T: 'static> InitializeFromFunction<T> for Store<T> {
fn initialize_from_function(f: fn() -> T) -> Self {
Store::new(f())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/scope.rs | packages/stores/src/scope.rs | //! This module contains the `SelectorScope` type with raw access to the underlying store system. Most applications should
//! use the [`Store`](dioxus_stores_macro::Store) macro to derive stores for their data structures, which provides a more ergonomic API.
use std::{fmt::Debug, hash::Hash};
use crate::subscriptions::{PathKey, StoreSubscriptions, TinyVec};
use dioxus_core::Subscribers;
use dioxus_signals::{
BorrowError, BorrowMutError, MappedMutSignal, Readable, ReadableRef, Writable, WritableExt,
WritableRef,
};
/// SelectorScope is the primitive that backs the store system.
///
/// Under the hood stores consist of two different parts:
/// - The underlying lock that contains the data in the store.
/// - A tree of subscriptions used to make the store reactive.
///
/// The `SelectorScope` contains a view into the lock (`Lens`) and a path into the subscription tree. When
/// the selector is read to, it will track the current path in the subscription tree. When it it written to
/// it marks itself and all its children as dirty.
///
/// When you derive the [`Store`](dioxus_stores_macro::Store) macro on your data structure,
/// it generates methods that map the lock to a new type and scope the path to a specific part of the subscription structure.
/// For example, a `Counter` store might look like this:
///
/// ```rust, ignore
/// #[derive(Store)]
/// struct Counter {
/// count: i32,
/// }
///
/// impl CounterStoreExt for Store<Counter> {
/// fn count(
/// self,
/// ) -> dioxus_stores::Store<
/// i32,
/// dioxus_stores::macro_helpers::dioxus_signals::MappedMutSignal<i32, __W>,
/// > {
/// let __map_field: fn(&CounterTree) -> &i32 = |value| &value.count;
/// let __map_mut_field: fn(&mut CounterTree) -> &mut i32 = |value| &mut value.count;
/// let scope = self.selector().scope(0u32, __map_field, __map_mut_field);
/// dioxus_stores::Store::new(scope)
/// }
/// }
/// ```
///
/// The `count` method maps the lock to the `i32` type and creates a child `0` path in the subscription tree. Only writes
/// to that `0` path or its parents will trigger a re-render of the components that read the `count` field.
#[derive(PartialEq)]
pub struct SelectorScope<Lens> {
path: TinyVec,
store: StoreSubscriptions,
write: Lens,
}
impl<Lens> Debug for SelectorScope<Lens> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("SelectorScope")
.field("path", &self.path)
.finish()
}
}
impl<Lens> Clone for SelectorScope<Lens>
where
Lens: Clone,
{
fn clone(&self) -> Self {
Self {
path: self.path,
store: self.store,
write: self.write.clone(),
}
}
}
impl<Lens> Copy for SelectorScope<Lens> where Lens: Copy {}
impl<Lens> SelectorScope<Lens> {
pub(crate) fn new(path: TinyVec, store: StoreSubscriptions, write: Lens) -> Self {
Self { path, store, write }
}
/// Create a child selector scope for a hash key. The scope will only be marked as dirty when a
/// write occurs to that key or its parents.
///
/// Note the hash is lossy, so there may rarely be collisions. If a collision does occur, it may
/// cause reruns in a part of the app that has not changed. As long as derived data is pure,
/// this should not cause issues.
pub fn hash_child<U: ?Sized, T, F, FMut>(
self,
index: &impl Hash,
map: F,
map_mut: FMut,
) -> SelectorScope<MappedMutSignal<U, Lens, F, FMut>>
where
F: Fn(&T) -> &U,
FMut: Fn(&mut T) -> &mut U,
{
let hash = self.store.hash(index);
self.child(hash, map, map_mut)
}
/// Create a child selector scope for a specific index. The scope will only be marked as dirty when a
/// write occurs to that index or its parents.
pub fn child<U: ?Sized, T, F, FMut>(
self,
index: PathKey,
map: F,
map_mut: FMut,
) -> SelectorScope<MappedMutSignal<U, Lens, F, FMut>>
where
F: Fn(&T) -> &U,
FMut: Fn(&mut T) -> &mut U,
{
self.child_unmapped(index).map(map, map_mut)
}
/// Create a hashed child selector scope for a specific index without mapping the writer. The scope will only
/// be marked as dirty when a write occurs to that index or its parents.
pub fn hash_child_unmapped(self, index: &impl Hash) -> SelectorScope<Lens> {
let hash = self.store.hash(index);
self.child_unmapped(hash)
}
/// Create a child selector scope for a specific index without mapping the writer. The scope will only
/// be marked as dirty when a write occurs to that index or its parents.
pub fn child_unmapped(mut self, index: PathKey) -> SelectorScope<Lens> {
self.path.push(index);
self
}
/// Map the view into the writable data without creating a child selector scope
pub fn map<U: ?Sized, T, F, FMut>(
self,
map: F,
map_mut: FMut,
) -> SelectorScope<MappedMutSignal<U, Lens, F, FMut>>
where
F: Fn(&T) -> &U,
FMut: Fn(&mut T) -> &mut U,
{
self.map_writer(move |write| MappedMutSignal::new(write, map, map_mut))
}
/// Track this scope shallowly.
pub fn track_shallow(&self) {
self.store.track(&self.path);
}
/// Track this scope recursively.
pub fn track(&self) {
self.store.track_recursive(&self.path);
}
/// Mark this scope as dirty recursively.
pub fn mark_dirty(&self) {
self.store.mark_dirty(&self.path);
}
/// Mark this scope as dirty shallowly.
pub fn mark_dirty_shallow(&self) {
self.store.mark_dirty_shallow(&self.path);
}
/// Mark this scope as dirty at and after the given index.
pub fn mark_dirty_at_and_after_index(&self, index: usize) {
self.store.mark_dirty_at_and_after_index(&self.path, index);
}
/// Map the writer to a new type.
pub fn map_writer<W2>(self, map: impl FnOnce(Lens) -> W2) -> SelectorScope<W2> {
SelectorScope {
path: self.path,
store: self.store,
write: map(self.write),
}
}
/// Write without notifying subscribers.
pub fn write_untracked(&self) -> WritableRef<'static, Lens>
where
Lens: Writable,
{
self.write.write_unchecked()
}
/// Borrow the writer
pub(crate) fn as_ref(&self) -> SelectorScope<&Lens> {
SelectorScope {
path: self.path,
store: self.store,
write: &self.write,
}
}
}
impl<Lens: Readable> Readable for SelectorScope<Lens> {
type Target = Lens::Target;
type Storage = Lens::Storage;
fn try_read_unchecked(&self) -> Result<ReadableRef<'static, Lens>, BorrowError> {
self.track();
self.write.try_read_unchecked()
}
fn try_peek_unchecked(&self) -> Result<ReadableRef<'static, Lens>, BorrowError> {
self.write.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers {
self.store.subscribers(&self.path)
}
}
impl<Lens: Writable> Writable for SelectorScope<Lens> {
type WriteMetadata = Lens::WriteMetadata;
fn try_write_unchecked(&self) -> Result<WritableRef<'static, Lens>, BorrowMutError> {
self.mark_dirty();
self.write.try_write_unchecked()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/subscriptions.rs | packages/stores/src/subscriptions.rs | use dioxus_core::{ReactiveContext, SubscriberList, Subscribers};
use dioxus_signals::{CopyValue, ReadableExt, SyncStorage, Writable, WritableExt};
use std::fmt::Debug;
use std::hash::BuildHasher;
use std::{
collections::{HashMap, HashSet},
hash::Hash,
ops::Deref,
sync::Arc,
};
/// A single node in the [`StoreSubscriptions`] tree. Each path is a specific view into the store
/// and can be subscribed to and marked dirty separately. If the whole store is read or written to, all
/// nodes in the subtree are subscribed to or marked as dirty.
#[derive(Clone, Default)]
pub(crate) struct SelectorNode {
subscribers: HashSet<ReactiveContext>,
root: HashMap<PathKey, SelectorNode>,
}
impl SelectorNode {
/// Get an existing selector node by its path.
fn get(&self, path: &[PathKey]) -> Option<&SelectorNode> {
let [first, rest @ ..] = path else {
return Some(self);
};
self.root.get(first).and_then(|child| child.get(rest))
}
/// Get an existing selector node by its path mutably.
fn get_mut(&mut self, path: &[PathKey]) -> Option<&mut SelectorNode> {
let [first, rest @ ..] = path else {
return Some(self);
};
self.root
.get_mut(first)
.and_then(|child| child.get_mut(rest))
}
/// Get a selector mutably or create one if it doesn't exist. This is used when subscribing to
/// a path that may not exist yet.
fn get_mut_or_default(&mut self, path: &[PathKey]) -> &mut SelectorNode {
let [first, rest @ ..] = path else {
return self;
};
self.root
.entry(*first)
.or_default()
.get_mut_or_default(rest)
}
/// Get the path to each node under this node
///
/// This is used to mark nodes dirty recursively when a Store is written to.
fn paths_under(&self, current_path: &[PathKey], paths: &mut Vec<Box<[PathKey]>>) {
paths.push(current_path.into());
for (i, child) in self.root.iter() {
let mut child_path: Vec<PathKey> = current_path.into();
child_path.push(*i);
child.paths_under(&child_path, paths);
}
}
/// Get paths to only children before a certain index.
///
/// This is used when inserting a new item into a list.
/// Items after the index that is inserted need to be marked dirty because the value that index points to may have changed.
fn paths_at_and_after_index(
&self,
path: &[PathKey],
index: usize,
paths: &mut Vec<Box<[PathKey]>>,
) {
let Some(node) = self.get(path) else {
return;
};
// Mark the nodes before the index as dirty
for (i, child) in node.root.iter() {
if *i as usize >= index {
let mut child_path: Vec<PathKey> = path.into();
child_path.push(*i);
child.paths_under(&child_path, paths);
}
}
}
/// Remove a path from the subscription tree
fn remove(&mut self, path: &[PathKey]) {
let [first, rest @ ..] = path else {
return;
};
if let Some(node) = self.root.get_mut(first) {
if rest.is_empty() {
self.root.remove(first);
} else {
node.remove(rest);
}
}
}
}
pub(crate) type PathKey = u16;
#[cfg(feature = "large-path")]
const PATH_LENGTH: usize = 32;
#[cfg(not(feature = "large-path"))]
const PATH_LENGTH: usize = 16;
#[derive(Copy, Clone, PartialEq)]
pub(crate) struct TinyVec {
length: usize,
path: [PathKey; PATH_LENGTH],
}
impl Default for TinyVec {
fn default() -> Self {
Self::new()
}
}
impl Debug for TinyVec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TinyVec")
.field("path", &&self.path[..self.length])
.finish()
}
}
impl TinyVec {
pub(crate) const fn new() -> Self {
Self {
length: 0,
path: [0; PATH_LENGTH],
}
}
pub(crate) const fn push(&mut self, index: u16) {
if self.length < self.path.len() {
self.path[self.length] = index;
self.length += 1;
} else {
panic!("SelectorPath is full");
}
}
}
impl Deref for TinyVec {
type Target = [u16];
fn deref(&self) -> &Self::Target {
&self.path[..self.length]
}
}
#[derive(Default)]
pub(crate) struct StoreSubscriptionsInner {
root: SelectorNode,
hasher: std::collections::hash_map::RandomState,
}
#[derive(Default)]
pub(crate) struct StoreSubscriptions {
inner: CopyValue<StoreSubscriptionsInner, SyncStorage>,
}
impl Clone for StoreSubscriptions {
fn clone(&self) -> Self {
*self
}
}
impl Copy for StoreSubscriptions {}
impl PartialEq for StoreSubscriptions {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl StoreSubscriptions {
/// Create a new instance of StoreSubscriptions.
pub(crate) fn new() -> Self {
Self {
inner: CopyValue::new_maybe_sync(StoreSubscriptionsInner {
root: SelectorNode::default(),
hasher: std::collections::hash_map::RandomState::new(),
}),
}
}
/// Hash an index into a PathKey using the hasher. The hash should be consistent
/// across calls
pub(crate) fn hash(&self, index: &impl Hash) -> PathKey {
(self.inner.write_unchecked().hasher.hash_one(index) % PathKey::MAX as u64) as PathKey
}
/// Subscribe to a specific path in the store.
pub(crate) fn track(&self, key: &[PathKey]) {
if let Some(rc) = ReactiveContext::current() {
let subscribers = self.subscribers(key);
rc.subscribe(subscribers);
}
}
/// Subscribe to a path and all of its children recursively. This should be called any time we give out
/// a raw reference to a store, because the user could read any level of the store.
pub(crate) fn track_recursive(&self, key: &[PathKey]) {
if let Some(rc) = ReactiveContext::current() {
let mut paths = Vec::new();
{
let mut write = self.inner.write_unchecked();
let root = write.root.get_mut_or_default(key);
let mut nodes = vec![(key.to_vec(), &*root)];
while let Some((path, node)) = nodes.pop() {
for (child_key, child_node) in &node.root {
let mut new_path = path.clone();
new_path.push(*child_key);
nodes.push((new_path, child_node));
}
paths.push(path);
}
}
for path in paths {
let subscribers = self.subscribers(&path);
rc.subscribe(subscribers);
}
}
}
/// Mark the node and all its children as dirty
pub(crate) fn mark_dirty(&self, key: &[PathKey]) {
let paths = {
let read = &self.inner.read_unchecked();
let Some(node) = read.root.get(key) else {
return;
};
let mut paths = Vec::new();
node.paths_under(key, &mut paths);
paths
};
for path in paths {
self.mark_dirty_shallow(&path);
}
}
/// Mark a single node as dirty
pub(crate) fn mark_dirty_shallow(&self, key: &[PathKey]) {
// We cannot hold the subscribers lock while calling mark_dirty, because mark_dirty can run user code which may cause a new subscriber to be added. If we hold the lock, we will deadlock.
#[allow(clippy::mutable_key_type)]
let mut subscribers = {
let mut write = self.inner.write_unchecked();
let Some(node) = write.root.get_mut(key) else {
return;
};
std::mem::take(&mut node.subscribers)
};
subscribers.retain(|reactive_context| reactive_context.mark_dirty());
// Extend the subscribers list instead of overwriting it in case a subscriber is added while reactive contexts are marked dirty
let mut write = self.inner.write_unchecked();
let Some(node) = write.root.get_mut(key) else {
return;
};
node.subscribers.extend(subscribers);
}
/// Mark all nodes after the index and their children as dirty
pub(crate) fn mark_dirty_at_and_after_index(&self, key: &[PathKey], index: usize) {
let paths = {
let read = self.inner.read_unchecked();
let mut paths = Vec::new();
read.root.paths_at_and_after_index(key, index, &mut paths);
paths
};
for path in paths {
self.mark_dirty_shallow(&path);
}
}
/// Get a subscriber list for a specific path in the store. This is used to subscribe to changes
/// to a specific path in the store and remove the node from the subscription tree when it is no longer needed.
pub(crate) fn subscribers(&self, key: &[PathKey]) -> Subscribers {
Arc::new(StoreSubscribers {
subscriptions: *self,
path: key.to_vec().into_boxed_slice(),
})
.into()
}
}
/// A subscriber list implementation that handles garbage collection of the subscription tree.
struct StoreSubscribers {
subscriptions: StoreSubscriptions,
path: Box<[PathKey]>,
}
impl SubscriberList for StoreSubscribers {
/// Add a subscriber to the subscription list for this path in the store, creating the node if it doesn't exist.
fn add(&self, subscriber: ReactiveContext) {
let Ok(mut write) = self.subscriptions.inner.try_write_unchecked() else {
return;
};
let node = write.root.get_mut_or_default(&self.path);
node.subscribers.insert(subscriber);
}
/// Remove a subscriber from the subscription list for this path in the store. If the node has no subscribers left
/// remove that node from the subscription tree.
fn remove(&self, subscriber: &ReactiveContext) {
let Ok(mut write) = self.subscriptions.inner.try_write_unchecked() else {
return;
};
let Some(node) = write.root.get_mut(&self.path) else {
return;
};
node.subscribers.remove(subscriber);
if node.subscribers.is_empty() && node.root.is_empty() {
write.root.remove(&self.path);
}
}
/// Visit all subscribers for this path in the store, calling the provided function on each subscriber.
fn visit(&self, f: &mut dyn FnMut(&ReactiveContext)) {
let Ok(read) = self.subscriptions.inner.try_read() else {
return;
};
let Some(node) = read.root.get(&self.path) else {
return;
};
node.subscribers.iter().for_each(f);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/slice.rs | packages/stores/src/impls/slice.rs | use std::iter::FusedIterator;
use crate::{impls::index::IndexWrite, store::Store};
use dioxus_signals::{Readable, ReadableExt};
impl<Lens, I> Store<Vec<I>, Lens>
where
Lens: Readable<Target = Vec<I>> + 'static,
I: 'static,
{
/// Returns the length of the slice. This will only track the shallow state of the slice.
/// It will only cause a re-run if the length of the slice could change.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| vec![1, 2, 3]);
/// assert_eq!(store.len(), 3);
/// ```
pub fn len(&self) -> usize {
self.selector().track_shallow();
self.selector().peek().len()
}
/// Checks if the slice is empty. This will only track the shallow state of the slice.
/// It will only cause a re-run if the length of the slice could change.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| vec![1, 2, 3]);
/// assert!(!store.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_empty()
}
/// Returns an iterator over the items in the slice. This will only track the shallow state of the slice.
/// It will only cause a re-run if the length of the slice could change.
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| vec![1, 2, 3]);
/// for item in store.iter() {
/// println!("{}", item);
/// }
/// ```
pub fn iter(
&self,
) -> impl ExactSizeIterator<Item = Store<I, IndexWrite<usize, Lens>>>
+ DoubleEndedIterator
+ FusedIterator
+ '_
where
Lens: Clone,
{
(0..self.len()).map(move |i| self.clone().index(i))
}
/// Try to get an item from slice. This will only track the shallow state of the slice.
/// It will only cause a re-run if the length of the slice could change. The new store
/// will only update when the item at the index changes.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| vec![1, 2, 3]);
/// let indexed_store = store.get(1).unwrap();
/// // The indexed store can access the store methods of the indexed store.
/// assert_eq!(indexed_store(), 2);
/// ```
pub fn get(&self, index: usize) -> Option<Store<I, IndexWrite<usize, Lens>>>
where
Lens: Clone,
{
if index >= self.len() {
None
} else {
Some(self.clone().index(index))
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/hashmap.rs | packages/stores/src/impls/hashmap.rs | //! Additional utilities for `HashMap` stores.
use std::{
borrow::Borrow,
collections::HashMap,
hash::{BuildHasher, Hash},
iter::FusedIterator,
panic::Location,
};
use crate::{store::Store, ReadStore};
use dioxus_signals::{
AnyStorage, BorrowError, BorrowMutError, ReadSignal, Readable, ReadableExt, UnsyncStorage,
Writable, WriteLock, WriteSignal,
};
use generational_box::ValueDroppedError;
impl<Lens: Readable<Target = HashMap<K, V, St>> + 'static, K: 'static, V: 'static, St: 'static>
Store<HashMap<K, V, St>, Lens>
{
/// Get the length of the HashMap. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// assert_eq!(store.len(), 0);
/// store.insert(0, "value".to_string());
/// assert_eq!(store.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.selector().track_shallow();
self.selector().peek().len()
}
/// Check if the HashMap is empty. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// assert!(store.is_empty());
/// store.insert(0, "value".to_string());
/// assert!(!store.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_empty()
}
/// Iterate over the current entries in the HashMap, returning a tuple of the key and a store for the value. This method
/// will track the store shallowly and only cause re-runs when items are added or removed from the map, not when existing
/// values are modified.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(0, "value1".to_string());
/// store.insert(1, "value2".to_string());
/// for (key, value_store) in store.iter() {
/// println!("{}: {}", key, value_store.read());
/// }
/// ```
pub fn iter(
&self,
) -> impl ExactSizeIterator<Item = (K, Store<V, GetWrite<K, Lens>>)>
+ DoubleEndedIterator
+ FusedIterator
+ '_
where
K: Eq + Hash + Clone,
St: BuildHasher,
Lens: Clone,
{
self.selector().track_shallow();
let keys: Vec<_> = self.selector().peek_unchecked().keys().cloned().collect();
keys.into_iter()
.map(move |key| (key.clone(), self.clone().get_unchecked(key)))
}
/// Get an iterator over the values in the HashMap. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(0, "value1".to_string());
/// store.insert(1, "value2".to_string());
/// for value_store in store.values() {
/// println!("{}", value_store.read());
/// }
/// ```
pub fn values(
&self,
) -> impl ExactSizeIterator<Item = Store<V, GetWrite<K, Lens>>>
+ DoubleEndedIterator
+ FusedIterator
+ '_
where
K: Eq + Hash + Clone,
St: BuildHasher,
Lens: Clone,
{
self.selector().track_shallow();
let keys = self.selector().peek().keys().cloned().collect::<Vec<_>>();
keys.into_iter()
.map(move |key| self.clone().get_unchecked(key))
}
/// Insert a new key-value pair into the HashMap. This method will mark the store as shallowly dirty, causing
/// re-runs of any reactive scopes that depend on the shape of the map.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// assert!(store.get(0).is_none());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// ```
pub fn insert(&mut self, key: K, value: V)
where
K: Eq + Hash,
St: BuildHasher,
Lens: Writable,
{
// Mark the store itself as dirty since the keys may have changed
self.selector().mark_dirty_shallow();
// Mark the existing value as dirty if it exists
self.selector()
.as_ref()
.hash_child_unmapped(key.borrow())
.mark_dirty();
self.selector().write_untracked().insert(key, value);
}
/// Remove a key-value pair from the HashMap. This method will mark the store as shallowly dirty, causing
/// re-runs of any reactive scopes that depend on the shape of the map or the value of the removed key.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// let removed_value = store.remove(&0);
/// assert_eq!(removed_value, Some("value".to_string()));
/// assert!(store.get(0).is_none());
/// ```
pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where
Q: ?Sized + Hash + Eq + 'static,
K: Borrow<Q> + Eq + Hash,
St: BuildHasher,
Lens: Writable,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().remove(key)
}
/// Clear the HashMap, removing all key-value pairs. This method will mark the store as shallowly dirty,
/// causing re-runs of any reactive scopes that depend on the shape of the map.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(1, "value1".to_string());
/// store.insert(2, "value2".to_string());
/// assert_eq!(store.len(), 2);
/// store.clear();
/// assert!(store.is_empty());
/// ```
pub fn clear(&mut self)
where
Lens: Writable,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().clear();
}
/// Retain only the key-value pairs that satisfy the given predicate. This method will mark the store as shallowly dirty,
/// causing re-runs of any reactive scopes that depend on the shape of the map or the values retained.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(1, "value1".to_string());
/// store.insert(2, "value2".to_string());
/// store.retain(|key, value| *key == 1);
/// assert_eq!(store.len(), 1);
/// assert!(store.get(1).is_some());
/// assert!(store.get(2).is_none());
/// ```
pub fn retain(&mut self, mut f: impl FnMut(&K, &V) -> bool)
where
Lens: Writable,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().retain(|k, v| f(k, v));
}
/// Check if the HashMap contains a key. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// assert!(!store.contains_key(&0));
/// store.insert(0, "value".to_string());
/// assert!(store.contains_key(&0));
/// ```
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
Q: ?Sized + Hash + Eq + 'static,
K: Borrow<Q> + Eq + Hash,
St: BuildHasher,
{
self.selector().track_shallow();
self.selector().peek().contains_key(key)
}
/// Get a store for the value associated with the given key. This method creates a new store scope
/// that tracks just changes to the value associated with the key.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// assert!(store.get(0).is_none());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// ```
pub fn get<Q>(self, key: Q) -> Option<Store<V, GetWrite<Q, Lens>>>
where
Q: Hash + Eq + 'static,
K: Borrow<Q> + Eq + Hash,
St: BuildHasher,
{
self.contains_key(&key).then(|| self.get_unchecked(key))
}
/// Get a store for the value associated with the given key without checking if the key exists.
/// This method creates a new store scope that tracks just changes to the value associated with the key.
///
/// This is not unsafe, but it will panic when you try to read the value if it does not exist.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::HashMap;
/// let mut store = use_store(|| HashMap::new());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get_unchecked(0).cloned(), "value".to_string());
/// ```
#[track_caller]
pub fn get_unchecked<Q>(self, key: Q) -> Store<V, GetWrite<Q, Lens>>
where
Q: Hash + Eq + 'static,
K: Borrow<Q> + Eq + Hash,
St: BuildHasher,
{
let location = Location::caller();
self.into_selector()
.hash_child_unmapped(key.borrow())
.map_writer(move |writer| GetWrite {
index: key,
write: writer,
created: location,
})
.into()
}
}
/// A specific index in a `Readable` / `Writable` hashmap
#[derive(Clone, Copy)]
pub struct GetWrite<Index, Write> {
index: Index,
write: Write,
created: &'static Location<'static>,
}
impl<Index, Write, K, V, St> Readable for GetWrite<Index, Write>
where
Write: Readable<Target = HashMap<K, V, St>>,
Index: Hash + Eq + 'static,
K: Borrow<Index> + Eq + Hash + 'static,
St: BuildHasher + 'static,
{
type Target = V;
type Storage = Write::Storage;
fn try_read_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_read_unchecked().and_then(|value| {
Self::Storage::try_map(value, |value: &Write::Target| value.get(&self.index))
.ok_or_else(|| BorrowError::Dropped(ValueDroppedError::new(self.created)))
})
}
fn try_peek_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_peek_unchecked().and_then(|value| {
Self::Storage::try_map(value, |value: &Write::Target| value.get(&self.index))
.ok_or_else(|| BorrowError::Dropped(ValueDroppedError::new(self.created)))
})
}
fn subscribers(&self) -> dioxus_core::Subscribers
where
Self::Target: 'static,
{
self.write.subscribers()
}
}
impl<Index, Write, K, V, St> Writable for GetWrite<Index, Write>
where
Write: Writable<Target = HashMap<K, V, St>>,
Index: Hash + Eq + 'static,
K: Borrow<Index> + Eq + Hash + 'static,
St: BuildHasher + 'static,
{
type WriteMetadata = Write::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<dioxus_signals::WritableRef<'static, Self>, BorrowMutError>
where
Self::Target: 'static,
{
self.write.try_write_unchecked().and_then(|value| {
WriteLock::filter_map(value, |value: &mut Write::Target| {
value.get_mut(&self.index)
})
.ok_or_else(|| BorrowMutError::Dropped(ValueDroppedError::new(self.created)))
})
}
}
impl<Index, Write, K, V, St> ::std::convert::From<Store<V, GetWrite<Index, Write>>>
for Store<V, WriteSignal<V>>
where
Write::WriteMetadata: 'static,
Write: Writable<Target = HashMap<K, V, St>, Storage = UnsyncStorage> + 'static,
Index: Hash + Eq + 'static,
K: Borrow<Index> + Eq + Hash + 'static,
St: BuildHasher + 'static,
V: 'static,
{
fn from(value: Store<V, GetWrite<Index, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| WriteSignal::new(writer))
.into()
}
}
impl<Index, Write, K, V, St> ::std::convert::From<Store<V, GetWrite<Index, Write>>> for ReadStore<V>
where
Write: Readable<Target = HashMap<K, V, St>, Storage = UnsyncStorage> + 'static,
Index: Hash + Eq + 'static,
K: Borrow<Index> + Eq + Hash + 'static,
St: BuildHasher + 'static,
V: 'static,
{
fn from(value: Store<V, GetWrite<Index, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| ReadSignal::new(writer))
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.