Skip to content

Your first Linker component ​

Goal: a two-step ticket form. In step one the user enters a subject; the server validates it, remembers it and moves on to step two.

Step 1: write the component ​

src/cg/ticket.rs:

rust
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerResponse};
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Default, Serialize, Deserialize)]
pub struct Ticket {
    step: u8,          // server-side state: the browser can't see or change it
    subject: String,
}

impl LinkerComponent for Ticket {
    const ALIAS: &'static str = "ticket";
    const METHODS: &'static [&'static str] = &["saveStep1"];

    async fn mount(&mut self, _: &LinkerContext, _: &Args) -> laravel::Result<()> {
        self.step = 1;
        Ok(())
    }

    async fn call(&mut self, _: &LinkerContext, _method: &str, args: Args) -> laravel::Result<LinkerResponse> {
        let subject = args.get("subject").and_then(Value::as_str).unwrap_or_default().trim();
        if subject.is_empty() || subject.chars().count() > 120 {
            return Ok(LinkerResponse::validation([("subject", "A subject is required, at most 120 characters.")]));
        }

        self.subject = subject.to_owned();
        self.step = 2;

        Ok(LinkerResponse::ok()
            .data("step", self.step)
            .then(Action::scroll_to("#step-2")))
    }
}

Key points:

  • The struct is the state. In Stateful mode it's restored from the cache with serde before each call and saved back after a successful one. It needs Serialize + Deserialize + Default.
  • METHODS: methods not listed don't exist for the browser; calling one returns policy "不支援的操作。" (unsupported operation). Names must match ^[a-zA-Z][a-zA-Z0-9]*$.
  • You validate parameters yourself. args is the JSON object the browser sent (serde_json::Map). On failure return LinkerResponse::validation, and the browser draws the message next to the field with that name.
  • .data(key, value): written to client state; templates read it with data-state-*.
  • .then(Action::…): chains a browser action.

Step 2: register it ​

src/cg/mod.rs:

rust
mod ticket;

pub use ticket::Ticket;

pub fn register() {
    // …existing registrations
    cg_component::runtime::linker::register::<Ticket>();
}

The browser sends the alias (ticket), not the type name. Aliases must match ^[a-z][a-zA-Z0-9]*$; an invalid one makes register panic, so you find out at startup.

There's deliberately no automatic scanning. This register() is the complete answer to "which components can the browser call". With directory scanning, dropping a file in would open a door, and that wouldn't stand out in a diff.

Step 3: mount it in a handler ​

src/http/handlers/tickets.rs:

rust
use cg_component::runtime::{self, Allow, linker};
use laravel::prelude::*;
use laravel::view::{Html, View};

use crate::cg::Ticket;
use crate::models::User;

pub async fn create(user: Authenticated<User>) -> laravel::Result<View> {
    let mount = linker::mount::<Ticket, User>(&user, linker::Args::new()).await?;
    let object = runtime::render_object("ticketWizard", &[Allow::StateRead, Allow::StateWrite]);

    Ok(view("tickets.create", data! {}).with_html("wizard_attrs", Html::raw(mount.html() + &object.render(&[]))))
}

Add route.get("/tickets/create", tickets::create); to src/routes/web.rs.

  • linker::mount creates the instance (runs mount(), saves it to the cache) and returns the data-linker, data-linker-instance, data-linker-rev and data-linker-min-delay attributes.
  • The Linker endpoints need a login, and so does mounting: the handler gets the user with Authenticated<User>.
  • render_object grants StateRead (data-state-is reads step) and StateWrite (data-state-init writes the initial value).

Step 4: the template ​

resources/views/tickets/create.html:

html
{% extends "layouts/site.html" %}

{% block content %}
<div{{ wizard_attrs }} data-state-init="step=1">
    <form>
        <input name="subject">
        {{ cg_button("Next", type="submit", attrs={"data-linker-call": "saveStep1", "data-linker-args": "form"}) }}
    </form>

    <div id="step-2" data-state-is="step=2">
        Step two…
    </div>
</div>
{% endblock %}
  • data-linker-args="form" collects every field of the nearest <form>. Put it on the submit button, not on the <form> itself (why: see Template attributes).
  • When validation fails, the error message appears next to the subject field automatically; you don't write that.
  • The data.step Linker returns is written to ticketWizard:step (the namespace is the render object's name), and data-state-is="step=2" switches on its own.

Done. No new API route, no hand-written fetch, no front-end code.

Lifecycle ​

Page handler: linker::mount
  → C::default() → mount() → saved to the cache (linker:{user}:{uuid}) → outputs uuid + rev=0
The user triggers data-linker-call
  → POST /{prefix}/linker { component, instance, rev, method, args }
  → Logged in? (no → 401 policy)
  → Lock the instance (wait up to 3 s; can't get it → service "操作忙碌中" / busy)
  → Read the state (missing, expired or someone else's → 409 expired)
  → Does rev match? (no → 409 conflict, with the server's rev)
  → booted() → referer → METHODS → call()
  → Success: write the state back, rev + 1; validation failure: only renew
  → Return { ok, data, pipeline, instance, rev }
  • Calls on the same instance are locked and run in order; a request with an old rev gets conflict.
  • After 30 minutes idle or 8 hours total the instance is expired, and the user is asked to reload.
  • A reload creates a brand new instance; state that wasn't saved to the DB is gone. To let users resume, save a draft row.

Next: Your first render fragment, then the Mental model. The full three-step version is in A multi-step wizard.