Responses and actions
The server doesn't send JS; it sends "which named action to run".
LinkerResponse
use cg_component::runtime::linker::{Action, FailureKind, LinkerResponse, messages};
// Success: data is written to client state
LinkerResponse::ok().data("matchCount", 12);
// Failures
LinkerResponse::validation([("email", "Already taken")]);
LinkerResponse::policy("No permission.");
LinkerResponse::not_found();
LinkerResponse::fail(FailureKind::Service).message("The stock service is temporarily unavailable");| Constructor | kind | Default message |
|---|---|---|
ok() | success | — |
validation(errors) | validation | 有欄位需要修正。(some fields need fixing) |
policy(message) | policy | (yours) |
not_found() | service | 找不到這筆資料。(not found) |
fail(FailureKind::Service) | service | 操作忙碌中,請稍後再試。(busy, try again) |
fail(FailureKind::Expired / Conflict) | Usually returned by the framework | — |
.message(text) | Replaces the default message | — |
.data(key, value) | Adds a key to data; the value is serialized with serde | — |
The default messages are in the messages module; they're the strings from PHP's lang/zh_TW/linker.php (messages::POLICY, messages::EXPIRED…).
You can also just return Err: errors from call are translated into a kind by HTTP status; see Errors.
Pipeline
Ok(LinkerResponse::ok()
.then(Action::toast("success", "Saved"))
.then(Action::state_clear("customerForm"))
.then(Action::render_fragment("#list", "customers.results", json!({ "mode": "results" })))
.catch(Action::focus("#name"))
.always(Action::state_set("ui", "busy", false)))| Method | When it runs |
|---|---|
.then(action) | The call succeeded and no earlier step failed |
.catch(action) | The call failed, or an earlier step threw |
.always(action) | Always |
PHP's ->call() is Rust's .then().
The pipeline still runs when the whole call fails, only catch and always are left. That's useful for a multi-step form submitted at once, where the bad field may be in a hidden step:
LinkerResponse::validation([("body", "A body is required.")])
.catch(Action::state_set("ticketQuick", "step", 2))On failure, data is not written to client state; only the pipeline runs.
Built-in actions
| Action | Arguments (? optional) | Rust shortcut | Effect |
|---|---|---|---|
dom.scrollTo | target | Action::scroll_to(target) | Scroll to an element |
dom.class | target, class, on? | Action::class(target, class, on) | Toggle a class |
dom.repeat | items, ref?, mode? | Action::new("dom.repeat", …) | Render a list from a reference row; see dom.repeat |
form.focus | target | Action::focus(target) | Focus a field |
form.reset | target? | Action::reset(target) | Reset a form (by default the first form in the mount point) |
state.set | scope, key, value | Action::state_set(scope, key, value) | Write client state |
state.clear | scope | Action::state_clear(scope) | Clear a namespace |
render.fragment | target, name, params?, fresh? | Action::render_fragment(target, name, params) | Ask render fragments to redraw a block |
render.page | name, params?, url? | Action::render_page(name, params, url) | Replace the whole page |
ui.toast | level, message | Action::toast(level, message) | A notification; level is error / warning / anything else (success style) |
ui.confirm | message, title?, label?, target?, level?, destructive? | Action::confirm(message) | A confirm dialog; returns Promise<boolean>, and the pipeline waits |
Notes:
- The
targetselector ofdom.*andform.*only searches inside the mount point (within(context, selector)). The server can't touch nodes outside it. - Rust's
BUILTIN_ACTIONSalso has aui.test, which the syncedactions.jsdoesn't implement; don't use it.
This list is the complete answer to "the most the server can make the browser do". The JS implementations are in resources/js/cg/linker/actions.js; the argument specs are BUILTIN_ACTIONS in crates/cg-component/src/runtime/linker/response.rs.
Arguments are checked when the response is built
Action::new(name, args) returns Result<Action, String>:
- The name must look like
scope.name(^[a-z][a-z0-9]*\.[a-z][a-zA-Z0-9]*$). - Built-in actions: a missing required argument, an unknown extra argument or a wrong type (
string/int/number/bool/array/mixed) all returnErr. - The shortcuts (
Action::toastetc.) take typed arguments and can't fail.
Action::new("ui.toats", json!({})) // Ok: the name is valid, but…
Action::new("render.fragment", json!({ "target": "#x" })) // Err: missing argument name
Action::new("render.fragment", json!({ "target": "#x", "name": "list", "fresh": true })) // OkA name that isn't in the built-in table, like ui.toats, is let through as a custom action (Rust doesn't know what you registered in JS), and only fails in the browser because nothing is registered under it, jumping to catch. Prefer the shortcuts for built-in actions.
Inside call, convert to laravel::Error with ?:
let repeat = Action::new("dom.repeat", json!({ "ref": "rows", "items": rows })).map_err(laravel::Error::msg)?;Custom actions
Action::new("app.highlight", json!({ "target": "#row-3" }))And register it in JavaScript (resources/js/site.js or a file it imports):
import { registerLinkerAction, within } from './cg/runtime.js';
registerLinkerAction('app.highlight', (args, context) => {
within(context, args.target)?.classList.add('is-highlighted');
});Rules and review: see Action governance.
The response JSON
{"ok": true, "data": {"count": 1}, "pipeline": [{"fn": "ui.toast", "args": {"level": "success", "message": "+1"}, "on": "then"}],
"instance": "…", "rev": 1}
{"ok": false, "kind": "validation", "message": "有欄位需要修正。", "errors": {"name": ["Please enter a name."]},
"data": {}, "pipeline": []}Stateful responses also carry instance and rev; Stateless responses carry the renewed url on success or validation failure.