教學:多步驟精靈
做一個三步驟的開單精靈:主旨 → 內容 → 確認送出。伺服器保證不能跳步,任一步驗證失敗畫面會停在那一步。
1. 先決定狀態放哪
| 選項 | 跳步防護 | 撐過重新整理 | 往返次數 |
|---|---|---|---|
| A. Stateful Linker,每步送一次 | ✅ 伺服器擋 | ❌ | 每步一次 |
| B. 客戶端 state 暫存,最後一次送出 | 最後一起驗 | ❌ | 一次 |
| C. DB 草稿列 | ✅ | ✅ | 每步一次 |
這篇做 A,最後附上 B 的寫法。
2. Migration 與 model
rust
// database/migrations/2026_12_02_000001_create_tickets_table.rs
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("tickets", |table| {
table.id();
table.foreign_id("user_id").constrained().cascade_on_delete();
table.string("subject");
table.text("body");
table.timestamps();
})
.await
}rust
// src/models/ticket.rs
use laravel::model::model;
use laravel::time::Timestamp;
#[model]
pub struct Ticket {
pub id: i64,
pub user_id: i64,
pub subject: String,
pub body: String,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}3. 元件
rust
// src/cg/ticket_wizard.rs
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerResponse, messages};
use laravel::model::create;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::models::Ticket;
#[derive(Default, Serialize, Deserialize)]
pub struct TicketWizard {
step: u8,
subject: String,
body: String,
}
impl LinkerComponent for TicketWizard {
const ALIAS: &'static str = "ticketWizard";
const METHODS: &'static [&'static str] = &["saveSubject", "saveBody", "submit", "back"];
async fn mount(&mut self, _: &LinkerContext, _: &Args) -> laravel::Result<()> {
self.step = 1;
Ok(())
}
async fn call(&mut self, context: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
match method {
"saveSubject" => {
let subject = text(&args, "subject");
if subject.is_empty() || subject.chars().count() > 120 {
return Ok(LinkerResponse::validation([("subject", "主旨必填,最多 120 字。")]));
}
self.subject = subject;
self.step = 2;
Ok(self.show().then(Action::focus("#ticket-body")))
}
"saveBody" => {
if self.step < 2 {
return Ok(LinkerResponse::policy(messages::POLICY));
}
let body = text(&args, "body");
if body.is_empty() || body.chars().count() > 5000 {
return Ok(LinkerResponse::validation([("body", "內容必填,最多 5000 字。")]));
}
self.body = body;
self.step = 3;
Ok(self.show().data("previewSubject", &self.subject))
}
"submit" => {
if self.step != 3 {
return Ok(LinkerResponse::policy(messages::POLICY));
}
let user_id: i64 = context.user.parse()?;
let ticket = create!(Ticket {
user_id: user_id,
subject: &self.subject,
body: &self.body,
})
.await?;
self.step = 4;
Ok(self.show().then(Action::toast("success", &format!("已建立 #{}", ticket.id))))
}
"back" => {
let to = args.get("to").and_then(Value::as_u64).unwrap_or(1).clamp(1, 2) as u8;
self.step = to.min(self.step);
Ok(self.show())
}
_ => unreachable!("METHODS lists every method"),
}
}
}
impl TicketWizard {
fn show(&self) -> LinkerResponse {
LinkerResponse::ok().data("step", self.step)
}
}
fn text(args: &Args, key: &str) -> String {
args.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_owned()
}重點:
step是 struct 的欄位,存在伺服器 cache。saveBody與submit先檢查它 —— 這是伺服器端 guard,前端改不到。submit不讀任何參數,只有「按下去」。主旨與內容都用伺服器記住的值。back只能往回(to.min(self.step)),參數被夾在 1~2。- 驗證失敗不推進
rev、不存狀態,所以失敗的那次不會改到step。
註冊:src/cg/mod.rs 加上 mod ticket_wizard;、pub use ticket_wizard::TicketWizard;,register() 裡 linker::register::<TicketWizard>()。
4. Handler
rust
// src/http/handlers/tickets.rs
use cg_component::runtime::{self, Allow, linker};
use laravel::prelude::*;
use laravel::view::{Html, View};
use crate::cg::TicketWizard;
use crate::models::User;
pub async fn create(user: Authenticated<User>) -> laravel::Result<View> {
let mount = linker::mount::<TicketWizard, 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(&[]))))
}src/routes/web.rs 加上 route.get("/tickets/create", tickets::create);。
5. 模板
html
{% extends "layouts/site.html" %}
{% block title %}開單{% endblock %}
{% block content %}
<main class="mx-auto grid max-w-xl gap-4 px-6 py-12"{{ wizard_attrs }} data-state-init="step=1">
<ol class="flex gap-4">
<li data-state-is-class="step=1:font-bold; step>1:text-green-700">主旨</li>
<li data-state-is-class="step=2:font-bold; step>2:text-green-700">內容</li>
<li data-state-is-class="step=3:font-bold; step>3:text-green-700">確認</li>
</ol>
<form data-state-is="step=1">
<input name="subject" data-state-bind="subject">
{{ cg_button("下一步", type="submit", attrs={"data-linker-call": "saveSubject", "data-linker-args": "form"}) }}
</form>
<form data-state-is="step=2">
<textarea id="ticket-body" name="body" data-state-bind="body"></textarea>
{{ cg_button("上一步", variant="ghost", attrs={"data-linker-call": "back", "data-linker-args": "{\"to\":1}"}) }}
{{ cg_button("下一步", type="submit", attrs={"data-linker-call": "saveBody", "data-linker-args": "form"}) }}
</form>
<section data-state-is="step=3">
<p>主旨:<strong data-state-text="previewSubject"></strong></p>
{{ cg_button("上一步", variant="ghost", attrs={"data-linker-call": "back", "data-linker-args": "{\"to\":2}"}) }}
{{ cg_button("送出", attrs={"data-linker-call": "submit", "data-linker-confirm": "確定送出?"}) }}
</section>
<p data-state-is="step=4">完成!</p>
</main>
{% endblock %}運作方式:
- 每個方法回
data.step,寫進客戶端 state 的ticketWizard:step,data-state-is/-is-class自動切換畫面。 - 客戶端的
step只是顯示器。使用者在 DevTools 把它改成 3,畫面會跳過去,但按「送出」時伺服器的step還是 1 —— 回policy。 data-state-bind讓「上一步」回去時已填的字還在。- 按鈕用
cg_button產生,Linker 屬性放在attrs。attrs裡的 JSON 會被跳脫成{"to":1},瀏覽器讀屬性時還原成{"to":1}。
6. 驗證
- 主旨留空按下一步 → 錯誤畫在欄位旁,停在第一步。
- 在 console 執行
document.querySelector('[data-state-is="step=3"]').hidden = false再按送出 →policy。 - 送出後重新整理 → 回到第一步(新 instance)。這是規格,不是 bug。
測試的骨架(tests/tickets.rs):
rust
let post = |body| app.post(endpoints::linker_url()).acting_as(&owner).json(body);
post(call(0, "submit", json!({}))).await.assert_json(json!({ "ok": false, "kind": "policy" }));
post(call(0, "saveSubject", json!({ "subject": "" }))).await.assert_json(json!({ "ok": false, "kind": "validation" }));
post(call(0, "saveSubject", json!({ "subject": "印表機壞了" }))).await
.assert_json(json!({ "ok": true, "data": { "step": 2 }, "rev": 1 }));
post(call(1, "saveBody", json!({ "body": "卡紙" }))).await
.assert_json(json!({ "ok": true, "data": { "step": 3, "previewSubject": "印表機壞了" }, "rev": 2 }));
post(call(2, "submit", json!({}))).await.assert_json(json!({ "ok": true, "data": { "step": 4 }, "rev": 3 }));
assert_eq!(Ticket::query().count().await?, 1);注意失敗的呼叫不推進 rev:第一次成功之前一直是 0。
7. 變體:一次送出(選項 B)
所有步驟只在客戶端切換,最後一次送出。省往返,但驗證要一次做完 —— 錯的欄位可能在隱藏的步驟裡,所以用 catch 把畫面帶回去:
html
<div{{ quick_attrs }} data-state-init="step=1">
<form>
<fieldset data-state-is="step=1">
<input name="subject">
<button type="button" data-state-set="step=2">下一步</button>
</fieldset>
<fieldset data-state-is="step=2">
<textarea name="body"></textarea>
{{ cg_button("送出", type="submit", attrs={"data-linker-call": "submit", "data-linker-args": "form"}) }}
</fieldset>
</form>
</div>rust
async fn call(&mut self, ctx: &LinkerContext, _: &str, args: Args) -> laravel::Result<LinkerResponse> {
let subject = text(&args, "subject");
if subject.is_empty() || subject.chars().count() > 120 {
// catch 而不是 then:整通呼叫是失敗的,只有 catch / always 會跑。
// 不把 step 拉回去的話,錯誤會畫在 hidden 的面板裡,使用者只看到「按了沒反應」。
return Ok(LinkerResponse::validation([("subject", "主旨必填,最多 120 字。")])
.catch(Action::state_set("ticketQuick", "step", 1)));
}
let body = text(&args, "body");
if body.is_empty() || body.chars().count() > 5000 {
return Ok(LinkerResponse::validation([("body", "內容必填,最多 5000 字。")])
.catch(Action::state_set("ticketQuick", "step", 2)));
}
// 建立 Ticket…
Ok(LinkerResponse::ok().then(Action::toast("success", "已建立")))
}這個元件可以是 Stateless(const MODE: LinkerMode = LinkerMode::Stateless;):它不需要記住任何東西。state.set 的 scope 要等於 render 物件的名稱(這裡是 ticketQuick)。