maomi
Introduction
Guide
Documents

Write a Component

Add dependencies in Cargo.toml

To use maomi, rust 1.65+ is required. Then add maomi as cargo dependencies. In Cargo.toml:

[package]
name = "my-website"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
maomi = "0.4"
maomi-dom = "0.4"

In real world, some other crates are also needed:

[dependencies]
maomi = "0.4"
maomi-dom = "0.4"
wasm-bindgen = "0.2"
log = "0.4"
console_log = "0.2"
console_error_panic_hook = "0.1"

#[component] struct

A page is composed by components. To generate a page with maomi, write a component first.

A component is a struct with "#[component]" attribute:

use wasm_bindgen::prelude::*;
use maomi::prelude::*;
use maomi_dom::{prelude::*, element::*};
#[component(Backend = DomBackend)]
struct MyWebsite {
template: template! {
<div> "My Website" </div>
}
}

The struct must contain a "template!" field. It contains the template of this component.

Implement Component trait

The "Component" trait should be implemented for the component struct:

impl Component for MyWebsite {
fn new() -> Self {
Self {
template: Default::default(),
}
}
}

Render the Component into page body

Finally, this component can be put into the page body.

#[wasm_bindgen(start)]
pub fn wasm_main() {
// enable console log
console_error_panic_hook::set_once();
console_log::init_with_level(log::Level::Trace).unwrap();
// initialize a backend context in HTML <body>
let dom_backend = DomBackend::new_with_document_body().unwrap();
let backend_context = maomi::BackendContext::new(dom_backend);
// create a mount point for the component
let mount_point = backend_context
.enter_sync(move |ctx| {
ctx.attach(|_: &mut MyWebsite| {})
})
.map_err(|_| "Cannot init mount point")
.unwrap();
// leak the mount point and the backend context to keep working forever
std::mem::forget(mount_point);
std::mem::forget(backend_context);
}

Compile to WebAssembly

Compile the code with wasm-pack

wasm-pack build --target no-modules

The generated code is under the "pkg" directory.

Write an HTML wrapper

Write an HTML file with empty <body>.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body></body>
<script src="pkg/my_website.js"></script>
<script>
wasm_bindgen('pkg/my_website_bg.wasm')
</script>
</html>

Then serve it in an HTTP server and see the result!