Actions and signals
Server actions, typed patches, client signals and client expressions.
An action is a route type and a handler. A template invokes it with a struct literal. The handler answers with typed patches.
A signal is a value in the browser. It belongs to one component instance.
gx new slice todoRoutes of the example
// Package route holds the route types of the todo slice. A route
// package holds only route types.
package route
import "github.com/alternayte/gx"
// Index is the list page.
type Index struct {
gx.Route `GET /todo`
}
// Add adds one item. Title comes from the Title signal of the page.
type Add struct {
gx.Route `POST /todo/add`
Title string `signal:"title"`
}
// Rules checks the title. The browser controls each signal value.
func (in *Add) Rules() gx.Rules {
return gx.Rules{gx.Field(&in.Title, gx.Required, gx.MaxLen(80))}
}
// Clear removes every item.
type Clear struct {
gx.Route `POST /todo/clear`
}
// Count gives the number of items. The page asks for it when the count
// comes into view.
type Count struct {
gx.Route `GET /todo/count`
}Signals and client expressions
The signals block declares each signal with a type and a first value. Inside the markup, $Name is the signal.
The first value can read the props. Use this to start a signal from server data, for example from a query value that the loader puts in a prop: Q string = p.Q. A page load then starts the signal from the URL.
An attribute that reads a signal is a client expression. Gx changes it into the syntax of the adapter. Signals and client expressions need the Datastar adapter: read Adapters. A client expression is a small part of Go: literals, signals, values from the server, operators, and the functions of package gxc.
| Directive | Example | Meaning |
|---|---|---|
show |
show={$Open} |
Shows the element when the value is true. |
text |
text={$Title} |
Sets the text of the element. |
bind:<prop> |
bind:value={$Title} |
Joins an input and a signal in two directions. |
class:<name> |
class:font-semibold={$Open} |
Adds or removes a class. |
attr:<name> |
attr:aria-expanded={$Open} |
Sets an attribute. |
on:<event> |
on:click={$Open = !$Open} |
Runs signal statements or invokes an action. |
package todo
import "acme/todo/route"
props {
// Items is the list at the first load.
Items []string = nil
}
signals {
// Title is the text of the new item.
Title string = ""
// Open shows the help text.
Open bool = false
}
<gx.Head title="To do" />
<h1 class="text-2xl font-semibold">To do</h1>
<div class="mt-4 flex gap-2">
<input type="text" aria-label="Title" bind:value={$Title} class="rounded-md border border-border px-3 py-2" />
<button class="rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground" on:click={route.Add{}}>Add</button>
<button class="rounded-md border border-border px-3 py-1.5 text-sm" on:click={route.Clear{}}>Clear</button>
</div>
<p class="mt-2 text-sm text-muted-foreground">New item: <span text={$Title}></span></p>
items := p.Items
<ul #items(items []string) class="mt-4 list-disc pl-5">
for _, item := range items {
<li>{item}</li>
}
</ul>
<button class="mt-4 text-sm underline" on:click={$Open = !$Open} attr:aria-expanded={$Open}>Help</button>
<p show={$Open} class:font-semibold={$Open}>Write a title and press Add.</p>
<p class="mt-4 text-sm" on:visible={route.Count{}}>
<span id="todo-count">Counting</span>
</p>Answers of an action
| Answer | Effect |
|---|---|
c.Patch(nodes...) |
Sends fragments. The browser morphs each one into the element with the same id. |
c.Update(node) |
Takes a component from new data and sends only the fragments that changed. |
c.SetSignals(v) |
Sets the signals of the instance that invoked the action. |
c.Redirect(route) |
Goes to a page. |
c.Toast(text) |
Shows a toast in the toaster region. |
nil with no call |
Answers 204. The page does not change. |
A redirect loads the next page in full. A toast that the handler queues with a redirect does not go to the current page. It goes in the signed cookie gx_flash. gx.Toaster() shows it on the next page. Read Forms.
Give an element with an on: action the attribute data-gx-close="success". The runtime then closes the nearest dialog or popover when the answer has a status of 2xx and no header Gx-Error. An error of the handler keeps the dialog open. Read Forms.
A patch can render an open modal dialog closed, for example a patch of the element that holds the dialog. The runtime then closes the dialog before the morph, so the rest of the page takes clicks again. The runtime finds the dialog in the new content by its id. A dialog with no id has the same position below its nearest parent with an id.
An answer that is a page and not patches loads that page in full. An example is the redirect to the sign-in page that a middleware sends for an expired session. The rule is for the requests that Gx writes: an on: action, a form and the action of a toast. A Datastar action or an hx-get that you write by hand keeps the swap of its adapter.
Gx generates a function for each fragment and a Signals struct for each component with signals. Here they are IndexViewItems and IndexViewSignals.
A fragment of a component with signals takes the instance key as its first parameter. gx.ScopeKey reads the key from the request.
// Package todo is the todo slice: its pages, actions and views.
package todo
import (
"strconv"
"sync"
"github.com/alternayte/gx"
"acme/todo/route"
)
// The items live in memory. A real app uses a database.
var (
mu sync.Mutex
items []string
)
// IndexPage is the list page.
var IndexPage = gx.Page(func(c *gx.Ctx, in route.Index) (IndexViewProps, error) {
mu.Lock()
defer mu.Unlock()
return IndexViewProps{Items: append([]string(nil), items...)}, nil
}, IndexView)
// Add adds one item, patches the list and empties the text field.
var Add = gx.Action(func(c *gx.Ctx, in route.Add) error {
mu.Lock()
items = append(items, in.Title)
list := append([]string(nil), items...)
mu.Unlock()
key := gx.ScopeKey(gx.Scope(c.R), "todo.IndexView")
if err := c.Patch(IndexViewItems(key, list)); err != nil {
return err
}
return c.SetSignals(IndexViewSignals{Title: ""})
})
// Clear removes every item and patches the empty list.
var Clear = gx.Action(func(c *gx.Ctx, in route.Clear) error {
mu.Lock()
items = nil
mu.Unlock()
key := gx.ScopeKey(gx.Scope(c.R), "todo.IndexView")
return c.Patch(IndexViewItems(key, nil))
})
// Count patches the count. The element has the id that the patch names.
var Count = gx.Action(func(c *gx.Ctx, in route.Count) error {
mu.Lock()
n := len(items)
mu.Unlock()
return c.Patch(gx.El("span", gx.Attrs{{Key: "id", Value: "todo-count"}}, gx.Text(strconv.Itoa(n)+" items")))
})
// Routes lists every page, action and form of the slice.
var Routes = gx.Collect(IndexPage, Add, Clear, Count)/todo
The page of the sample app
Automatic updates
c.Update(node) takes the component of the action, made from new data. You write no list of fragments.
- The page gives each fragment a hash of its content, in the attribute
data-gx-h. - The browser sends the hashes with each request to the site. A
GETaction, for example a poll, sends them too. - The server renders the component and compares the hash of each fragment.
- Only a fragment with a different hash goes to the browser.
The server keeps no state for a user between two requests.
A fragment is the unit of an update. A change inside an inner fragment sends only the inner fragment. A new or a removed inner fragment sends the fragment around it. A component with no fragment goes as a whole, and gx check gives the hint GX4012 for a large one.
A fragment that holds a link to the current page has a different hash in an action answer, so it always goes. Use c.Patch when you know the exact fragment.
Optimistic updates
An optimistic:<event> directive changes signals before the request of the action, so the page shows the result immediately. Write it beside the on:<event> handler of the action: <button on:click={route.Like{}} optimistic:click={$Count++}>.
- The runtime saves the value of each signal that the statements write.
- The statements run. The page shows the new values.
- The request of the action goes to the server.
- When the action succeeds, the answer of the server wins. A
c.SetSignalsor a patch replaces the optimistic value. An action with no answer keeps it. - When the action fails, the runtime puts the saved values back. A failure is an error of the handler, a rule failure, an error status or no network.
The directive changes signals only. To show an optimistic row or label, bind it to a signal with show or text.
The request of an optimistic update goes one time. The adapter does not send it again after a failure.
A Gx form has no on:submit handler: optimistic:submit on an element that spreads p.F.Attrs() runs just before the runtime sends the form. Read An optimistic form.
An action with .debounce or .throttle sends its request later, so its optimistic directive has no rollback. gx check reports GX4013 for a directive with no action.
Shared signals
A signal with the word shared has one value for each viewer of a room. Use it for presence, a typing mark or a cursor.
- Write the word before the name:
signals { shared Typing bool = false }. - Give the component a prop of type
gx.Room. - In the loader, make the key of the room:
gx.RoomKey(c, "doc-42"). Each viewer with the same key is in the same room. - Mount the routes of the room in a group of the app. Gx generates them as
<Component>Room:app.Group("/", auth, notes.Routes, notes.NoteRoom).
A change of a viewer goes to the server, and then to each viewer of the room. The writer gets it back too.
- The key has a signature. A viewer cannot change the key in the page to enter a different room. The server answers 403 to a key that it did not sign.
- The page carries a token for one component. The token of the room of one component is not valid at the room of a different component.
- The token has an expiry. A new token is valid for one hour or more. The stream gives the page a new token before the expiry. A page that has no connection for longer than the life of its token must load again.
- The middleware of the group runs. The stream and each write are requests to the routes that you mounted.
- The value passes rules. Write a
Rules()method on the generated<Component>Signalsstruct. A value that fails a rule reaches no viewer, and the page of the writer shows the value of the room again. - A rule with no field reads the room. For a signal that a write does not hold, the rule gets the last value of the room.
- A shared signal is not durable. The room holds the last values while it has a viewer. Keep data that must stay in your database.
An app with one replica needs no setup. For more than one replica, give gx.Config two values:
Bus: your implementation ofgx.Bus, for example onLISTENandNOTIFYof your database. Without it, each replica has its own rooms.Secret: the same bytes on each replica. Without it, each process signs with its own secret, and a key of one replica is not valid on a second replica.
gx dev writes the bus of the app to its log. gx check reports GX4014 for a shared signal with no room. Under the htmx adapter a signal is a compile error.
Server topics
A server topic tells an open page that data changed. Use it when code outside a request changes the data of a page: a background job, a queue worker or a second process.
- Give the component a prop of type
gx.Topic. - In the loader, make the topic:
gx.TopicKey(c, "orders:"+userID). The middleware of the group ran before the loader, so the loader decides who can listen. - In the component, write the directive with an action:
<ul id="orders" on:topic(p.Orders)={route.Fresh{}}>. - When the data changes, call
app.Publish(ctx, "orders:"+userID). Any goroutine can call it. It needs no request.
Each open page that listens to the key runs its own action. The action runs with the session and the props of its viewer, as each action does, and its answer patches the page. The stream carries only the name of the topic, never HTML or data.
- The key has a signature. The page carries a token of the key with an expiry and a signature of the server. The stream answers 403 to a token that the server did not sign, or that expired. A room token is not valid as a topic token.
- The token has an expiry. A new token is valid for one hour or more. The stream gives the page a new token before the expiry.
- A page has one stream. The stream at
/_gx/topicscarries each topic of the page. The page opens it again when a patch or a navigation changes its topics. - The stream comes back. An idle stream sends a comment every 25 s, so a proxy keeps it open. When the server closes the stream, the page opens it again after 1 s, then after 2 s, 4 s and up to 30 s. After the stream opens again, each element that listens runs its action one time, because a
Publishcan have come while the stream was closed. When the stream answers 403, the tokens expired: each element runs its action one time, and the page opens the stream again when a patch brings new tokens. - A burst gives one run. The first message for a stream starts a wait of 250 ms. The stream then sends one event for each topic that changed. 100
Publishcalls in 100 ms run the action of a page one time. - The bus carries the messages.
Publishgoes throughgx.Config.Bus. Two replicas with a shared bus reach the pages of each other. Each replica needs the sameSecret. - A message is not durable. A page with no connection misses the message. It shows the new data at its next load.
- The page loads the module only when it needs it. A page with no
on:topicloads notopic.jsand opens no stream.
on:topic works under the Datastar adapter and under the htmx adapter. It takes no modifier. gx check reports GX4015 for an argument that is not a gx.Topic. It gives the hint GX4016 for a constant key with no Publish, and for a Publish of a constant key that no gx.TopicKey makes.
The JSON wire
.API() on an action gives it a JSON answer for a client that is not a page: a mobile app or a script. The page still gets its patches from the same action.
- A request to the address of the action with
Accept: application/jsongets JSON. - The input comes from the path, the query and a JSON body. It passes
Rules(). - The answer is the value that the handler gives to
gx.ToolResult(c, v). With no value, the status is 204. - A rule failure is status 422 with the field and the key of each error.
- An action with no
.API()answers 406 to such a request.
gx api writes an OpenAPI 3.1 file and a TypeScript client for the marked actions. The client has one function for each action, with the types of its input and of its result.
Events and modifiers
An on: directive takes a browser event name.
| Modifier | Meaning |
|---|---|
.prevent |
Calls preventDefault. |
.stop |
Stops the event at this element. |
.once |
Runs one time. |
.outside |
Runs for an event outside the element. |
.window |
Listens on the window. |
.debounce(300ms) |
Waits until the events stop. |
.throttle(1s) |
Runs at most one time in the period. |
.concurrent |
Sends a request for each event, also while a request of the element is in flight. |
.background |
Lets interval run while the page is hidden and while the request of the last tick is open. |
Three special events invoke a GET action with no click: load, visible and interval(5s). Use them for a part that loads late and for polling. The event topic(p.Orders) runs an action when server code publishes the key of the topic (see Server topics).
Polling
An interval action is a poll. A poll does not send a request while the page is hidden, for example in a background tab. When the page shows again, the poll runs one time at once, so the page does not show old data for a full period. A tick does not send a request while the request of the last tick is open, so each request of a slow handler completes.
To poll while the page is hidden, add .background: on:interval(5s).background={route.Fresh{}}. Each tick then sends a request, and a new request cancels the open one. The modifier is for interval only.
A poll that calls c.Update sends only the fragments that changed (see Automatic updates).
A request in flight
An element that invokes an action gets aria-busy="true" when its request takes more than 100 ms. The mark goes when the last answer arrives or fails. A second click, dblclick or submit of the element before the answer arrives sends no request, so a double click sends one request. An optimistic update of the element does not run for that event too. Style the pending state with CSS:
button[aria-busy="true"] { opacity: 0.6; cursor: progress; }Each other user event, such as input.debounce(300ms), keeps the mark and sends a request for each event. The newest request wins: the adapter cancels or drops the answer of the earlier request. The modifier .concurrent does the same for a click. The events load, visible, interval and topic set no mark.
The events load, visible and topic send each request. A poll skips a tick while its last request is open (see Polling).
One scope for each instance
Each instance of a component has its own signals. Two carts on one page keep two Qty values.
A component with signals that renders more than one time needs key={expr}. In a loop with no key, that is the diagnostic GX2012.
What a client expression cannot do
- It cannot call a Go function, except the functions of package
gxc. Read GX4005. - It cannot use a type or an operator that gives a different result in JavaScript. Read GX4007.
- It cannot read a
gx.Secretvalue. Read GX7002.
A value from the server in a client expression goes into the page as JSON. The reader can see it.
Errors
An action that returns an error shows a toast in production. In gx dev, the error overlay shows the error.
A rule failure of the input, such as a tampered signal value, shows an error toast with the field and the message. The answer has status 200 and the header Gx-Error, so the runtime puts the values of an optimistic update back.