Skip to content

What is this ​

cg-component started as an experimental component framework on Laravel (PHP + Blade). This project is its Laravel for Rust version: a blank project with everything wired up, ready to start a new application from.

It has three parts:

  • Components: Badge, Button and Icon are Rust structs that write their own HTML. The output has the same structure as the PHP Blade views, so the CSS is shared unchanged.
  • Render fragments (renderBlade in PHP): ask the server for a piece of HTML and put the whole piece on the page.
  • Linker: call Rust methods from HTML attributes and get back data and "named actions".

The browser side of render fragments and Linker is the same JavaScript, synced from the PHP project (resources/js/cg/); on the server, cg_component::runtime answers with exactly the same JSON. Both share one client-side store (state), so "replace a whole block of HTML" and "keep what the user was in the middle of" don't conflict.

This wiki is a tutorial: it starts with "why" and goes all the way to writing a complete module yourself. The source code is the precise specification (crates/cg-component/src/); the PHP version's design documents are in the PHP project's docs/.

Why Laravel for Rust needs this approach ​

Laravel for Rust templates are MiniJinja, which can't run Blade. The PHP components are all Blade views, so they can't be moved over as they are. Instead:

PHP versionRust version
app/Component/Badge/BadgeView.blade.phpwrite_html in crates/cg-component/src/badge.rs
@renderObject / @renderBlade / @renderAutoruntime::render_object / render_trigger / render_auto, returning Attributes
@linker('alias')linker::mount::<C, User>(&user, params), returning the mount point's attributes
Controllers with CanRenderCallSafelyFunctions registered with render::register("name", …)
#[Computable]LinkerComponent::METHODS

tests/php_parity.rs compares the HTML structure with the PHP snapshots element by element, and tests/runtime.rs checks the protocol over HTTP.

Two claims ​

1. Server-driven interaction doesn't need state to round-trip ​

Livewire sends a whole signed snapshot back and forth with every request. Linker keeps state on the server and gives the browser only an opaque uuid.

LivewireLinker
Where state livesRound-trips with every request (snapshot + HMAC)Only in the server cache; the browser gets uuid + rev
Exposed surfaceEvery public method and propertyOnly the methods listed in METHODS
What comes backAn HTML diffData + named actions
Server telling the browser to do things$this->js('any JS'), effectively evalA table of named actions, no eval; CSP doesn't need unsafe-eval

Failures come in exactly six shapes (validation / policy / expired / conflict / service / fatal), and the browser has a single handler for them.

2. DOM diffing is optional ​

No morphing, no diffing: replace a whole innerHTML. That's safe because "what the user was in the middle of" was never kept in the DOM.

User expands row 3 → clicks "Refresh list" → the whole block of HTML is replaced → row 3 is… still expanded

It's still expanded not because a diff preserved it, but because it was never in the DOM. The open value lives in an in-memory key-value store, and the new nodes read it back as soon as they're bound.

The subsystems ​

SubsystemWhereSingle responsibilityDoesn't
Componentscrates/cg-component/src/*.rsWrite HTML identical to PHP'sHandle interaction
Render fragmentsruntime/render.rs + renderBlade.jsTransport HTMLMake business decisions
statestate.js / stateBind.jsClient memory + declarative display (data-state-*)Send requests
Linkerruntime/linker/ + linker.jsBusiness round trips: a call goes in, data + named actions come outReturn HTML or touch the DOM

The JavaScript runtime attaches nothing to window. The page's only entry point is HTML attributes, and those have to pass a render object's allow list first. What each block of DOM may do is written in the handler and the template, where you can see it.

In thirty seconds ​

Server:

rust
#[derive(Default, Serialize, Deserialize)]
pub struct CustomerList {
    keyword: String,                                       // state lives on the server
}

impl LinkerComponent for CustomerList {
    const ALIAS: &'static str = "customerList";
    const METHODS: &'static [&'static str] = &["search"];   // callable from the browser (unlisted = doesn't exist)

    async fn call(&mut self, ctx: &LinkerContext, _: &str, args: Args) -> laravel::Result<LinkerResponse> {
        let keyword = args.get("keyword").and_then(Value::as_str).unwrap_or_default();
        if keyword.chars().count() > 64 {                  // you validate parameters yourself
            return Ok(LinkerResponse::validation([("keyword", "At most 64 characters.")]));
        }
        self.keyword = keyword.to_owned();
        let rows = rows(ctx, &self.keyword).await?;

        Ok(LinkerResponse::ok()
            .data("matchCount", rows.len())               // written to client state
            .then(Action::new("dom.repeat", json!({ "ref": "customers", "items": rows }))   // tells the browser what to do
                .map_err(laravel::Error::msg)?))
    }
}

Template:

html
<div{{ panel_attrs }}>   <!-- data-linker="customerList" + the render object's allow list -->
    <input type="search" name="keyword" data-linker-call="search" data-linker-on="input"
           data-linker-debounce="400" data-linker-args="keyword" data-state-bind="keyword">

    <p><span data-state-text="matchCount">0</span> matches</p>
    …
</div>

No new route, no hand-written fetch, no front-end code. The full version is in A searchable customer list.

What it deliberately doesn't do is in Known trade-offs; what differs from the PHP version is in vs the PHP version.

Next: Quick Start.