feat: inline dioxus-native from blitz (#3675)

* Rename dioxus-blitz to dioxus-native

* Add CSS import support (#139)

* Remove data dependencie from NetProvider + global provider.

* Feat CSS import

* Move net handler code out of util

* Fixing test...

* Use the better suited OnceLock instead of LazyLock

* Removing static and move resource callback back out of the document.

Signed-off-by: koko <kokos.kekse@gmail.com>

* Make things work

Signed-off-by: koko <kokos.kekse@gmail.com>

* Fix the servo example

Signed-off-by: koko <kokos.kekse@gmail.com>

* Replace servo image with a more compact version

Signed-off-by: koko <kokos.kekse@gmail.com>

* revert: 8467b271

Signed-off-by: koko <kokos.kekse@gmail.com>

---------

Signed-off-by: koko <kokos.kekse@gmail.com>

* Create readme app

* WPT: reuse FontContext to avoid reloading system fonts

Takes runtime for css-flexbox from 12s -> 8s

* Move Devtools to traits crate

* Suppress unused variable warning

* Implement net for DioxusDocument

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Eliminate BlitzWindowEvent type

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Make net crate use document id instead of window id

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename and document net traits

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Split `dioxus-native` crate into `dioxus-native` and `blitz-shell` crates (#163)

* Rename waker module to event

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Create seperate DioxusNativeApplication

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename dioxus-native crate to blitz-shell

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Split blitz-shell out of dioxus-native crate

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Remove need for dioxus-native to depend directly on stylo

---------

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Unnest dioxus-native modules

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Split MutationWriter into it's own module

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Split HtmlDocument into it's own crate

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename dom field of Window to doc

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Support prefers-color-scheme (dark mode)

* Remove use of the `todo` macro in event handling and add a comment about it being a todo (#168)

Using the `todo` macro causes a panic when this event is encountered. Noop is preferable in this case as it does not crash the application. This is especially annoying on platforms where `Ime::Enabled` event is sent upon application start even when the user is using a keyboard layout that does not need an IME support. There was added a "TODO" comment that informs about this feature being missing. Most IDEs and code editors have support/plugins/extensions to work with this type of comments and this type of comment is already used widely across the codebase. As such, the information about this feature not being implemented is not lost.

* Upgrade to dioxus 0.6-rc.0

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Fix text input in dioxus-native

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Make dioxus-native depend dioxus-core and dioxus-html rather than dioxus

* Remove "full" feature from tokio

* Move Viewport to blitz_traits

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Make tokio optional in dioxus-native and blitz-shell

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Make SVG support optional

* Abstract renderer behind a trait

blitz-shell no longer depends on blitz-renderer-vello

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Split HTML launch functions out in `blitz` crate

* feat: Add mousedown and mouseup event (#172)

* feat: Add mousedown and mouseup event

* feat: Triggering :active pseudo-class

* fix: Triggering :active pseudo-class

* Rename RendererEvent to DomEvent

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename Document to BaseDocument. DocumentLike to Document

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Move event and document abstractions to blitz-traits

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename BlitzEvent to BlitzShellEvent

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Restyle when style attribute is mutated

* feat: Support text box mouse selection (#182)

* Rename raw_dom_data to data

Signed-off-by: Nico Burns <nico@nicoburns.com>

* Rename dioxus-native to native

* Add to workspace

* simplify launch module, integrate native

* Fix it up again

* Update cargo lock

* FIx: propagate accessibility feature fla

* implement asset resolver

* add native to feature match in cli

* Implement document and history for native

* use no-op eval

* clippy

* typos

* typo

* Convert logs to trace

* Bump blitz to alpha releases

* unset image data

* fix style integration with blitz

* fix a few lints

* wire up ids

* implement a few more events

* add more helpful todo note

* bump ci to allow edition 2024, use newer nightly

* make clippy happy

* also update matrix tests to rust 2024

* Add autofocus

Co-authored-by: otgerrogla 2356820+otgerrogla@users.noreply.github.com

* Wait for the suspense boundary above the router to resolve before sending the first streaming chunk (#3891)

* Change the suspense streaming context after suspense is resolved in the router

* Wait for the suspense context before streaming the first chunk in ssr

* forward more response parts

* warn

* extract the hydration format into a crate

* Fix hydration when no data is sent

* forward web and server features

* Fix suspense that starts on the client

* fix use_server_future on the client

* Add documentation for fullstack hooks and protocol

* downgrade rust edition

* fix clippy

* fix tests

* fix clippy

* Fix pure web compile

* undo changes to the fullstack router example

* fix formatting

* hoist a bunch of deps

---------

Signed-off-by: koko <kokos.kekse@gmail.com>
Signed-off-by: Nico Burns <nico@nicoburns.com>
Co-authored-by: Nico Burns <nico@nicoburns.com>
Co-authored-by: koko <72217393+kokoISnoTarget@users.noreply.github.com>
Co-authored-by: David Husička <25853767+DavidHusicka@users.noreply.github.com>
Co-authored-by: luoxiaozero <48741584+luoxiaozero@users.noreply.github.com>
Co-authored-by: Evan Almloff <evanalmloff@gmail.com>
This commit is contained in:
Jonathan Kelleyotgerrogla 2356820+otgerrogla@users.noreply.github.comNico BurnskokoDavid HusičkaluoxiaozeroEvan Almloff
authored and GitHub committed 2025-04-08 17:30:49 -07:00
1 parent 84221f55a0
commit 12c6938346
38 files changed
+6156 -2087

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
use blitz_shell::BlitzShellNetCallback;
use std::sync::Arc;
use blitz_dom::{
net::{CssHandler, ImageHandler, Resource},
util::ImageType,
BaseDocument,
};
use blitz_shell::BlitzShellEvent;
use blitz_traits::net::{NetCallback, NetProvider};
use winit::event_loop::EventLoopProxy;
use crate::NodeId;
pub struct DioxusNativeNetProvider {
callback: Arc<dyn NetCallback<Data = Resource> + 'static>,
inner_net_provider: Arc<dyn NetProvider<Data = Resource> + 'static>,
}
impl DioxusNativeNetProvider {
pub fn shared(proxy: EventLoopProxy<BlitzShellEvent>) -> Arc<dyn NetProvider<Data = Resource>> {
Arc::new(Self::new(proxy)) as Arc<dyn NetProvider<Data = Resource>>
}
pub fn new(proxy: EventLoopProxy<BlitzShellEvent>) -> Self {
let net_callback = BlitzShellNetCallback::shared(proxy);
let net_provider = blitz_net::Provider::shared(net_callback.clone());
Self {
callback: net_callback,
inner_net_provider: net_provider,
}
}
}
impl NetProvider for DioxusNativeNetProvider {
type Data = Resource;
fn fetch(
&self,
doc_id: usize,
request: blitz_traits::net::Request,
handler: blitz_traits::net::BoxedHandler<Self::Data>,
) {
if request.url.scheme() == "dioxus" {
match dioxus_asset_resolver::serve_asset_from_raw_path(request.url.path()) {
Ok(res) => {
tracing::trace!("fetching asset from file system success {request:#?}");
handler.bytes(doc_id, res.into_body().into(), self.callback.clone())
}
Err(_) => {
tracing::warn!("fetching asset from file system error {request:#?}");
}
}
} else {
self.inner_net_provider.fetch(doc_id, request, handler);
}
}
}
pub fn fetch_linked_stylesheet(doc: &BaseDocument, node_id: NodeId, queued_url: String) {
let url = doc.resolve_url(&queued_url);
doc.net_provider.fetch(
doc.id(),
blitz_traits::net::Request::get(url.clone()),
Box::new(CssHandler {
node: node_id,
source_url: url,
guard: doc.guard.clone(),
provider: doc.net_provider.clone(),
}),
);
}
pub fn fetch_image(doc: &BaseDocument, node_id: usize, queued_image: String) {
let src = doc.resolve_url(&queued_image);
doc.net_provider.fetch(
doc.id(),
blitz_traits::net::Request::get(src),
Box::new(ImageHandler::new(node_id, ImageType::Image)),
);
}
+70
View File
@@ -0,0 +1,70 @@
use blitz_shell::BlitzShellEvent;
use dioxus_document::{Document, NoOpDocument};
use winit::{event_loop::EventLoopProxy, window::WindowId};
use crate::DioxusNativeEvent;
pub struct DioxusNativeDocument {
pub(crate) proxy: EventLoopProxy<BlitzShellEvent>,
pub(crate) window: WindowId,
}
impl DioxusNativeDocument {
pub(crate) fn new(proxy: EventLoopProxy<BlitzShellEvent>, window: WindowId) -> Self {
Self { proxy, window }
}
}
impl Document for DioxusNativeDocument {
fn eval(&self, _js: String) -> dioxus_document::Eval {
NoOpDocument.eval(_js)
}
fn create_head_element(
&self,
name: &str,
attributes: &[(&str, String)],
contents: Option<String>,
) {
let window = self.window;
_ = self.proxy.send_event(BlitzShellEvent::embedder_event(
DioxusNativeEvent::CreateHeadElement {
name: name.to_string(),
attributes: attributes
.iter()
.map(|(name, value)| (name.to_string(), value.clone()))
.collect(),
contents,
window,
},
));
}
fn set_title(&self, title: String) {
self.create_head_element("title", &[], Some(title));
}
fn create_meta(&self, props: dioxus_document::MetaProps) {
let attributes = props.attributes();
self.create_head_element("meta", &attributes, None);
}
fn create_script(&self, props: dioxus_document::ScriptProps) {
let attributes = props.attributes();
self.create_head_element("script", &attributes, props.script_contents().ok());
}
fn create_style(&self, props: dioxus_document::StyleProps) {
let attributes = props.attributes();
self.create_head_element("style", &attributes, props.style_contents().ok());
}
fn create_link(&self, props: dioxus_document::LinkProps) {
let attributes = props.attributes();
self.create_head_element("link", &attributes, None);
}
fn create_head_component(&self) -> bool {
true
}
}
+166
View File
@@ -0,0 +1,166 @@
use blitz_renderer_vello::BlitzVelloRenderer;
use blitz_shell::BlitzApplication;
use dioxus_core::{ScopeId, VirtualDom};
use dioxus_history::{History, MemoryHistory};
use std::{collections::HashSet, rc::Rc};
use winit::application::ApplicationHandler;
use winit::event::{StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoopProxy};
use winit::window::WindowId;
use crate::{
assets::DioxusNativeNetProvider, contexts::DioxusNativeDocument,
mutation_writer::MutationWriter, BlitzShellEvent, DioxusDocument, DioxusNativeEvent,
WindowConfig,
};
pub struct DioxusNativeApplication {
pending_vdom: Option<VirtualDom>,
inner: BlitzApplication<DioxusDocument, BlitzVelloRenderer>,
proxy: EventLoopProxy<BlitzShellEvent>,
}
impl DioxusNativeApplication {
pub fn new(proxy: EventLoopProxy<BlitzShellEvent>, vdom: VirtualDom) -> Self {
Self {
pending_vdom: Some(vdom),
inner: BlitzApplication::new(proxy.clone()),
proxy,
}
}
pub fn add_window(&mut self, window_config: WindowConfig<DioxusDocument, BlitzVelloRenderer>) {
self.inner.add_window(window_config);
}
fn handle_blitz_shell_event(
&mut self,
event_loop: &ActiveEventLoop,
event: &DioxusNativeEvent,
) {
match event {
#[cfg(all(
feature = "hot-reload",
debug_assertions,
not(target_os = "android"),
not(target_os = "ios")
))]
DioxusNativeEvent::DevserverEvent(event) => match event {
dioxus_devtools::DevserverMsg::HotReload(hotreload_message) => {
for window in self.inner.windows.values_mut() {
dioxus_devtools::apply_changes(&window.doc.vdom, hotreload_message);
window.poll();
}
}
dioxus_devtools::DevserverMsg::Shutdown => event_loop.exit(),
dioxus_devtools::DevserverMsg::FullReloadStart => {}
dioxus_devtools::DevserverMsg::FullReloadFailed => {}
dioxus_devtools::DevserverMsg::FullReloadCommand => {}
},
DioxusNativeEvent::CreateHeadElement {
name,
attributes,
contents,
window,
} => {
if let Some(window) = self.inner.windows.get_mut(window) {
window.doc.create_head_element(name, attributes, contents);
window.poll();
}
}
// Suppress unused variable warning
#[cfg(not(all(
feature = "hot-reload",
debug_assertions,
not(target_os = "android"),
not(target_os = "ios")
)))]
_ => {
let _ = event_loop;
let _ = event;
}
}
}
}
impl ApplicationHandler<BlitzShellEvent> for DioxusNativeApplication {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
tracing::debug!("Injecting document provider into all windows");
let vdom = self.pending_vdom.take().unwrap();
#[cfg(feature = "net")]
let net_provider = {
let proxy = self.proxy.clone();
let net_provider = DioxusNativeNetProvider::shared(proxy);
Some(net_provider)
};
#[cfg(not(feature = "net"))]
let net_provider = None;
// Create document + window from the baked virtualdom
let doc = DioxusDocument::new(vdom, net_provider);
let window = WindowConfig::new(doc);
// little hack since View::init is not public - fix this once alpha-2 is out
let old_windows = self.inner.windows.keys().copied().collect::<HashSet<_>>();
self.add_window(window);
self.inner.resumed(event_loop);
let new_windows = self.inner.windows.keys().cloned().collect::<HashSet<_>>();
// todo(jon): we should actually mess with the pending windows instead of passing along the contexts
for window_id in new_windows.difference(&old_windows) {
let window = self.inner.windows.get_mut(window_id).unwrap();
window.doc.vdom.in_runtime(|| {
let shared: Rc<dyn dioxus_document::Document> =
Rc::new(DioxusNativeDocument::new(self.proxy.clone(), *window_id));
ScopeId::ROOT.provide_context(shared);
});
// Add history
let history_provider: Rc<dyn History> = Rc::new(MemoryHistory::default());
window
.doc
.vdom
.in_runtime(|| ScopeId::ROOT.provide_context(history_provider));
// Queue rebuild
let mut writer = MutationWriter::new(&mut window.doc.inner, &mut window.doc.vdom_state);
window.doc.vdom.rebuild(&mut writer);
drop(writer);
// And then request redraw
window.request_redraw();
}
}
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
self.inner.suspended(event_loop);
}
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
self.inner.new_events(event_loop, cause);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
self.inner.window_event(event_loop, window_id, event);
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: BlitzShellEvent) {
match event {
BlitzShellEvent::Embedder(event) => {
if let Some(event) = event.downcast_ref::<DioxusNativeEvent>() {
self.handle_blitz_shell_event(event_loop, event);
}
}
event => self.inner.user_event(event_loop, event),
}
}
}
+564
View File
@@ -0,0 +1,564 @@
//! Integration between Dioxus and Blitz
use std::{any::Any, collections::HashMap, rc::Rc, sync::Arc};
use blitz_dom::{
local_name, namespace_url,
net::Resource,
node::{Attribute, NodeSpecificData},
ns, Atom, BaseDocument, ElementNodeData, Node, NodeData, QualName, DEFAULT_CSS,
};
use blitz_traits::{net::NetProvider, ColorScheme, Document, DomEvent, DomEventData, Viewport};
use dioxus_core::{ElementId, Event, VirtualDom};
use dioxus_html::{set_event_converter, FormValue, PlatformEventData};
use futures_util::{pin_mut, FutureExt};
use super::event_handler::{BlitzKeyboardData, NativeClickData, NativeConverter, NativeFormData};
use crate::mutation_writer::{DioxusState, MutationWriter};
use crate::NodeId;
pub(crate) fn qual_name(local_name: &str, namespace: Option<&str>) -> QualName {
QualName {
prefix: None,
ns: namespace.map(Atom::from).unwrap_or(ns!(html)),
local: Atom::from(local_name),
}
}
pub struct DioxusDocument {
pub(crate) vdom: VirtualDom,
pub(crate) vdom_state: DioxusState,
pub(crate) inner: BaseDocument,
#[allow(unused)]
pub(crate) html_element_id: NodeId,
#[allow(unused)]
pub(crate) head_element_id: NodeId,
#[allow(unused)]
pub(crate) body_element_id: NodeId,
#[allow(unused)]
pub(crate) main_element_id: NodeId,
}
// Implement DocumentLike and required traits for DioxusDocument
impl AsRef<BaseDocument> for DioxusDocument {
fn as_ref(&self) -> &BaseDocument {
&self.inner
}
}
impl AsMut<BaseDocument> for DioxusDocument {
fn as_mut(&mut self) -> &mut BaseDocument {
&mut self.inner
}
}
impl From<DioxusDocument> for BaseDocument {
fn from(doc: DioxusDocument) -> BaseDocument {
doc.inner
}
}
impl Document for DioxusDocument {
type Doc = BaseDocument;
fn poll(&mut self, mut cx: std::task::Context) -> bool {
{
let fut = self.vdom.wait_for_work();
pin_mut!(fut);
match fut.poll_unpin(&mut cx) {
std::task::Poll::Ready(_) => {}
std::task::Poll::Pending => return false,
}
}
let mut writer = MutationWriter::new(&mut self.inner, &mut self.vdom_state);
self.vdom.render_immediate(&mut writer);
true
}
fn id(&self) -> usize {
self.inner.id()
}
fn handle_event(&mut self, event: &mut DomEvent) {
let chain = self.inner.node_chain(event.target);
set_event_converter(Box::new(NativeConverter {}));
let renderer_event = event.clone();
let mut prevent_default = false;
let mut stop_propagation = false;
match &event.data {
DomEventData::MouseMove(data)
| DomEventData::MouseDown(data)
| DomEventData::MouseUp(data) => {
let click_event_data = wrap_event_data(NativeClickData(data.clone()));
for node_id in chain.clone().into_iter() {
let node = &self.inner.tree()[node_id];
let dioxus_id = node.element_data().and_then(DioxusDocument::dioxus_id);
if let Some(id) = dioxus_id {
let click_event = Event::new(click_event_data.clone(), true);
self.vdom
.runtime()
.handle_event(event.name(), click_event.clone(), id);
prevent_default |= !click_event.default_action_enabled();
stop_propagation |= !click_event.propagates();
}
if !event.bubbles || stop_propagation {
break;
}
}
}
DomEventData::Click(data) => {
let click_event_data = wrap_event_data(NativeClickData(data.clone()));
for node_id in chain.clone().into_iter() {
let node = &self.inner.tree()[node_id];
let dioxus_id = node.element_data().and_then(DioxusDocument::dioxus_id);
let mut trigger_label = false;
if let Some(id) = dioxus_id {
// Trigger click event
let click_event = Event::new(click_event_data.clone(), true);
self.vdom
.runtime()
.handle_event("click", click_event.clone(), id);
prevent_default |= !click_event.default_action_enabled();
stop_propagation |= !click_event.propagates();
if !prevent_default {
let mut default_event =
DomEvent::new(node_id, renderer_event.data.clone());
self.inner.as_mut().handle_event(&mut default_event);
prevent_default = true;
let element = self.inner.tree()[node_id].element_data().unwrap();
trigger_label = element.name.local == *"label";
//TODO Check for other inputs which trigger input event on click here, eg radio
let triggers_input_event = element.name.local == local_name!("input")
&& element.attr(local_name!("type")) == Some("checkbox");
if triggers_input_event {
let form_data =
wrap_event_data(self.input_event_form_data(&chain, element));
let input_event = Event::new(form_data, true);
self.vdom.runtime().handle_event("input", input_event, id);
}
}
}
//Clicking labels triggers click, and possibly input event, of bound input
if trigger_label {
if let Some((dioxus_id, node_id)) = self.label_bound_input_element(node_id)
{
let click_event = Event::new(click_event_data.clone(), true);
self.vdom.runtime().handle_event(
"click",
click_event.clone(),
dioxus_id,
);
// Handle default DOM event
if click_event.default_action_enabled() {
let DomEventData::Click(event) = &renderer_event.data else {
unreachable!();
};
let input_click_data = self
.inner
.get_node(node_id)
.unwrap()
.synthetic_click_event(event.mods);
let mut default_event = DomEvent::new(node_id, input_click_data);
self.inner.as_mut().handle_event(&mut default_event);
prevent_default = true;
// TODO: Generated click events should bubble separately
// prevent_default |= !click_event.default_action_enabled();
//TODO Check for other inputs which trigger input event on click here, eg radio
let element_data = self
.inner
.get_node(node_id)
.unwrap()
.element_data()
.unwrap();
let triggers_input_event =
element_data.attr(local_name!("type")) == Some("checkbox");
let form_data = wrap_event_data(
self.input_event_form_data(&chain, element_data),
);
if triggers_input_event {
let input_event = Event::new(form_data, true);
self.vdom.runtime().handle_event(
"input",
input_event,
dioxus_id,
);
}
}
}
}
if !event.bubbles || stop_propagation {
break;
}
}
}
DomEventData::KeyPress(kevent) => {
let key_event_data = wrap_event_data(BlitzKeyboardData(kevent.clone()));
for node_id in chain.clone().into_iter() {
let node = &self.inner.tree()[node_id];
let dioxus_id = node.element_data().and_then(DioxusDocument::dioxus_id);
println!("{} {:?}", node_id, dioxus_id);
if let Some(id) = dioxus_id {
if kevent.state.is_pressed() {
// Handle keydown event
let event = Event::new(key_event_data.clone(), true);
self.vdom
.runtime()
.handle_event("keydown", event.clone(), id);
prevent_default |= !event.default_action_enabled();
stop_propagation |= !event.propagates();
if !prevent_default && kevent.text.is_some() {
// Handle keypress event
let event = Event::new(key_event_data.clone(), true);
self.vdom
.runtime()
.handle_event("keypress", event.clone(), id);
prevent_default |= !event.default_action_enabled();
stop_propagation |= !event.propagates();
if !prevent_default {
// Handle default DOM event
let mut default_event =
DomEvent::new(node_id, renderer_event.data.clone());
self.inner.as_mut().handle_event(&mut default_event);
prevent_default = true;
// Handle input event
let element =
self.inner.tree()[node_id].element_data().unwrap();
let triggers_input_event = &element.name.local == "input"
&& matches!(
element.attr(local_name!("type")),
None | Some("text" | "password" | "email" | "search")
);
if triggers_input_event {
let form_data = wrap_event_data(dbg!(
self.input_event_form_data(&chain, element)
));
let input_event = Event::new(form_data, true);
self.vdom.runtime().handle_event("input", input_event, id);
}
}
}
} else {
// Handle keyup event
let event = Event::new(key_event_data.clone(), true);
self.vdom.runtime().handle_event("keyup", event.clone(), id);
prevent_default |= !event.default_action_enabled();
stop_propagation |= !event.propagates();
}
}
if !event.bubbles || stop_propagation {
break;
}
}
}
DomEventData::Hover => {}
// TODO: Implement IME and Hover events handling
DomEventData::Ime(_) => {}
}
if !event.cancelable || !prevent_default {
self.inner.as_mut().handle_event(event);
}
}
}
fn wrap_event_data<T: Any>(value: T) -> Rc<dyn Any> {
Rc::new(PlatformEventData::new(Box::new(value)))
}
impl DioxusDocument {
/// Generate the FormData from an input event
/// Currently only cares about input checkboxes
pub fn input_event_form_data(
&self,
parent_chain: &[usize],
element_node_data: &ElementNodeData,
) -> NativeFormData {
let parent_form = parent_chain.iter().find_map(|id| {
let node = self.inner.get_node(*id)?;
let element_data = node.element_data()?;
if element_data.name.local == local_name!("form") {
Some(node)
} else {
None
}
});
let values = if let Some(parent_form) = parent_form {
let mut values = HashMap::<String, FormValue>::new();
for form_input in self.input_descendents(parent_form).into_iter() {
// Match html behaviour here. To be included in values:
// - input must have a name
// - if its an input, we only include it if checked
// - if value is not specified, it defaults to 'on'
if let Some(name) = form_input.attr(local_name!("name")) {
if form_input.attr(local_name!("type")) == Some("checkbox")
&& form_input
.element_data()
.and_then(|data| data.checkbox_input_checked())
.unwrap_or(false)
{
let value = form_input
.attr(local_name!("value"))
.unwrap_or("on")
.to_string();
values.insert(name.to_string(), FormValue(vec![value]));
}
}
}
values
} else {
Default::default()
};
let value = match &element_node_data.node_specific_data {
NodeSpecificData::CheckboxInput(checked) => checked.to_string(),
NodeSpecificData::TextInput(input_data) => input_data.editor.text().to_string(),
_ => element_node_data
.attr(local_name!("value"))
.unwrap_or_default()
.to_string(),
};
NativeFormData { value, values }
}
/// Collect all the inputs which are descendents of a given node
fn input_descendents(&self, node: &Node) -> Vec<&Node> {
node.children
.iter()
.flat_map(|id| {
let mut res = Vec::<&Node>::new();
let Some(n) = self.inner.get_node(*id) else {
return res;
};
let Some(element_data) = n.element_data() else {
return res;
};
if element_data.name.local == local_name!("input") {
res.push(n);
}
res.extend(self.input_descendents(n).iter());
res
})
.collect()
}
pub fn new(
vdom: VirtualDom,
net_provider: Option<Arc<dyn NetProvider<Data = Resource>>>,
) -> Self {
let viewport = Viewport::new(0, 0, 1.0, ColorScheme::Light);
let mut doc = BaseDocument::new(viewport);
// Set net provider
if let Some(net_provider) = net_provider {
doc.set_net_provider(net_provider);
}
// Create a virtual "html" element to act as the root element, as we won't necessarily
// have a single root otherwise, while the rest of blitz requires that we do
let html_element_id = doc.create_node(NodeData::Element(ElementNodeData::new(
qual_name("html", None),
Vec::new(),
)));
let root_node_id = doc.root_node().id;
let html_element = doc.get_node_mut(html_element_id).unwrap();
html_element.parent = Some(root_node_id);
let root_node = doc.get_node_mut(root_node_id).unwrap();
root_node.children.push(html_element_id);
// Create the body element
let body_element_id = doc.create_node(NodeData::Element(ElementNodeData::new(
qual_name("body", None),
Vec::new(),
)));
let html_element = doc.get_node_mut(html_element_id).unwrap();
html_element.children.push(body_element_id);
let body_element = doc.get_node_mut(body_element_id).unwrap();
body_element.parent = Some(html_element_id);
// Create another virtual element to hold the root <div id="main"></div> under the html element
let main_element_id = doc.create_node(NodeData::Element(ElementNodeData::new(
qual_name("div", Some("id")),
vec![blitz_dom::node::Attribute {
name: qual_name("id", None),
value: "main".to_string(),
}],
)));
let body_element = doc.get_node_mut(body_element_id).unwrap();
body_element.children.push(main_element_id);
let main_element = doc.get_node_mut(main_element_id).unwrap();
main_element.parent = Some(body_element_id);
// Create the head element
let head_element_id = doc.create_node(NodeData::Element(ElementNodeData::new(
qual_name("head", None),
Vec::new(),
)));
let head_element = doc.get_node_mut(head_element_id).unwrap();
head_element.parent = Some(html_element_id);
let html_element = doc.get_node_mut(html_element_id).unwrap();
html_element.children.push(head_element_id);
// Include default and user-specified stylesheets
doc.add_user_agent_stylesheet(DEFAULT_CSS);
let state = DioxusState::create(&mut doc, main_element_id);
let mut doc = Self {
vdom,
vdom_state: state,
inner: doc,
html_element_id,
head_element_id,
body_element_id,
main_element_id,
};
doc.inner.set_base_url("dioxus://index.html");
// doc.initial_build();
// doc.inner.print_tree();
doc
}
pub fn initial_build(&mut self) {
// let mut writer = MutationWriter::new(&mut self.inner, &mut self.vdom_state);
// self.vdom.rebuild(&mut writer);
// dbg!(self.vdom.rebuild_to_vec());
// std::process::exit(0);
// dbg!(writer.state);
}
pub fn label_bound_input_element(&self, label_node_id: NodeId) -> Option<(ElementId, NodeId)> {
let bound_input_elements = self.inner.label_bound_input_elements(label_node_id);
// Filter down bound elements to those which have dioxus id
bound_input_elements.into_iter().find_map(|n| {
let target_element_data = n.element_data()?;
let node_id = n.id;
let dioxus_id = DioxusDocument::dioxus_id(target_element_data)?;
Some((dioxus_id, node_id))
})
}
fn dioxus_id(element_node_data: &ElementNodeData) -> Option<ElementId> {
Some(ElementId(
element_node_data
.attrs
.iter()
.find(|attr| *attr.name.local == *"data-dioxus-id")?
.value
.parse::<usize>()
.ok()?,
))
}
pub fn create_head_element(
&mut self,
name: &str,
attributes: &[(String, String)],
contents: &Option<String>,
) {
let mut stylesheet = None;
let mut title = None;
if name == "link" {
let is_stylesheet = attributes
.iter()
.any(|(name, value)| name == "rel" && value == "stylesheet");
if is_stylesheet {
stylesheet = attributes
.iter()
.find(|(name, _value)| name == "href")
.map(|(_name, value)| value.clone());
}
}
if name == "title" {
title = attributes
.iter()
.find(|(name, _value)| name == "text")
.and_then(|(_name, _value)| contents.clone());
}
let attributes = attributes
.iter()
.map(|(name, value)| Attribute {
name: qual_name(name, None),
value: value.clone(),
})
.collect();
let new_element = self
.inner
.create_node(NodeData::Element(ElementNodeData::new(
qual_name(name, None),
attributes,
)));
if let Some(contents) = contents {
let text_node = self.inner.create_text_node(contents);
self.inner
.get_node_mut(new_element)
.unwrap()
.children
.push(text_node);
}
self.inner
.get_node_mut(self.head_element_id)
.unwrap()
.children
.push(new_element);
if let Some(url) = stylesheet {
crate::assets::fetch_linked_stylesheet(&self.inner, new_element, url);
}
if let Some(_title) = title {
println!("todo: set title");
}
}
// pub fn apply_mutations(&mut self) {
// // Apply the mutations to the actual dom
// let mut writer = MutationWriter {
// doc: &mut self.inner,
// state: &mut self.vdom_state,
// };
// self.vdom.render_immediate(&mut writer);
// println!("APPLY MUTATIONS");
// self.inner.print_tree();
// }
}
+23
View File
@@ -0,0 +1,23 @@
use winit::window::WindowId;
/// Dioxus-native specific event type
pub enum DioxusNativeEvent {
/// A hotreload event, basically telling us to update our templates.
#[cfg(all(
feature = "hot-reload",
debug_assertions,
not(target_os = "android"),
not(target_os = "ios")
))]
DevserverEvent(dioxus_devtools::DevserverMsg),
/// Create a new head element from the Link and Title elements
///
/// todo(jon): these should probabkly be synchronous somehow
CreateHeadElement {
window: WindowId,
name: String,
attributes: Vec<(String, String)>,
contents: Option<String>,
},
}
+220
View File
@@ -0,0 +1,220 @@
use blitz_traits::{BlitzKeyEvent, BlitzMouseButtonEvent, MouseEventButton};
use dioxus_html::{
geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint},
input_data::{MouseButton, MouseButtonSet},
point_interaction::{
InteractionElementOffset, InteractionLocation, ModifiersInteraction, PointerInteraction,
},
AnimationData, ClipboardData, CompositionData, DragData, FocusData, FormData, FormValue,
HasFileData, HasFormData, HasMouseData, HtmlEventConverter, ImageData, KeyboardData, MediaData,
MountedData, MouseData, PlatformEventData, PointerData, ResizeData, ScrollData, SelectionData,
ToggleData, TouchData, TransitionData, VisibleData, WheelData,
};
use dioxus_html::{HasFocusData, HasKeyboardData};
use keyboard_types::{Code, Key, Location, Modifiers};
use std::any::Any;
use std::collections::HashMap;
pub struct NativeConverter {}
impl HtmlEventConverter for NativeConverter {
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
event.downcast::<NativeFormData>().unwrap().clone().into()
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
event.downcast::<NativeClickData>().unwrap().clone().into()
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
event
.downcast::<BlitzKeyboardData>()
.unwrap()
.clone()
.into()
}
fn convert_focus_data(&self, _event: &PlatformEventData) -> FocusData {
NativeFocusData {}.into()
}
fn convert_animation_data(&self, _event: &PlatformEventData) -> AnimationData {
todo!("todo: convert_animation_data in dioxus-native. requires support in blitz")
}
fn convert_clipboard_data(&self, _event: &PlatformEventData) -> ClipboardData {
todo!("todo: convert_clipboard_data in dioxus-native. requires support in blitz")
}
fn convert_composition_data(&self, _event: &PlatformEventData) -> CompositionData {
todo!("todo: convert_composition_data in dioxus-native. requires support in blitz")
}
fn convert_drag_data(&self, _event: &PlatformEventData) -> DragData {
todo!("todo: convert_drag_data in dioxus-native. requires support in blitz")
}
fn convert_image_data(&self, _event: &PlatformEventData) -> ImageData {
todo!("todo: convert_image_data in dioxus-native. requires support in blitz")
}
fn convert_media_data(&self, _event: &PlatformEventData) -> MediaData {
todo!("todo: convert_media_data in dioxus-native. requires support in blitz")
}
fn convert_mounted_data(&self, _event: &PlatformEventData) -> MountedData {
todo!("todo: convert_mounted_data in dioxus-native. requires support in blitz")
}
fn convert_pointer_data(&self, _event: &PlatformEventData) -> PointerData {
todo!("todo: convert_pointer_data in dioxus-native. requires support in blitz")
}
fn convert_scroll_data(&self, _event: &PlatformEventData) -> ScrollData {
todo!("todo: convert_scroll_data in dioxus-native. requires support in blitz")
}
fn convert_selection_data(&self, _event: &PlatformEventData) -> SelectionData {
todo!("todo: convert_selection_data in dioxus-native. requires support in blitz")
}
fn convert_toggle_data(&self, _event: &PlatformEventData) -> ToggleData {
todo!("todo: convert_toggle_data in dioxus-native. requires support in blitz")
}
fn convert_touch_data(&self, _event: &PlatformEventData) -> TouchData {
todo!("todo: convert_touch_data in dioxus-native. requires support in blitz")
}
fn convert_transition_data(&self, _event: &PlatformEventData) -> TransitionData {
todo!("todo: convert_transition_data in dioxus-native. requires support in blitz")
}
fn convert_wheel_data(&self, _event: &PlatformEventData) -> WheelData {
todo!("todo: convert_wheel_data in dioxus-native. requires support in blitz")
}
fn convert_resize_data(&self, _event: &PlatformEventData) -> ResizeData {
todo!("todo: convert_resize_data in dioxus-native. requires support in blitz")
}
fn convert_visible_data(&self, _event: &PlatformEventData) -> VisibleData {
todo!("todo: convert_visible_data in dioxus-native. requires support in blitz")
}
}
#[derive(Clone, Debug)]
pub struct NativeFormData {
pub value: String,
pub values: HashMap<String, FormValue>,
}
impl HasFormData for NativeFormData {
fn as_any(&self) -> &dyn std::any::Any {
self as &dyn std::any::Any
}
fn value(&self) -> String {
self.value.clone()
}
fn values(&self) -> HashMap<String, FormValue> {
self.values.clone()
}
}
impl HasFileData for NativeFormData {}
#[derive(Clone, Debug)]
pub(crate) struct BlitzKeyboardData(pub(crate) BlitzKeyEvent);
impl ModifiersInteraction for BlitzKeyboardData {
fn modifiers(&self) -> Modifiers {
self.0.modifiers
}
}
impl HasKeyboardData for BlitzKeyboardData {
fn key(&self) -> Key {
self.0.key.clone()
}
fn code(&self) -> Code {
self.0.code
}
fn location(&self) -> Location {
self.0.location
}
fn is_auto_repeating(&self) -> bool {
self.0.is_auto_repeating
}
fn is_composing(&self) -> bool {
self.0.is_composing
}
fn as_any(&self) -> &dyn std::any::Any {
self as &dyn Any
}
}
#[derive(Clone)]
pub struct NativeClickData(pub(crate) BlitzMouseButtonEvent);
impl InteractionLocation for NativeClickData {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.0.x as _, self.0.y as _)
}
// these require blitz to pass them along, or a dom rect
fn screen_coordinates(&self) -> ScreenPoint {
unimplemented!()
}
fn page_coordinates(&self) -> PagePoint {
unimplemented!()
}
}
impl InteractionElementOffset for NativeClickData {
fn element_coordinates(&self) -> ElementPoint {
todo!()
}
}
impl ModifiersInteraction for NativeClickData {
fn modifiers(&self) -> Modifiers {
self.0.mods
}
}
impl PointerInteraction for NativeClickData {
fn trigger_button(&self) -> Option<MouseButton> {
Some(match self.0.button {
MouseEventButton::Main => MouseButton::Primary,
MouseEventButton::Auxiliary => MouseButton::Auxiliary,
MouseEventButton::Secondary => MouseButton::Secondary,
MouseEventButton::Fourth => MouseButton::Fourth,
MouseEventButton::Fifth => MouseButton::Fifth,
})
}
fn held_buttons(&self) -> MouseButtonSet {
dioxus_html::input_data::decode_mouse_button_set(self.0.buttons.bits() as u16)
}
}
impl HasMouseData for NativeClickData {
fn as_any(&self) -> &dyn std::any::Any {
self as &dyn std::any::Any
}
}
#[derive(Clone)]
pub struct NativeFocusData {}
impl HasFocusData for NativeFocusData {
fn as_any(&self) -> &dyn std::any::Any {
self as &dyn std::any::Any
}
}
+96
View File
@@ -0,0 +1,96 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
//! A native renderer for Dioxus.
//!
//! ## Feature flags
//! - `default`: Enables the features listed below.
//! - `accessibility`: Enables [`accesskit`] accessibility support.
//! - `hot-reload`: Enables hot-reloading of Dioxus RSX.
//! - `menu`: Enables the [`muda`] menubar.
//! - `tracing`: Enables tracing support.
mod assets;
mod contexts;
mod dioxus_application;
mod dioxus_document;
mod event;
mod event_handler;
mod mutation_writer;
pub use dioxus_application::DioxusNativeApplication;
pub use dioxus_document::DioxusDocument;
pub use event::DioxusNativeEvent;
use blitz_shell::{create_default_event_loop, BlitzShellEvent, Config, WindowConfig};
use dioxus_core::{ComponentFunction, Element, VirtualDom};
use std::any::Any;
type NodeId = usize;
/// Launch an interactive HTML/CSS renderer driven by the Dioxus virtualdom
pub fn launch(app: fn() -> Element) {
launch_cfg(app, vec![], vec![])
}
pub fn launch_cfg(
app: fn() -> Element,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
cfg: Vec<Box<dyn Any>>,
) {
launch_cfg_with_props(app, (), contexts, cfg)
}
// todo: props shouldn't have the clone bound - should try and match dioxus-desktop behavior
pub fn launch_cfg_with_props<P: Clone + 'static, M: 'static>(
app: impl ComponentFunction<P, M>,
props: P,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
_cfg: Vec<Box<dyn Any>>,
) {
let _cfg = _cfg
.into_iter()
.find_map(|cfg| cfg.downcast::<Config>().ok())
.unwrap_or_default();
let event_loop = create_default_event_loop::<BlitzShellEvent>();
// Turn on the runtime and enter it
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let _guard = rt.enter();
// Setup hot-reloading if enabled.
#[cfg(all(
feature = "hot-reload",
debug_assertions,
not(target_os = "android"),
not(target_os = "ios")
))]
{
use crate::event::DioxusNativeEvent;
if let Some(endpoint) = dioxus_cli_config::devserver_ws_endpoint() {
let proxy = event_loop.create_proxy();
dioxus_devtools::connect(endpoint, move |event| {
let dxn_event = DioxusNativeEvent::DevserverEvent(event);
let _ = proxy.send_event(BlitzShellEvent::embedder_event(dxn_event));
})
}
}
// Spin up the virtualdom
// We're going to need to hit it with a special waker
// Note that we are delaying the initialization of window-specific contexts (net provider, document, etc)
let mut vdom = VirtualDom::new_with_props(app, props);
// Add contexts
for context in contexts {
vdom.insert_any_root_context(context());
}
// Create application
let mut application = DioxusNativeApplication::new(event_loop.create_proxy(), vdom);
// Run event loop
event_loop.run_app(&mut application).unwrap();
}
+575
View File
@@ -0,0 +1,575 @@
use crate::{dioxus_document::qual_name, NodeId};
use blitz_dom::{
local_name, namespace_url,
node::{Attribute, NodeSpecificData},
ns, BaseDocument, ElementNodeData, NodeData, QualName, RestyleHint,
};
use dioxus_core::{
AttributeValue, ElementId, Template, TemplateAttribute, TemplateNode, WriteMutations,
};
use rustc_hash::FxHashMap;
use std::collections::HashSet;
/// The state of the Dioxus integration with the RealDom
#[derive(Debug)]
pub struct DioxusState {
/// Store of templates keyed by unique name
templates: FxHashMap<Template, Vec<NodeId>>,
/// Stack machine state for applying dioxus mutations
stack: Vec<NodeId>,
/// Mapping from vdom ElementId -> rdom NodeId
node_id_mapping: Vec<Option<NodeId>>,
}
/// A writer for mutations that can be used with the RealDom.
pub struct MutationWriter<'a> {
/// The realdom associated with this writer
pub doc: &'a mut BaseDocument,
/// The state associated with this writer
pub state: &'a mut DioxusState,
pub style_nodes: HashSet<usize>,
/// The (latest) node which has been mounted in and had autofocus=true, if any
#[cfg(feature = "autofocus")]
pub node_to_autofocus: Option<usize>,
}
impl<'a> MutationWriter<'a> {
pub fn new(doc: &'a mut BaseDocument, state: &'a mut DioxusState) -> Self {
MutationWriter {
doc,
state,
style_nodes: HashSet::new(),
#[cfg(feature = "autofocus")]
node_to_autofocus: None,
}
}
fn is_style_node(&self, node_id: NodeId) -> bool {
self.doc
.get_node(node_id)
.unwrap()
.data
.is_element_with_tag_name(&local_name!("style"))
}
fn maybe_push_style_node(&mut self, node_id: impl Into<Option<NodeId>>) {
if let Some(node_id) = node_id.into() {
if self.is_style_node(node_id) {
self.style_nodes.insert(node_id);
}
}
}
#[track_caller]
fn maybe_push_parent_style_node(&mut self, node_id: NodeId) {
let parent_id = self.doc.get_node(node_id).unwrap().parent;
self.maybe_push_style_node(parent_id);
}
}
impl Drop for MutationWriter<'_> {
fn drop(&mut self) {
// Add/Update inline stylesheets (<style> elements)
for &id in &self.style_nodes {
self.doc.upsert_stylesheet_for_node(id);
}
#[cfg(feature = "autofocus")]
if let Some(node_id) = self.node_to_autofocus {
if self.doc.get_node(node_id).is_some() {
self.doc.set_focus_to(node_id);
}
}
}
}
impl DioxusState {
/// Initialize the DioxusState in the RealDom
pub fn create(_doc: &mut BaseDocument, mount_node: NodeId) -> Self {
Self {
templates: FxHashMap::default(),
stack: vec![mount_node],
node_id_mapping: vec![Some(mount_node)],
}
}
/// Convert an ElementId to a NodeId
pub fn element_to_node_id(&self, element_id: ElementId) -> NodeId {
self.try_element_to_node_id(element_id).unwrap()
}
/// Attempt to convert an ElementId to a NodeId. This will return None if the ElementId is not in the RealDom.
pub fn try_element_to_node_id(&self, element_id: ElementId) -> Option<NodeId> {
self.node_id_mapping.get(element_id.0).copied().flatten()
}
}
impl MutationWriter<'_> {
/// Update an ElementId -> NodeId mapping
fn set_id_mapping(&mut self, node_id: NodeId, element_id: ElementId) {
let element_id: usize = element_id.0;
// Ensure node_id_mapping is large enough to contain element_id
if self.state.node_id_mapping.len() <= element_id {
self.state.node_id_mapping.resize(element_id + 1, None);
}
// Set the new mapping
self.state.node_id_mapping[element_id] = Some(node_id);
}
/// Find a child in the document by child index path
fn load_child(&self, path: &[u8]) -> NodeId {
let mut current = self
.doc
.get_node(*self.state.stack.last().unwrap())
.unwrap();
for i in path {
let new_id = current.children[*i as usize];
current = self.doc.get_node(new_id).unwrap();
}
current.id
}
fn create_template_node(&mut self, node: &TemplateNode) -> NodeId {
match node {
TemplateNode::Element {
tag,
namespace,
attrs,
children,
} => {
let name = qual_name(tag, *namespace);
let attrs = attrs
.iter()
.filter_map(|attr| match attr {
TemplateAttribute::Static {
name,
value,
namespace,
} => Some(Attribute {
name: qual_name(name, *namespace),
value: value.to_string(),
}),
TemplateAttribute::Dynamic { .. } => None,
})
.collect();
let mut data = ElementNodeData::new(name, attrs);
data.flush_style_attribute(self.doc.guard());
let child_ids: Vec<NodeId> = children
.iter()
.map(|child| self.create_template_node(child))
.collect();
let id = self.doc.create_node(NodeData::Element(data));
let node = self.doc.get_node(id).unwrap();
// Initialise style data
*node.stylo_element_data.borrow_mut() = Some(Default::default());
if let Some(src_attr) = node.attr(local_name!("src")) {
crate::assets::fetch_image(self.doc, id, src_attr.to_string());
}
let rel_attr = node.attr(local_name!("rel"));
let href_attr = node.attr(local_name!("href"));
if let (Some("stylesheet"), Some(href)) = (rel_attr, href_attr) {
crate::assets::fetch_linked_stylesheet(self.doc, id, href.to_string());
}
// If the node has an "id" attribute, store it in the ID map.
if let Some(id_attr) = node.attr(local_name!("id")) {
self.doc.nodes_to_id.insert(id_attr.to_string(), id);
}
for &child_id in &child_ids {
self.doc.get_node_mut(child_id).unwrap().parent = Some(id);
}
self.doc.get_node_mut(id).unwrap().children = child_ids;
id
}
TemplateNode::Text { text } => self.doc.create_text_node(text),
TemplateNode::Dynamic { .. } => self.doc.create_node(NodeData::Comment),
}
}
}
impl WriteMutations for MutationWriter<'_> {
fn append_children(&mut self, id: ElementId, m: usize) {
#[cfg(feature = "tracing")]
tracing::info!("append_children id:{} m:{}", id.0, m);
let children = self.state.stack.split_off(self.state.stack.len() - m);
let parent = self.state.element_to_node_id(id);
for child in children {
self.doc.get_node_mut(parent).unwrap().children.push(child);
self.doc.get_node_mut(child).unwrap().parent = Some(parent);
}
self.maybe_push_style_node(parent);
}
fn assign_node_id(&mut self, path: &'static [u8], id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("assign_node_id path:{:?} id:{}", path, id.0);
// If there is an existing node already mapped to that ID and
// it has no parent, then drop it
if let Some(node_id) = self.state.try_element_to_node_id(id) {
if let Some(node) = self.doc.get_node(node_id) {
if node.parent.is_none() {
self.doc.remove_and_drop_node(node_id);
}
}
}
let node_id = self.load_child(path);
self.set_id_mapping(node_id, id);
}
fn create_placeholder(&mut self, id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("create_placeholder id:{}", id.0);
let node_id = self.doc.create_node(NodeData::Comment);
self.set_id_mapping(node_id, id);
self.state.stack.push(node_id);
}
fn create_text_node(&mut self, value: &str, id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("create_text_node id:{} text:{}", id.0, value);
let node_id = self.doc.create_text_node(value);
self.set_id_mapping(node_id, id);
self.state.stack.push(node_id);
}
#[allow(clippy::map_entry)]
fn load_template(&mut self, template: Template, index: usize, id: ElementId) {
if !self.state.templates.contains_key(&template) {
let template_root_ids: Vec<NodeId> = template
.roots
.iter()
.map(|root| self.create_template_node(root))
.collect();
self.state.templates.insert(template, template_root_ids);
}
let template_entry = &self.state.templates[&template];
let template_node_id = template_entry[index];
let clone_id = self.doc.deep_clone_node(template_node_id);
#[cfg(feature = "autofocus")]
autofocus_node_recursive(self.doc, &mut self.node_to_autofocus, clone_id);
self.set_id_mapping(clone_id, id);
self.state.stack.push(clone_id);
}
fn replace_node_with(&mut self, id: ElementId, m: usize) {
#[cfg(feature = "tracing")]
tracing::info!("replace_node_with id:{} m:{}", id.0, m);
let new_nodes = self.state.stack.split_off(self.state.stack.len() - m);
let anchor_node_id = self.state.element_to_node_id(id);
self.maybe_push_parent_style_node(anchor_node_id);
self.doc.insert_before(anchor_node_id, &new_nodes);
self.doc.remove_node(anchor_node_id);
}
fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize) {
#[cfg(feature = "tracing")]
tracing::info!("replace_placeholder_with_nodes path:{:?} m:{}", path, m);
let new_nodes = self.state.stack.split_off(self.state.stack.len() - m);
let anchor_node_id = self.load_child(path);
self.maybe_push_parent_style_node(anchor_node_id);
self.doc.insert_before(anchor_node_id, &new_nodes);
self.doc.remove_node(anchor_node_id);
}
fn insert_nodes_after(&mut self, id: ElementId, m: usize) {
#[cfg(feature = "tracing")]
tracing::info!("insert_nodes_after id:{} m:{}", id.0, m);
let new_nodes = self.state.stack.split_off(self.state.stack.len() - m);
let anchor_node_id = self.state.element_to_node_id(id);
let next_sibling_id = self
.doc
.get_node(anchor_node_id)
.unwrap()
.forward(1)
.map(|node| node.id);
match next_sibling_id {
Some(anchor_node_id) => {
self.doc.insert_before(anchor_node_id, &new_nodes);
}
None => self.doc.append(anchor_node_id, &new_nodes),
}
self.maybe_push_parent_style_node(anchor_node_id);
}
fn insert_nodes_before(&mut self, id: ElementId, m: usize) {
#[cfg(feature = "tracing")]
tracing::info!("insert_nodes_before id:{} m:{}", id.0, m);
let new_nodes = self.state.stack.split_off(self.state.stack.len() - m);
let anchor_node_id = self.state.element_to_node_id(id);
self.doc.insert_before(anchor_node_id, &new_nodes);
self.maybe_push_parent_style_node(anchor_node_id);
}
fn set_attribute(
&mut self,
name: &'static str,
ns: Option<&'static str>,
value: &AttributeValue,
id: ElementId,
) {
let node_id = self.state.element_to_node_id(id);
#[cfg(feature = "tracing")]
tracing::info!(
"set_attribute node_id:{} ns: {:?} name:{}, value:{:?}",
node_id,
ns,
name,
value
);
self.doc.snapshot_node(node_id);
let mut queued_image = None;
let mut queued_stylesheet = None;
{
let node = &mut self.doc.nodes[node_id];
let stylo_element_data = &mut *node.stylo_element_data.borrow_mut();
if let Some(data) = stylo_element_data {
data.hint |= RestyleHint::restyle_subtree();
}
if let NodeData::Element(ref mut element) = node.data {
if element.name.local == local_name!("input") && name == "checked" {
set_input_checked_state(element, value);
}
// FIXME: support other non-text attributes
else if let AttributeValue::Text(val) = value {
if name == "value" {
// Update text input value
if let Some(input_data) = element.text_input_data_mut() {
input_data.set_text(
&mut self.doc.font_ctx,
&mut self.doc.layout_ctx,
val,
);
}
}
// FIXME check namespace
let existing_attr = element
.attrs
.iter_mut()
.find(|attr| attr.name.local == *name);
if let Some(existing_attr) = existing_attr {
existing_attr.value.clear();
existing_attr.value.push_str(val);
} else {
// we have overloaded the style namespace to accumulate style attributes without a `style` block
if ns == Some("style") {
// todo: need to accumulate style attributes into a single style
//
// element.
} else {
element.attrs.push(Attribute {
name: qual_name(name, ns),
value: val.to_string(),
});
}
}
if name == "style" {
element.flush_style_attribute(&self.doc.guard);
}
if name == "src" && !val.is_empty() {
element.node_specific_data = NodeSpecificData::None;
queued_image = Some(val.to_string());
}
if element.name.local == local_name!("link")
&& name == "href"
&& !val.is_empty()
{
queued_stylesheet = Some(val.to_string());
}
}
if let AttributeValue::None = value {
// Update text input value
if name == "value" {
if let Some(input_data) = element.text_input_data_mut() {
input_data.set_text(
&mut self.doc.font_ctx,
&mut self.doc.layout_ctx,
"",
);
}
}
// FIXME: check namespace
element.attrs.retain(|attr| attr.name.local != *name);
}
}
}
if let Some(queued_image) = queued_image {
crate::assets::fetch_image(self.doc, node_id, queued_image);
}
if let Some(queued_stylesheet) = queued_stylesheet {
crate::assets::fetch_linked_stylesheet(self.doc, node_id, queued_stylesheet);
}
}
fn set_node_text(&mut self, value: &str, id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("set_node_text id:{} value:{}", id.0, value);
let node_id = self.state.element_to_node_id(id);
let node = self.doc.get_node_mut(node_id).unwrap();
let text = match node.data {
NodeData::Text(ref mut text) => text,
// todo: otherwise this is basically element.textContent which is a bit different - need to parse as html
_ => return,
};
let changed = text.content != value;
if changed {
text.content.clear();
text.content.push_str(value);
let parent = node.parent;
self.maybe_push_style_node(parent);
}
}
fn create_event_listener(&mut self, _name: &'static str, _id: ElementId) {
// we're going to actually set the listener here as a placeholder - in JS this would also be a placeholder
// we might actually just want to attach the attribute to the root element (delegation)
self.set_attribute(
_name,
None,
&AttributeValue::Text("<rust func>".into()),
_id,
);
// also set the data-dioxus-id attribute so we can find the element later
self.set_attribute(
"data-dioxus-id",
None,
&AttributeValue::Text(_id.0.to_string()),
_id,
);
// let node_id = self.state.element_to_node_id(id);
// let mut node = self.rdom.get_mut(node_id).unwrap();
// node.add_event_listener(name);
}
fn remove_event_listener(&mut self, _name: &'static str, _id: ElementId) {
// let node_id = self.state.element_to_node_id(id);
// let mut node = self.rdom.get_mut(node_id).unwrap();
// node.remove_event_listener(name);
}
fn remove_node(&mut self, id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("remove_node id:{}", id.0);
let node_id = self.state.element_to_node_id(id);
self.doc.remove_node(node_id);
}
fn push_root(&mut self, id: ElementId) {
#[cfg(feature = "tracing")]
tracing::info!("push_root id:{}", id.0,);
let node_id = self.state.element_to_node_id(id);
self.state.stack.push(node_id);
}
}
/// Set 'checked' state on an input based on given attributevalue
fn set_input_checked_state(element: &mut ElementNodeData, value: &AttributeValue) {
let checked: bool;
match value {
AttributeValue::Bool(checked_bool) => {
checked = *checked_bool;
}
AttributeValue::Text(val) => {
if let Ok(checked_bool) = val.parse() {
checked = checked_bool;
} else {
return;
};
}
_ => {
return;
}
};
match element.node_specific_data {
NodeSpecificData::CheckboxInput(ref mut checked_mut) => *checked_mut = checked,
// If we have just constructed the element, set the node attribute,
// and NodeSpecificData will be created from that later
// this simulates the checked attribute being set in html,
// and the element's checked property being set from that
NodeSpecificData::None => element.attrs.push(Attribute {
name: QualName {
prefix: None,
ns: ns!(html),
local: local_name!("checked"),
},
value: checked.to_string(),
}),
_ => {}
}
}
#[cfg(feature = "autofocus")]
fn autofocus_node_recursive(
doc: &BaseDocument,
node_to_autofocus: &mut Option<usize>,
node_id: usize,
) {
if let Some(node) = doc.get_node(node_id) {
if node.is_focussable() {
if let NodeData::Element(ref element) = node.data {
if let Some(value) = element.attr(local_name!("autofocus")) {
if value == "true" {
*node_to_autofocus = Some(node_id);
}
}
}
}
for child_node_id in &node.children {
autofocus_node_recursive(doc, node_to_autofocus, *child_node_id);
}
}
}