Actions & Selection
Actions are server-callable operations on a row, on a set of rows, or on the table itself. They're declared on the server next to the table's controller and the table renders them in the right place — a dropdown in the row, a button on the toolbar, or a bulk button that lights up only when rows are selected. Each action can declare an @InputForm so the table opens a form dialog before submitting.
Action levels
Three scopes:
| Scope | Where it renders | Operates on |
|---|---|---|
row | per-row dropdown | one row |
rows | toolbar (bulk button) | selected rows |
table | toolbar | the table itself |
Row actions render through <AsRowActions> — a single button when the row has exactly one action, a … dropdown when it has more. Table and bulk actions render through <AsTableActions> in the toolbar.
Declaration lives on the server — @atscript/moost-db's @DbAction decorator on the table's controller. The level is inferred from the handler's parameter decorators (@DbActionID() → row, @DbActionIDs() → rows, neither → table), and the table receives the finished list — name, label, level, icon, intent — from the /meta response's actions array:
import {
AsDbController,
TableController,
DbAction,
DbActionID,
DbActionIDs,
} from "@atscript/moost-db";
import { Post } from "@moostjs/event-http";
import { Order } from "./schema/order.as";
import { ordersTable } from "./db";
@TableController(ordersTable)
export class OrdersController extends AsDbController<typeof Order> {
@Post("actions/ship")
@DbAction("ship", { label: "Ship" })
async ship(@DbActionID() id: { id: string }) {
// one identifier → level: 'row'
}
@Post("actions/export")
@DbAction("export", { label: "Export" })
async exportOrders(@DbActionIDs() ids: { id: string }[]) {
// identifier array → level: 'rows'
}
}@DbAction carries the full server-side wiring — handler, input form, intent, gating, and the level itself. See the db.atscript.dev annotations reference for the full surface. The table just renders what /meta reports.
Input forms
An action with @InputForm declares a .as type as its input schema:
export interface RefundInput {
@meta.label 'Amount'
amount: number
@meta.label 'Reason'
reason: string
}@Post("actions/refund")
@DbAction("refund", { label: "Refund" })
async refund(@DbActionID() id: { id: string }, @InputForm(RefundInput) input: RefundInput) {
// ...
}When the user invokes refund, the table opens <AsActionFormDialog>. The dialog fetches the form schema, renders it through <AsForm> (from @atscript/vue-form), and submits with the form data wrapped as { input: ... }. The dialog is mounted lazily — only when an action with @InputForm is detected on the table.
To customise the dialog body, use <AsTableRoot>'s #actionForm slot — it forwards through to the dialog. To replace the dialog entirely, swap controls.actionFormDialog (Tier 2).
Selection
state.selectedRows is a ShallowRef<unknown[]> — the primary keys (or composite-PK objects) of selected rows. The selection mode is set on <AsTable :select="...">:
"none"(default) — no checkboxes; row clicks fire the default action."single"— radio-style: row clicks replace the selection with that row's PK."multi"— checkbox column; clicks toggle selection.
<AsTable :select="select" :row-delete="canDeleteRows" />canDeleteRows is a boolean (or RowDeleteOpt) — when true, the table synthesises a __remove row action with a confirm prompt.
state.selectedCount is a computed for badge counts. To act on every row matching the filter, not only the loaded ones, see Select All Matching Rows (since 0.1.147). state.isPkSelected(pk) is the O(1) "is this row selected" predicate used internally by the checkbox cell.
Each row's selection control is a real role="checkbox" with aria-checked, an accessible name ("Select row") and a Space keyboard toggle.
Per-row selectability
:row-selectable decides, per row, whether it may be selected at all. Return false, or a string — the string becomes the disabled reason, surfaced on the control as title and inside its accessible name. Since 0.1.133.
<AsTable
select="multi"
:row-selectable="(row) => (row.archived ? 'Archived rows cannot be picked' : true)"
/>The predicate gates every path: row click, the Space/Enter toggle, and the header select-all. It is enforced by the selection model, so <AsWindowTable> honours it exactly as <AsTable> does. An ineligible row renders aria-disabled="true" on its control and data-selectable="false" on the <tr>, and it is excluded from the select-all count — so the header checkbox reads fully checked once every eligible row is picked.
Select-all never un-picks: a row that is already selected but is now ineligible keeps its selection, and it does not hold the header back from reading fully checked.
The header's select-all control is a role="checkbox" too, with aria-label="Select all rows" and Space / Enter activation.
What the header checkbox acts on
Since 0.1.142 the header checkbox acts on the loaded rows only — the rows the table is showing — and never touches the rest of the selection:
| Header state | Reads as | Click |
|---|---|---|
none (unchecked) | no eligible loaded row is selected | adds every eligible loaded row to the selection |
some (indeterminate) | some eligible loaded rows are selected | adds the rest |
all (checked) | every eligible loaded row is selected | removes the eligible loaded rows; picks elsewhere stay |
A pick on another page (with selectionPersistence: 'persist') survives both directions, and does not move the header off none. To empty the selection for real, call state.clearSelection().
<AsWindowTable> renders the header checkbox only once every row of the dataset is loaded; it then behaves as above over all rows. While part of the dataset is unloaded there is no select-all control — selecting whatever blocks happen to be cached would pick rows the user never saw. Render your own count and clear action there through the #header-__select slot (below).
state.selectAll(rows) / state.deselectAll(rows) are the same operations for your own controls: they add or remove the eligible rows' keys and leave every other key alone; state.toggleAll(rows) is the header's click over rows. Before 0.1.142 selectAll replaced the selection and the header's deselect cleared it entirely.
Row click vs. checkbox
By default a click anywhere on a row toggles it. With select-on="control" only the row's checkbox toggles; a row click just moves the active row (and still emits row-click), which suits rows the user clicks to inspect. Since 0.1.142.
<AsTable select="multi" select-on="control" />The keyboard is the same in both: Space / Enter on the active row toggles it, Space on a focused checkbox toggles that row. A click on the checkbox in control mode does not emit row-click and does not trigger the double-click main action.
Custom selection controls
The selection column is addressed like a pseudo-column named __select (as __actions is for row actions), on both <AsTable> and <AsWindowTable>. Since 0.1.142.
<AsTable select="multi" select-on="control">
<template #header-__select="{ state, toggle, selectedCount }">
<MyCheckbox
v-if="state"
:checked="state === 'all'"
:indeterminate="state === 'some'"
aria-label="Select all rows"
@click.stop="toggle"
/>
<span v-else-if="selectedCount">{{ selectedCount }}</span>
</template>
<template #cell-__select="{ selected, selectable, reason, toggle }">
<MyCheckbox
:checked="selected"
:disabled="!selectable"
:title="reason"
aria-label="Select row"
@click.stop="toggle"
/>
</template>
</AsTable>| Slot | Props |
|---|---|
#header-__select | state — 'none' | 'some' | 'all', or undefined when no select-all is available; toggle() — the header's action; selectedCount — size of the whole selection |
#cell-__select | row; index (absolute in <AsWindowTable>); selected; selectable + reason from :row-selectable; toggle() — toggles the row (gated) and makes it active |
- Call
togglefrom a handler that stops propagation (@click.stop): in the defaultselect-on="row"the click would otherwise also reach the row and toggle it back. - The slot replaces the default control's accessibility too — give yours a checkbox role,
aria-checkedand a name.
Announcing a running action
While state.actions.invoke is in flight, the <AsTableActions> trigger for that action carries aria-busy="true" and its accessible name gains a ", running" suffix (the visible label never changes). The toolbar also renders one screen-reader-only polite live region that announces "<label> running" on start and "<label> finished" / "<label> failed" on settle — it lives outside the default slot, so a custom toolbar keeps the announcements. Since 0.1.133.
Programmatic invocation
state.actions.invoke(action, pk?, opts?) invokes any action without going through the UI:
import { useTableActions } from "@atscript/vue-table";
const actions = useTableActions();
// Per-row
const result = await actions.invoke(action, { id: "order-123" });
// Bulk
const result = await actions.invoke(action, [{ id: "order-1" }, { id: "order-2" }]);
if (result.ok) {
// result.kind: 'backend' | 'navigate' | 'custom' | 'remove'
} else {
// result.kind === 'error', result.error: ClientError | Error
}pk is always an identifier object (or array of objects), never a bare scalar. This is per @atscript/db-client's invariant #11 — even a single-PK table sends { id: "..." }.
InvokeOpts.input carries the @InputForm payload for actions that have one; InvokeOpts.suppressRefresh skips the post-success re-query for this one call; InvokeOpts.event bridges to the <AsTableRoot @action> emit.
The result is a discriminated union — it never throws. Toast / log based on result.ok and result.kind.
The @action emit
<AsTableRoot @action="onAction"> fires after every action result. This is where apps wire custom processors — actions whose processor === 'custom' skip the server entirely and dispatch to client code:
function onAction(action: TVueTableActionInfo, ids: unknown[], result: ActionResult) {
if (action.processor === "custom" && action.name === "export-csv") {
void downloadCsv(apiPath, ids);
return;
}
if (!result.ok) {
pushToast(false, `${action.label} failed: ${result.error.message}`);
return;
}
if (result.kind === "remove") {
const removed = (result.data as { deletedCount?: number })?.deletedCount ?? 1;
pushToast(true, `Deleted ${removed} row(s).`);
}
// ...
}For CSV export, reach for the native useTableExport() hook instead — it reuses the table's live query, its visible column order and its cell-value resolution, and pages through every matching row. The custom-action route above stays the right answer when the export must run server-side (a signed URL, a heavy report job): declare the action as processor: 'custom' on the .as, then match it by name in the @action handler.
Native new-tab navigations are silent to @action
When a navigate action is opened in a new tab (middle-click, cmd/ctrl+click), the browser owns the navigation — it does not call invoke and does not fire @action. Only a plain left click on a navigate action routes in-SPA and emits (with kind: 'navigate'). Don't hang new-tab side effects off @action.
Navigate actions
An action declared with processor: 'navigate' (see the db.atscript.dev annotations reference) sends the user to a URL instead of mutating a row. The table renders these as real <a href> anchors — so all native link affordances work: middle-click and cmd/ctrl+click open a new tab, right-click offers "copy link address" / "open in new tab", and the URL previews in the status bar on hover. Menu items in the … dropdown render as links too.
Declare one server-side with processor: 'navigate' and a value template — $1 is the row identifier placeholder (see the db.atscript.dev annotations reference):
@DbRowActions({
view: { label: "View", processor: "navigate", value: "/customers/$1" },
})
class CustomersController extends AsDbController<typeof Customer> {}When it renders as a link
An action becomes an anchor when all hold:
processor === 'navigate';- it has no confirm prompt (
promptText); - it has no
@InputForm; - a href is computable.
The href is computed at render time from the action's value. For a row-level action, $1 is replaced with the row's URL-encoded preferredId — the same interpolation the client performs on invoke. A row with no identifiable primary key (empty preferredId) yields no href and the action falls back to a <button>. Confirmable navigate actions and @InputForm navigate actions also stay buttons.
The signature of the render-time helper — navigateHrefFor — is exported from @atscript/ui for consumers building their own action chrome.
Click semantics
| Gesture on a linkable navigate action | What happens |
|---|---|
| Plain left click (no modifier key) | preventDefault() → routed through the normal invoke path. SPA routing runs via the client's navigate hook and @action fires with kind: 'navigate'. |
| Middle click / cmd(ctrl)+click / right click | Native browser behaviour (new tab, copy link, …). No invoke, no @action emit — the current tab's state is unchanged. |
Confirmable navigate actions (those with a confirm prompt) stay <button>s, because a confirm dialog can't guard a native anchor navigation. On them a middle-click / cmd+click runs the same confirmation, then on accept opens the target in a new tab via window.open(href, "_blank", "noopener,noreferrer") — still no invoke, no emit. A plain left click confirms then invokes, exactly as before.
DOs and DON'Ts
- DO treat a plain left click as the only navigate gesture that reaches your app — SPA routing and
@actionboth run there. - DON'T rely on
@actionto observe new-tab navigations. Modified and middle clicks are native and silent to the emit; put nothing on@actionthat a new-tab open must trigger. - DO set
resolveHrefwhen your app is served under a router base path (see below); root-hosted apps need nothing.
resolveHref for base-path apps
action.value is interpolated to a raw path like /customers/1. When your app is served under a router base path, map that raw path to a fully-resolved href with the resolveHref prop on <AsTableRoot> (also a useTable({ resolveHref }) option):
<AsTableRoot url="/api/db/tables/customers" :resolve-href="resolveHref" />import { useRouter } from "vue-router";
const router = useRouter();
const resolveHref = (url: string) => router.resolve(url).href;resolveHref is applied only to the anchor's href attribute and the new-tab window.open target — never to the plain-left-click invoke path. That path goes through the client's navigate hook, which already accounts for the base. Default is identity (url) => url.
Wiring vue-router: both halves
The two halves are separate on purpose and an SPA needs both. resolveHref paints the link; the client's navigate hook performs the navigation. Without navigate, a plain left click on a navigate action does a full page load — the browser's default — which drops your app's in-memory state.
Set the hook once, app-wide, through the client factory:
// main.ts — after the router exists
import { setDefaultClientFactory } from "@atscript/vue-table";
import { Client } from "@atscript/db-client";
import { router } from "./router";
setDefaultClientFactory((url) => new Client(url, { navigate: (to) => router.push(to) }));…and resolve hrefs on the table:
<script setup lang="ts">
import { useRouter } from "vue-router";
const router = useRouter();
</script>
<template>
<AsTableRoot url="/api/db/tables/customers" :resolve-href="(url) => router.resolve(url).href" />
</template>With both in place a plain click routes in-SPA, cmd/middle-click opens a real new tab at the resolved href, and "copy link address" yields a URL that works when pasted.
Navigate actions are gated by per-row $actions exactly like any other action (see Per-row action availability), and their ActionResult on the invoke path is { ok: true, kind: 'navigate' }.
Selecting and extending row actions
The row-actions cell shows every row / rows action the server declared for the table. One screen often wants fewer of them, different wording, or an action the server has no idea about. That is the :row-actions prop on <AsTableRoot>. Since 0.1.134.
<AsTableRoot
url="/api/db/tables/orders"
:row-actions="{
include: ['approve', 'cancel'],
overrides: { cancel: { label: 'Void', intent: 'negative' } },
extra: [
{ name: 'audit', label: 'Audit trail', icon: 'i-as-list', onInvoke: (row) => openAudit(row) },
{ name: 'print', label: 'Print', href: (row) => `/print/orders/${row.id}` },
],
}"
/>| Field | Effect |
|---|---|
include | Allowlist of server action names. Omit for "all of them". |
exclude | Denylist, applied after include. Also removes an extra of the same name. |
overrides | Per-name label / icon / intent / promptText patch. |
extra | App-owned actions, appended after the server ones. |
The server stays authoritative. The per-row $actions gate runs first; include can only narrow what a row was already allowed, and overrides change appearance only. Naming a gated action in include does not bring it back.
extra actions are the app's own, so include does not apply to them — being listed in extra is the opt-in. include: [] therefore hides every server action while keeping the extras, which is how a screen replaces the row actions wholesale. Each takes either:
href(row)— rendered as a real<a>throughstate.resolveHref, with all the native link affordances of a navigate action; oronInvoke(row, pk)— awaited locally, then settled as an@actionemit withkind: 'custom'(a rejection settles askind: 'error').
Add promptText for a confirmation, and enabled(row) to hide the action on rows it doesn't apply to (false) or show it disabled with a reason (a string — see Disabled with a reason).
The same policy drives the single-button form, the … dropdown, a standalone <AsRowActions> mounted inside the table, the <AsTableActions level="row"> toolbar and the main action — every surface reads one compiled policy from the table context, so an excluded or relabelled action cannot reappear in another one. Pass :actions on <AsRowActions> to render an explicit list instead, bypassing both the server set and the policy.
DOs and DON'Ts
- DO use
include/excludefor per-screen presentation; keep authorization on the server. - DO give every
extraaction a name that can't collide with a server action. - DON'T expect
overridesto unlock anything — it is cosmetic. - DON'T put a mutation behind
onInvokethat the server should own;extrais for client-side affordances (drawers, print views, audit panels).
Row-level default action
A row action can be marked default. The framework's main-action path invokes it on dblclick or Enter when the table is in select="none" mode. Single-click is always reserved for cursor placement / selection — never the default action. The current default is exposed as state.actions.default.row.
The main-action (and the @main-action emit) always operate on the currently active row, resolved by state.getActiveRow() — the single nav-mode-aware resolver (page-relative in pagination, absolute in windowed mode). This resolves correctly on every page, including page ≥ 2 in paginated tables. The same resolver backs selection and the <AsTableActions level="row"> toolbar, so all three stay in sync.
Without a @main-action listener, the default is resolved for the active row exactly like the row-actions cell resolves it: the row's availability first, then the :row-actions policy. So Enter and double-click do nothing on a row whose default the server hid or disabled (with or without a reason), or that the policy excludes or leaves out of include; overrides apply (an overridden promptText asks first). A registered @main-action listener still receives every request — your handler decides. Since 0.1.144; earlier releases fired the declared default regardless and let the server reject it with a 409.
The selection state is reactive end-to-end: a multi → none transition auto-clears selectedRows; the actions column appears / disappears live without a remount; bulk action buttons disable when nothing is selected.
Per-row action availability
state.includeActions is a writable ref controlled by the renderer. The <AsTable :row-actions-column="..."> prop (or <AsWindowTable>'s equivalent) flips it on — and renders the column — when the row menu has anything to show: a row-level action, a rows-level one (they join every row's menu), or an app-owned extra action. Up to 0.1.146 only row-level actions counted, so a table whose actions were all rows-level got no column. When on, buildTableQuery requests per-row $actions: string[] from the server — the names of the actions the server evaluated as enabled for that row.
The table gates its action chrome against that list:
- Per-row dropdown and the single-selection toolbar hide any action whose name is absent from that row's
$actions— unless the server gave a reason (see Disabled with a reason). - Bulk selection (≥2 rows) enables a bulk action when at least one selected row allows it — the union of the selected rows'
$actions. An action enabled for only part of the selection stays available; the server re-checks every row at invoke time: withonDisabledRows: 'skip'it runs on the rows that qualify, with the default'reject'it answers 409 with the per-row reasons (an error result, see below). - The toolbar gates on the loaded rows of the selection (
state.selectedRowObjects), so gating also works whenrowValueFnreturns a scalar key. A selected row that is no longer loaded (another page, scrolled out of the window cache) has no verdict on the client: it never enables an action by itself, and a selection with no loaded row at all is not gated — the server's invoke-time check decides. Since 0.1.144; earlier the toolbar skipped gating for scalar selections.
Every server-declared action is gated this way regardless of its processor (backend, navigate, custom). The one exemption is the client-synthesised __remove (from :row-delete): its name never appears in $actions, so its visibility is governed by the table's canRemove flag instead — the server still authorises the delete at call time. Tables that don't opt into the actions column (no $actions in the payload) skip gating entirely and render every declared action.
Disabled with a reason
When a server disabled predicate returns a string instead of true, the row carries it in $disabledReasons (needs @atscript/db 0.1.141+; see the server's disabled reasons). The table then shows the action disabled instead of hiding it. Since 0.1.144.
@DbAction<Order, ["status"]>("ship", {
label: "Ship",
requiredFields: ["status"],
disabled: perRow((o) => (o.status === "shipped" ? "Order already shipped" : false)),
})| Row verdict | In the table |
|---|---|
name in $actions | enabled |
name in $disabledReasons | shown disabled, with the reason |
in neither (true verdict) | hidden (unchanged) |
How a disabled action looks and behaves:
- Rendered, focusable, inert. Buttons and menu items carry
aria-disabled="true"and dimmed styling but stay reachable by Tab / arrow keys, and their accessible name appends the reason ("Ship, Order already shipped"; buttons also use it astitle). Menu items show the reason on its own line under the label. Click, Enter, middle-click and cmd-click do nothing, and a disablednavigateaction is never a link. - Bulk: an action no selected row allows is shown disabled when any row gave a reason, listing the distinct reasons, up to three (
"Locked; Already archived; +2 more"). Enabled for any row wins. :row-actionsoverridesrelabel a disabled action and keep its reason;include/excludestill hide it. A client-onlyextraaction is disabled the same way whenenabled(row)returns a non-empty string.- Custom chrome:
<AsTableActions>'button/menu-itemslots replace only the content — the wrapper keeps the disabled state, so renderaction.disabledReasonif you want it visible. A fulldefault-slot replacement must render the disabled state itself (itsinvokeignores a disabled action); so must a custom row-actions cell, which gets its actions fromresolveRowActions— see Customization.
The server stays authoritative: a request that gets past the UI anyway is rejected with a 409 ActionDisabledError whose message is the reason, so the @action emit's result.error.message is toast-ready. The db-client error also exposes .reason / .reasons.
DO return reasons the user can act on ("Only processing orders can be shipped"). DON'T put data the caller may not see into a reason — it reaches the browser verbatim. DON'T return a reason for actions that make no sense on a row; true keeps them hidden.
Row actions on a view
A view controller that declares @DbActionsFrom(() => SourceController) (moost-db, see view-delegated actions) lists its source table's row actions in its own /meta and $actions. The table needs nothing extra: the row menu, the toolbar, disabled reasons, input forms and confirmations work as for the table's own actions. Since 0.1.147.
What happens under the hood, and what it means for your screen:
- Each delegated entry carries
owner(the source's base path) and, usually,idMap— the source's identifier field → the view column that holds it ({ id: "taskId" }). The table keeps those columns on every identifier it builds (tableDef.identifierFields=preferredId+ theidMappaths) and the client maps them to the source's id before POSTing to the source's route (value). Input forms load from the source (formUrl). - The view usually has no
preferredId; identifiers are then built from theidMapcolumns alone. The server adds those columns to$selecteven when they are not visible, so hiding the column is fine. - A selection key whose row is not loaded (a scalar
rowValueFnafter paging away) cannot be mapped; the action settles as an error result naming the missing column. Keep the defaultrowValueFn(the row object) on view tables, or a key that is one of theidMapcolumns. - Delegated actions that accept a query target run on all matching rows like own ones — the request goes to the view (
queryTarget.url), which resolves the view rows and runs the source action on them.
Next steps
- Customization — swap dialogs and row action chrome.
- Server-Side Presets — wire up the Moost backend.