Filters: sorting, URLs and UI
Sorting
Section titled “Sorting”Sort is a { field, dir }[]. Parse the compact query form and render it
allow-listed to columns (the SQL adapters expose buildOrderBy):
import { parseSortParam, serializeSort } from "@xtandard/lib/filters";
const { sort } = parseSortParam({ value: "createdAt:desc,name:asc" }); // asc/desc, any case; missing → desc; other → droppedserializeSort({ sort }); // "createdAt:desc,name:asc"
// drizzle / kysely:const { orderBy } = buildOrderBy({ sort, columns, defaultSort: [{ field: "createdAt", dir: "desc" }],});db.select() .from(t) .orderBy(...orderBy);In memory, buildComparator from @xtandard/lib/filters/memory takes the same
sort/defaultSort with paths and returns { compare } for Array.prototype.sort.
PostgREST’s buildOrder returns order terms and Elasticsearch’s buildSort a
sort array, both with an optional nulls: "first" | "last".
Use
buildOrderBywithdb.select(...).orderBy(...), not the RQB query — RQB aliases the root table and breaks column-referencing SQL.
Compact URL encoding
Section titled “Compact URL encoding”The model is intentionally verbose — { kind, operator, value } is great DX in
code. But in a URL it’s noisy: a three-clause group can run past 300 chars. The
compact codec shrinks the wire form without touching the model — encode
right before you put it in the address bar, decode right after you read it.
It does three things: flattens the filter wrapper into the column node,
collapses connectives to a single key ({ and: [...] } / { or: [...] } /
{ not: … }), and abbreviates keys + operators (field→f, operator→o with
short codes like contains→ct, inArray→iA). It is also spec-aware:
kind is not stored — it’s recovered on decode from the field → kind
allow-list the client already has (a resource’s _metadata). Decode is
defensive: a leaf with a field not in the allow-list, an unknown operator code,
or a wrong-typed argument (one bad element in a values list is enough) is
dropped whole (the same posture as the compiler), and you still
validate the reconstructed model as usual.
flowchart LR NODE["FilterNode<br/>(verbose model)"] -->|compactFilterNode| CMP["compact form<br/>(no kind, short keys)"] CMP -->|"rison.encode"| URL["URL param"] URL -->|"rison.decode"| CMP2["compact form"] CMP2 -->|"expandFilterNode + kinds"| NODE2["FilterNode<br/>(invalid leaves dropped)"] NODE2 -->|"validate, then adapter"| SRV["buildFilterNode"]
import { compactFilterNode, expandFilterNode } from "@xtandard/lib/filters";
const kinds = { title: "text", status: "enum", priority: "number" }; // from _metadata
// FE → URLconst { compact } = compactFilterNode({ node });const param = rison.encode(compact); // (or:!((f:title,o:ct,v:inves),(f:status,o:iA,vs:!(todo,in_progress)),(and:!((f:priority,o:eq,v:1)))))
// URL → FE (kind restored from `kinds`)const { node } = expandFilterNode({ compact: rison.decode(param), kinds });Versus the verbose form, the example above goes from ~330 → ~120 chars. The roughly equivalent verbose Rison was:
(nodes:!((field:title,filter:(kind:text,operator:contains,value:inves),type:column),(field:status,filter:(kind:enum,operator:inArray,values:!(todo,in_progress)),type:column),(nodes:!((field:priority,filter:(kind:number,operator:eq,value:1)),type:column)),type:and),type:or)-
Flat lists:
compactFilters({ filters })/expandFilters({ compact, kinds })for theColumnFilter[](implicit-AND) case — the compact form is just an array of leaves. -
Bind once:
createFilterUrlCodec({ kinds })returns{ encodeNode, decodeNode, encodeFilters, decodeFilters }— sugar for plugging into a URL-state codec (e.g.parseAsCodec(risonCodec(...))). -
The code tables are exported (
OPERATOR_CODE/operatorFromCode,UNIT_CODE/unitFromCode) if you need to read or extend them. -
Interactive filter-builders: by default
decodeNode/expandFilterNodePRUNE anand/orgroup that decodes to zero children (defensive — a stale or hand-edited URL collapses to a valid subset). When the URL is the source of truth for a tree being edited, that drops a just-added still-empty group (the “Add group” → empty box pattern) on the next round-trip. PasskeepEmptyGroups: true(onexpandFilterNodeorcreateFilterUrlCodec) to keep empty containers — invalid LEAVES (non-allow-listed field, unknown operator, bad value) are still dropped in both modes; only the empty-container collapse changes.const codec = createFilterUrlCodec({ kinds, keepEmptyGroups: true });codec.decodeNode({ and: [] }); // → { type: "and", nodes: [] } (kept, not null)
The codec is frontend-safe and zero-dependency (part of the core
@xtandard/lib/filters). The model is unchanged — adapters, validation, and everything server-side still consume the verbose objects; the compact form exists only betweenencodeanddecode.
Describing filters (chip labels)
Section titled “Describing filters (chip labels)”describeFieldFilter / describeColumnFilter render short, human labels for
active-filter chips (frontend-safe, no drizzle). The date preset’s label is
injected (describeDate) — without it, a preset falls back to its operator
label:
import { describeColumnFilter } from "@xtandard/lib/filters";
describeColumnFilter({ columnFilter: { field: "amount", filter: { kind: "number", operator: "between", from: 1, to: 9 }, }, label: "Amount",}); // "Amount between 1 – 9"
describeColumnFilter({ columnFilter: { field: "createdAt", filter: datePreset }, label: "Created", describeDate: (f) => formatPreset(f), // your DST-aware label}); // "Created Feb 2026"Resource metadata (backend-driven UIs)
Section titled “Resource metadata (backend-driven UIs)”ResourceMetadata / FieldMetadata are a serializable contract a backend can
expose (e.g. at …/_metadata) so a frontend renders a filter bar with no
hand-written field defs:
import type { ResourceMetadata } from "@xtandard/lib/filters";import { OPERATORS_BY_KIND } from "@xtandard/lib/filters";
const metadata: ResourceMetadata = { name: "tasks", fields: [ { field: "name", label: "Name", kind: "text", filterable: true, sortable: true, operators: [...OPERATORS_BY_KIND.text], }, { field: "status", label: "Status", kind: "enum", filterable: true, sortable: false, operators: [...OPERATORS_BY_KIND.enum], options: [{ value: "open", label: "Open" }], }, ], defaultSort: [{ field: "createdAt", dir: "desc" }], pagination: { styles: ["offset", "cursor"] }, crud: { read: true, create: true, update: true, delete: false },};