Rust for Rust, JS for JS: introducing Ahoi
Why I built Ahoi When you want to manage data state in Rust/Wasm inside a web app, there have been two main options. Option 1: hand-roll the bridge between Rust and JS. The reactivity does not live on the Rust/Wasm side, so you usually end up reimplementing the state layer on both sides. Option 2: use a Rust frontend framework such as Dioxus, Sycamore, or Leptos. I like these a lot, but there is…
I developed a tool called Ahoi to manage data state in Rust/Wasm within web applications. Two primary options existed for this task: developing a custom bridge between Rust and JavaScript or using a Rust frontend framework like Dioxus, Sycamore, or Leptos. However, I noticed a challenge - the JavaScript ecosystem offers a wealth of UI components, yet integrating with Rust frameworks could be awkward for event handling.
Ahoi addresses this issue by separating reactive state management in Rust and using a thin bridge to communicate with JavaScript. The project comprises two parts: a Rust crate for the reactivity engine and npm packages as bridges for supported JavaScript frameworks such as SolidJS, React, Vue, and Svelte.
The reactivity engine is built from scratch, drawing inspiration from earlier projects like Dioxus, Leptos, and Sycamore. The core of the reactivity system revolves around a reactive Stock that holds state and a key enum that determines what JavaScript can subscribe to. Each key in the enum is assigned a Rust type that JavaScript will receive during communication.
To interact with the Rust state from JavaScript, we define two types of keys: read-write and read-only. Read-write keys (like Hail::Count) enable JavaScript to directly modify Rust's state, while read-only keys (like Hail::Doubled) trigger re-computation in Rust when the underlying data changes. Commands, such as increasing a counter, are handled through a Tell enum.
On the JavaScript side, these keys translate to fully-typed signals that correspond to the host framework being used, whether it's SolidJS, React, Vue, or Svelte.
Ahoi doesn't aim to convert Rust code to TypeScript automatically; instead, it adds functionalities that these frameworks might lack, specifically regarding what each key returns. The bridge setup, including WebAssembly initialization and providing type exports, is detailed in the Quick Start. For more information, you can check the GitHub repository, a book and live demos, or install it via crates.io or npm.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.