v0.5.0 #2160
ealmloff
announced in
Announcements
v0.5.0
#2160
Replies: 2 comments
-
The doc site is looking great. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Amazing!!! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Dioxus 0.5: Signal Rewrite, Remove lifetimes/unsafe, CSS Hotreloading, 5x Faster Desktop, Asset System, and more!
Read the Full 0.5 release post on the Dioxus blog
The story
Here at Dioxus Labs, we have an unofficial rule: only one rewrite per year.
Our last rewrite brought some amazing features: templates, hotreloading, and insane performance. However, don’t be mistaken, rewrites are scary, time consuming, and a huge gamble. We started this new rewrite on January 1st of 2024, completed it by Feburary 1st, and then spent another month and a half writing tests, squashing bugs, and polishing documentation. Rewrites are absolutely not for the faint of heart.
If you’re new here, Dioxus (dye•ox•us) is a library for building GUIs in Rust. Originally, I built Dioxus as a rewrite of Yew with the intention of supporting proper server-side-rendering. Eventually, Dioxus got popular, we got some amazing sponsors, and I went full time. We’ve grown from a team of 1 (me) to a team of 4(!) - pulled entirely from the wonderful dioxus community.
Now, Dioxus is something a little different. Real life, actual companies are shipping web apps, desktop apps, and mobile apps with Dioxus. What was once just a fun little side project powers a small fraction of apps out in the wild. We now have lofty goals of simplifying the entire app development ecosystem. Web, Desktop, Mobile, all end-to-end typesafe, blazing fast, living under one codebase. The dream!
With 0.5 we took a hard look at how Dioxus would need to change to achieve those goals. The request we got from the community was clear: make it simpler, make it robust, make it polished.
What’s new?
This is probably the biggest release of Dioxus ever, with so many new features, bug fixes, and improvements that I can’t list them all. We churned over 100,000 lines of code (yes, 100,000+) with over 1,400 commits between 0.4.3 and 0.5.0. Here’s a quick overview:
dioxus-core
, removing all unsafe codeuse_state
anduse_ref
for a clone-freeSignal
-based APIcx: Scope
statelaunch
function that starts your app for any platformWebSys
event types<a/>
properties)Lifetime Problems
To make Dioxus simpler, we wanted to remove lifetimes entirely. Newcomers to rust are easily scared off by lifetime issues, and even experienced Rustaceans find wading through obtuse error messages exhausting.
In dioxus 0.1-0.4, every value in a component lives for a
'bump
lifetime. This lifetime lets you easily use hooks, props and the scope within event listeners without cloning anything. It was the chief innovation that made Dioxus so much easier to use than Yew when it was released.This works great for hooks most of the time. The lifetime lets you omit a bunch of manual clones every time you want to use a value inside an EventHandler (onclick, oninput, etc).
However, the lifetime doesn’t work for futures. Futures in dioxus need to be
'static
which means you always need to clone values before you use them in the future. Since a future might need to run while the component is rendering, it can’t share the component’s lifetime.If you don’t clone the value, you will run into an error like this:
The error complains that
cx
must outlive'static
without mentioning the hook at all which can be very confusing.Dioxus 0.5 fixes this issue by first removing scopes and the
'bump
lifetime and then introducing a newCopy
state management solution called signals. Here is what the component looks like in dioxus 0.5:While this might seem like a rather innocuous change, it has an impressively huge impact on how easy it is to write new components. I’d say building a new Dioxus app is about 2-5x easier with this change alone.
Goodbye scopes and lifetimes!
In the new version of dioxus, scopes and the
'bump
lifetime have been removed! This makes declaring a component and using runtime functions within that component much easier:You can now declare a component by just accepting your props directly instead of a scope parameter
And inside that component, you can use runtime functions directly
Now that lifetimes are gone,
Element
s are'static
which means you can use them in hooks or even provide them through the context API. This makes some APIs like virtual lists in dioxus significantly easier. We expect more interesting APIs to emerge from the community now that you don’t need to be a Rust wizard to implement things like virtualization and offscreen rendering.Removal of all Unsafe in Core
Removing the
'bump
lifetime along with the scope gave us a chance to remove a lot of unsafe from dioxus. dioxus-core 0.5 contains no unsafe code 🎉There’s still a tiny bit of unsafe floating around various dependencies that we plan to remove throughout the 0.5 release cycle, but way less: all quite simple to cut or unfortunately necessary due to FFI.
Signals!
Dioxus 0.5 introduces Signals as the core state primitive for components. Signals have two key advantages over the existing
use_state
anduse_ref
hooks: They are alwaysCopy
and they don’t require manual subscriptions.Copy state
Signal<T>
isCopy
, even if the innerT
values is not. This is enabled by our new generational-box crate (implemented with zero unsafe). Signals can even optionally beSend+Sync
if you need to move them between threads, removing the need for a whole class of specialized state management solutions.The combination of
Copy + Send + Sync
Signals, and static components makes it incredibly easy to move state to anywhere you need it:With
Copy
state, we’ve essentially bolted on a light form of garbage collection into Rust that uses component lifecycles as the triggers for dropping state. From a memory perspective, this is basically the same as 0.4, but with the added benefit of not needing to explicitlyClone
anything.Smarter subscriptions
Signals are smarter about what components rerun when they are changed. A component will only rerun if you read the value of the signal in the component (not in an async task or event handler). In this example, only the child will re-render when the button is clicked because only the child component is reading the signal:
Smarter subscriptions let us merge several different hooks into signals. For example, we were able to remove an entire crate dedicated to state management: Fermi. Fermi provided what was essentially a
use_state
API where statics were used as keys. This meant you could declare some global state, and then read it in your components:Since fermi didn’t support smart subscriptions, you had to explicitly declare use the right
use_read
/use_write
hooks to subscribe to the value. In Dioxus 0.5, we just use signals, eliminating the need for any sort of external state management solution altogether.Signals even work with the context API, so you can quickly share state between components in your app:
Smart subscriptions also apply to hooks. Hooks like
use_future
anduse_memo
will now automatically add signals you read inside the hook to the dependencies of the hook:Event System Rewrite
Since it’s release, dioxus has used a synthetic event system to create a cross platform event API. Synthetic events can be incredibly useful to make events work across platforms and even serialize them across the network, but they do have some drawbacks.
Dioxus 0.5 finally exposes the underlying event type for each platform along with a trait with a cross platform API. This has two advantages:
Again, this seems like a small change on the surface, but opens up dozens of new use cases and possible libraries you can build with dioxus.
💡 The Dioxus optimization guide has tips to help you make the smallest possible bundleCross platform launch
Dioxus 0.5 introduces a new cross platform API to launch your app. This makes it easy to target multiple platforms with the same application. Instead of pulling in a separate renderer package, you can now enable a feature on the dioxus crate and call the launch function from the prelude:
With that single application, you can easily target:
The CLI is now smart enough to automatically pass in the appropriate build features depending on the platform you’re targeting.
Asset System Beta
Currently assets in dioxus (and web applications in general) can be difficult to get right. Links to your asset can easily get out of date, the link to your asset can be different between desktop and web applications, and you need to manually add assets you want to use into your bundled application. In addition to all of that, assets can be a huge performance bottleneck.
Lets take a look at the dioxus mobile guide in the docsite as an example:
The 0.4 mobile guide takes 7 seconds to load and transfers 9 MB of resources. The page has 6 different large image files which slows down the page loading times significantly. We could switch to a more optimized image format like
avif
, but manually converting every screenshot is tedious and time consuming.Lets take a look at the 0.5 mobile guide with the new asset system:
The new mobile guide takes less than 1 second to load and requires only 1/3 of the resources with the exact same images!
Dioxus 0.5 introduces a new asset system called manganis. Manganis integrates with the CLI to check, bundle and optimize assets in your application. The API is currently unstable so the asset system is currently published as a separate crate. In the new asset system, you can just wrap your assets in the
mg!
macro and they will automatically be picked up by the CLI. You can read more about the new asset system in the manganis docs.As we continue to iterate on the 0.5 release, we plan to add hot reloading to manganis assets, so you can interactively add new the features to your app like CSS, images, tailwind classes, and more without forcing a complete reload.
CSS Hot Reloading
As part of our asset system overhaul, we implemented hotreloading of CSS files in the asset directory. If a CSS file appears in your RSX, the
dx
CLI will watch that file and immediately stream its updates to the running app. This works for web, desktop, and fullstack, with mobile support coming in a future mobile-centric update.Screen_Recording_2024-03-20_at_6.30.47_AM.mov
What’s even niftier is that you can stream these changes to several devices at once, unlocking simultaneous hotreloading across all devices that you target:
Hotreload_triple_-_HD_1080p.mov
5x Faster Desktop Rendering
Dioxus implements several optimizations to make diffing rendering fast. Templates let dioxus skip diffing on any static parts of the rsx macro. However, diffing is only one side of the story. After you create a list of changes you need to make to the DOM, you need to apply them.
We developed sledgehammer for dioxus web to make applying those mutations as fast as possible. It makes manipulating the DOM from Rust almost as fast as native JavaScript.
In dioxus 0.5, we apply that same technique to apply changes across the network as fast as possible. Instead of using json to communicate changes to the desktop and liveview renderers, dioxus 0.5 uses a binary protocol.
For render intensive workloads, the new renderer takes only 1/5 the time to apply the changes in the browser with 1/2 the latency. Here is one of the benchmarks we developed while working on the new binary protocol. In dioxus 0.4, the renderer was constantly freezing. In dioxus 0.5, it runs smoothly:
Dioxus 0.4
284067659-2f44831d-bf2c-49f0-a494-3d2b37244e8c.mov
Dioxus 0.5
284067647-c126e688-234a-4100-9c25-042b03f52d36.mov
Spreading props
One common pattern when creating components is providing some additional functionality to a specific element. When you wrap an element, it is often useful to provide some control over what attributes are set in the final element. Instead of manually copying over each attribute from the element, dioxus 0.5 supports extending specific elements and spreading the attributes into an element:
Shorthand attributes
Another huge quality-of-life feature we added was the ability to use shorthand struct initialization syntax to pass attributes into elements and components. We got tired of passing
class: class
everywhere and decided to finally implement this long awaited feature, at the expense of some code breakage. Now, it’s super simple to declare attributes from props:This feature works for anything implementing
IntoAttribute
, meaning signals also benefit from shorthand initialization. While signals as attributes don’t yet skip diffing, we plan to add this as a performance optimization throughout the 0.5 release cycle.Multi-line attribute merging
Another amazing feature added this cycle was attribute merging. When working with libraries like tailwind, you’ll occasionally want to make certain attributes conditional. Before, you had to format the attribute using an empty string. Now, you can simply add an extra attribute with a conditional, and the attribute will be merged using a space as a delimiter:
This is particularly important when using libraries like tailwind where attributes need to be parsed at compile time but also dynamic at runtime. This syntax integrates with the tailwind compiler, removing the runtime overhead for libraries like tailwind-merge.
Server function streaming
Dioxus 0.5 supports the latest version of the server functions crate which supports streaming data. Server functions can now choose to stream data to or from the client. This makes it easier to do a whole class of tasks on the server.
Creating a streaming server function is as easy as defining the output type and returning a TextStream from the server function. Streaming server functions are great for updating the client during any long running task.
We built an AI text generation example here: https://github.com/ealmloff/dioxus-streaming-llm that uses Kalosm and local LLMS to serve what is essentially a clone of OpenAI’s ChatGPT endpoint on commodity hardware.
native_drop.mov
Side note, the AI metaframework used here - Kalosm - is maintained by the Dioxus core team member ealmloff, and his AI GUI app Floneum is built with Dioxus!
Fullstack CLI platform
The CLI now supports a
fullstack
platform with hot reloading and parallel builds for the client and sever. You can now serve your fullstack app with thedx
command:dx serve # Or with an explicit platform dx serve --platform fullstack
Liveview router support
#1505
@DonAlonzo added liveview support for the router in dioxus 0.5. The router will now work out of the box with your liveview apps!
Custom Asset Handlers
#1719
@willcrichton added support for custom asset handlers to dioxus desktop. Custom asset handlers let you efficiently stream data from your rust code into the browser without going through javascript. This is great for high bandwidth communication like video streaming:
Screen_Recording_2024-02-22_at_10.40.42_AM.mov
Now, you can do things like work with gstreamer or webrtc and pipe data directly into the webview without needing to encode/decode frames by hand.
Native File Handling
This is a bit smaller of a tweak, but now we properly support file drops for desktop:
native_drop.mov
Previously we just gave you the option to intercept filedrops but now it’s natively integrated into the event systme.
Error handling
Error handling: You can use error boundaries and the throw trait to easily handle errors higher up in your app
Dioxus provides a much easier way to handle errors: throwing them. Throwing errors combines the best parts of an error state and early return: you can easily throw an error with
?
, but you keep information about the error so that you can handle it in a parent component.You can call
throw
on anyResult
type that implementsDebug
to turn it into an error state and then use?
to return early if you do hit an error. You can capture the error state with anErrorBoundary
component that will render the a different component if an error is thrown in any of its children.You can even nest
ErrorBoundary
components to capture errors at different levels of your app.This pattern is particularly helpful whenever your code generates a non-recoverable error. You can gracefully capture these "global" error states without panicking or handling state for each error yourself.
Hotreloading by default and “develop” mode for desktop
We shipped hotreloading in 0.3, added it to desktop in 0.4, and now we’re finally enabling it by default in 0.5. By default, when you
dx serve
your app, hotreloading is enabled in development mode.Additionally, we’ve drastically improved the developer experience of building desktop apps. When we can’t hotreload the app and have to do a full recompile, we now preserve the state of the open windows and resume that state. This means your app won’t block your entire screen on every edit and it will maintain its size and position, leading to a more magical experience. Once you’ve played with it, you can never go back - it’s that good.
resume_state_small.mov
Updates to the dioxus template
With this update, our newest core team member Miles (lovingly, @doge on our discord) put serious work into overhauling documentation and our templates. We now have templates to create new dioxus apps for web, desktop, mobile, tui, and fullstack under one command.
oh_five_release.mov
We also updated the default app you get when using
dx new
to be closer to the traditional create-react-app. The template is now seeded with assets, CSS, and some basic deploy configuration. Plus, it includes links to useful resources like dioxus-std, the VSCode Extension, docs, tutorials, and more.Dioxus-Community and Dioxus-std
The Dioxus Community is something special: discord members marc and Doge have been hard at working updating important ecosystem crates for the 0.5 release. With this release, important crates like icons, charts, and the dioxus-specific standard library are ready to use right out the gate. The
Dioxus Community
project is a new GitHub organization that keeps important crates up-to-date even when the original maintainers step down. If you build a library for Dioxus, we’ll be happy to help maintain it, keeping it at what is essentially “Tier 2” support.Coming soon
At a certain point we had to stop adding new features to this release. There’s plenty of cool projects on the horizon:
.wasm
directly - with lazy componentsSneak Peek: Dioxus-Blitz revival using Servo
We’re not going to say much about this now, but here’s a sneak peek at “Blitz 2.0”… we’re finally integrating servo into blitz so you can render natively with WGPU using the same CSS engine that powers Firefox. To push this effort forward, we’ve brought the extremely talented Nico Burns (the wizard behind our layout library Taffy) on full time. More about this later, but here’s a little demo of google.com being rendered at 900 FPS entirely on the GPU:
Admittedly the current iteration is not quite there (google.com is in fact a little wonky) but we’re progressing rapidly here and are quickly approaching something quite usable. The repo is here if you want to take a look and get involved:
https://github.com/jkelleyrtp/stylo-dioxus
How can you contribute?
Well, that’s it for the new features. We might’ve missed a few things (there’s so much new!). If you find Dioxus as exciting as we do, we’d love your help to completely transform app development. We’d love contributions including:
That’s it! We’re super grateful for the community support and excited for the rest of 2024.
Build cool things! ✌️
Full Changelog (since 0.4.3)
.gitignore
by @Exotik850 in Autoformat ignores files in.gitignore
#1704lazynodes
module docs by @tigerros in Fix typo inlazynodes
module docs #1759TaskId
by @Exotik850 in Make cx.spawn poll the task before returningTaskId
#1710--split-line-attributes
parameter for CLIfmt
by @marc2332 in feat:--split-line-attributes
parameter for CLIfmt
#1701dx create
by @tkr-sh in fix: no project-name in argument ofdx create
#1803init
subcommand by @hem1t ininit
subcommand #1840Config::rootelement
by @mirkootter in dioxus-web: AddConfig::rootelement
#1851isComposing
support by @egegungordu in AddisComposing
support #1863cargo-generate
by @Andrew15-5 in Removed 1 CLI dependency by updatingcargo-generate
#1873out_dir
andasset_dir
fields to methods inCrateConfig
(cli-config refactor) by @Andrew15-5 in Convertedout_dir
andasset_dir
fields to methods inCrateConfig
(cli-config refactor) #1882release
build option by @Andrew15-5 in feat(cli): added shortrelease
build option #1900dx build
by @Andrew15-5 in Now fullstack client uses correct config viadx build
#1898dx serve
by @Andrew15-5 in fix(serve): fixed long rebuilds withdx serve
#1903HasFileData
forWebDragData
by @spookyvision in fixHasFileData
forWebDragData
#1917eval
should not return an error - eval() should always be available by @jkelleyrtp in callingeval
should not return an error - eval() should always be available #1940Routable
macro by @tigerros in Fix Clippy warning inRoutable
macro #1975dioxus-router
docs by @marc2332 in fix: Updatedioxus-router
docs #1983ReadOnlySignal
as a prop when using the#[component]
macro #1979: generated Owned impl for the props builder was using the wrong generics by @jkelleyrtp in fix #1979: generated Owned impl for the props builder was using the wrong generics #2027Resource::clear()
and also updatedResource
docs by @marc2332 in feat: AddResource::clear()
and also updatedResource
docs #2049dx fmt
breaks file #2104: fmt incorrectly using 1-indexing for columns by @jkelleyrtp in Fix #2104: fmt incorrectly using 1-indexing for columns #2106New Contributors
dx create
#1803cargo-generate
#1873HasFileData
forWebDragData
#1917This discussion was created from the release v0.5.0.
Beta Was this translation helpful? Give feedback.
All reactions