The core
With the crate in place, the core needs three things: the app itself, a small
FFI surface for the shells to call, and a codegen binary that generates the
shell-side types (and the Core class that drives them).
The app
Here's the whole counter, in shared/src/app.rs:
// Rust: shared/src/app.rs
use crux_core::{
App, Command,
macros::effect,
render::{RenderOperation, render},
};
use facet::Facet;
use serde::{Deserialize, Serialize};
#[derive(Facet, Serialize, Deserialize, Clone, Debug)]
#[repr(C)]
pub enum Event {
Increment,
Decrement,
Reset,
}
#[effect(facet_typegen)]
#[derive(Debug)]
pub enum Effect {
Render(RenderOperation),
}
#[derive(Default)]
pub struct Model {
count: isize,
}
#[derive(Facet, Serialize, Deserialize, Clone, Default)]
pub struct ViewModel {
pub count: String,
}
#[derive(Default)]
pub struct Counter;
impl App for Counter {
type Event = Event;
type Model = Model;
type ViewModel = ViewModel;
type Effect = Effect;
fn update(&self, event: Event, model: &mut Model) -> Command<Effect, Event> {
match event {
Event::Increment => model.count += 1,
Event::Decrement => model.count -= 1,
Event::Reset => model.count = 0,
}
render()
}
fn view(&self, model: &Model) -> ViewModel {
ViewModel {
count: format!("Count is: {}", model.count),
}
}
}
An Event for each button, a Model holding the count, a ViewModel for the
shell to display, and one effect, Render, which tells the shell there is a
new view to show. The Facet derives and #[effect(facet_typegen)] let type
generation see the types that cross into the shell.
A very basic app builds this up a piece at a time,
and Testing shows how to test it.
The manifest
The library needs a few more dependencies, and a codegen binary behind a
feature flag:
# TOML: shared/Cargo.toml
[package]
name = "shared"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
[lints]
workspace = true
[lib]
crate-type = ["cdylib", "lib", "staticlib"]
[[bin]]
name = "codegen"
required-features = ["codegen"]
[features]
facet_typegen = ["crux_core/facet_typegen"]
codegen = [
"dep:anyhow",
"dep:clap",
"dep:log",
"dep:pretty_env_logger",
"facet_typegen",
]
[dependencies]
facet = { version = "=0.46.5", features = ["chrono"] }
boltffi.workspace = true
crux_core.workspace = true
serde = { workspace = true, features = ["derive"] }
# optional dependencies
anyhow = { workspace = true, optional = true }
clap = { version = "4.6.10", optional = true, features = ["derive"] }
log = { version = "0.4.35", optional = true }
pretty_env_logger = { version = "0.6.0", optional = true }
[dev-dependencies]
crux_core = { workspace = true, features = ["testing"] }
The example's workspace defines more than the one we set up: drop the
authors, repository, license and keywords lines, or add them to your
[workspace.package], and add boltffi = "=0.32.1" to your
[workspace.dependencies].
The FFI
The shells reach the core through a CoreFfi type, which BoltFFI exports from
shared/src/ffi.rs. It takes and returns bytes, and you will rarely need to
change it:
// Rust: shared/src/ffi.rs
#![allow(clippy::used_underscore_items)]
use crux_core::{
Core,
bridge::{Bridge, EffectId},
};
use crate::Counter;
/// The main interface used by the shell
#[boltffi::export]
pub struct CoreFfi {
core: Bridge<Counter>,
}
impl Default for CoreFfi {
fn default() -> Self {
Self::new()
}
}
#[boltffi::export]
impl CoreFfi {
#[must_use]
pub fn new() -> Self {
Self {
core: Bridge::new(Core::new()),
}
}
/// Send an event to the app and return the effects.
/// # Panics
/// If the event cannot be deserialized.
/// In production you should handle the error properly.
#[must_use]
pub fn update(&self, data: &[u8]) -> Vec<u8> {
let mut effects = Vec::new();
match self.core.update(data, &mut effects) {
Ok(()) => effects,
Err(e) => panic!("{e}"),
}
}
/// Resolve an effect and return the effects.
/// # Panics
/// If the `data` cannot be deserialized into an effect or the `effect_id` is invalid.
/// In production you should handle the error properly.
#[must_use]
pub fn resolve(&self, id: u32, data: &[u8]) -> Vec<u8> {
let mut effects = Vec::new();
match self.core.resolve(EffectId::from(id), data, &mut effects) {
Ok(()) => effects,
Err(e) => panic!("{e}"),
}
}
/// Get the current `ViewModel`.
/// # Panics
/// If the view cannot be serialized.
/// In production you should handle the error properly.
#[must_use]
pub fn view(&self) -> Vec<u8> {
let mut view_model = Vec::new();
match self.core.view(&mut view_model) {
Ok(()) => view_model,
Err(e) => panic!("{e}"),
}
}
}
lib.rs exposes it:
// Rust: shared/src/lib.rs
#![allow(clippy::unsafe_derive_deserialize)]
// `boltffi::scaffolding!()` emits an empty enum.
#![allow(clippy::empty_enums)]
mod app;
pub mod ffi;
boltffi::scaffolding!();
pub use app::*;
pub use crux_core::Core;
BoltFFI reads shared/boltffi.toml to find out where to put each shell's
bindings. The example's is a good starting point, and
Part I explains what each table
does:
# TOML: shared/boltffi.toml
[package]
name = "shared"
crate = "shared"
version = "0.1.0"
repository = "https://github.com/redbadger/crux/"
license = "Apache-2.0"
[targets.apple]
output = "../apple/generated/Shared"
include_macos = true
[targets.apple.swift]
module_name = "Shared"
[targets.apple.spm]
package_name = "Shared"
layout = "ffi-only"
[targets.android]
output = "../Android/generated"
min_sdk = 34
[targets.android.kotlin]
package = "com.crux.examples.counter"
output = "../Android/generated/kotlin"
[targets.android.pack]
output = "../Android/generated/jniLibs"
[targets.wasm]
output = "../web-nextjs/generated"
profile = "release"
artifact_path = "../target/wasm32-unknown-unknown/release/shared.wasm"
[targets.wasm.typescript]
output = "../web-nextjs/generated/pkg"
[targets.wasm.npm]
package_name = "shared"
[targets.csharp]
enabled = true
namespace = "CounterApp.Shared"
output = "../windows/generated/boltffi"
package_output = "../windows/generated/nuget"
package_id = "CounterApp.Shared.Ffi"
target_framework = "net10.0"
runtime_identifiers = ["win-x64", "win-arm64"]
The codegen
The codegen binary generates the shell-side types: Event, Effect,
ViewModel and everything they refer to, an EffectHandler interface with a
method per operation, and a Core class that runs the loop between the shell
and the core.
// Rust: shared/src/bin/codegen.rs
use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, ValueEnum};
use crux_core::type_generation::facet::{BoltFfi, Config, PackageLocation, TypeRegistry};
use log::info;
use shared::Counter;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum Language {
Swift,
Kotlin,
Csharp,
Typescript,
}
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(short, long, value_enum)]
language: Language,
#[arg(short, long)]
output_dir: PathBuf,
}
fn main() -> Result<()> {
pretty_env_logger::init();
let args = Args::parse();
let typegen_app = TypeRegistry::new()
.register_app::<Counter>()?
.build()?
// Where `boltffi pack` puts the bindings for each shell, so that the
// generated `Core` can be constructed with nothing but a handler.
.boltffi(
BoltFfi::new()
.swift("Shared")
.kotlin()
.typescript("shared", PackageLocation::Path("../pkg".to_string()))
.csharp(),
);
let name = match args.language {
Language::Swift => "App",
Language::Kotlin => "com.crux.examples.counter",
Language::Csharp => "CounterApp.Shared",
Language::Typescript => "app",
};
let mut builder = Config::builder(name, &args.output_dir);
if args.language == Language::Swift {
// The BoltFFI package the generated one now depends on declares these,
// and SPM will not link a package with a lower deployment target.
builder.platform(".iOS(.v16)").platform(".macOS(.v13)");
}
let config = builder.build();
match args.language {
Language::Swift => {
info!("Typegen for Swift");
typegen_app.swift(&config)?;
}
Language::Kotlin => {
info!("Typegen for Kotlin");
typegen_app.kotlin(&config)?;
}
Language::Csharp => {
info!("Typegen for C#");
typegen_app.csharp(&config)?;
}
Language::Typescript => {
info!("Typegen for TypeScript");
typegen_app.typescript(&config)?;
}
}
Ok(())
}
The .boltffi(...) call connects the generated Core to the BoltFFI bindings
of the core. It repeats the names that boltffi.toml and ffi.rs already use,
and lists only the languages for which you build shells.
Bridging to BoltFFI explains each
option, including the platform(...) calls for Swift.
Each shell's just typegen runs this binary for its own language, so there's
nothing to run yet. Time to build a shell.