Skip to content

Responses and actions ​

The server doesn't send JS; it sends "which named action to run".

LinkerResponse ​

rust
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");
ConstructorkindDefault 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 ​

rust
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)))
MethodWhen 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:

rust
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 ​

ActionArguments (? optional)Rust shortcutEffect
dom.scrollTotargetAction::scroll_to(target)Scroll to an element
dom.classtarget, class, on?Action::class(target, class, on)Toggle a class
dom.repeatitems, ref?, mode?Action::new("dom.repeat", …)Render a list from a reference row; see dom.repeat
form.focustargetAction::focus(target)Focus a field
form.resettarget?Action::reset(target)Reset a form (by default the first form in the mount point)
state.setscope, key, valueAction::state_set(scope, key, value)Write client state
state.clearscopeAction::state_clear(scope)Clear a namespace
render.fragmenttarget, name, params?, fresh?Action::render_fragment(target, name, params)Ask render fragments to redraw a block
render.pagename, params?, url?Action::render_page(name, params, url)Replace the whole page
ui.toastlevel, messageAction::toast(level, message)A notification; level is error / warning / anything else (success style)
ui.confirmmessage, title?, label?, target?, level?, destructive?Action::confirm(message)A confirm dialog; returns Promise<boolean>, and the pipeline waits

Notes:

  • The target selector of dom.* and form.* only searches inside the mount point (within(context, selector)). The server can't touch nodes outside it.
  • Rust's BUILTIN_ACTIONS also has a ui.test, which the synced actions.js doesn'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 return Err.
  • The shortcuts (Action::toast etc.) take typed arguments and can't fail.
rust
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 }))  // Ok

A 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 ?:

rust
let repeat = Action::new("dom.repeat", json!({ "ref": "rows", "items": rows })).map_err(laravel::Error::msg)?;

Custom actions ​

rust
Action::new("app.highlight", json!({ "target": "#row-3" }))

And register it in JavaScript (resources/js/site.js or a file it imports):

js
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 ​

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.