Filter AST with Remote Data
Use a Filter AST with remote data to describe the filter in the grid and apply it to the complete dataset on your server. The server returns the filtered page and total count. This works with RevoGrid Pro’s remote pagination, as well as other server-owned data sources.
Try it live
Section titled “Try it live”Open a column filter to build a Filter AST with the grouped editor. This demo enables openByDefault and predefinedFilters, so the editor opens directly with an empty condition for the selected column. Enter a value and apply the rule to send the tree to the simulated HTTP backend; the page and count update from the filtered results. The backend filters all 102 records before paging. The source tabs include the HTTP client and backend service. The simulated backend is demo infrastructure; use your own API in an application.
You can also edit a visible cell. Event Manager sends the edit to the same backend by user ID, and the grid reloads the active filter and page after the save. For example, filter Relationship to single, then change a visible value to relationship: the saved row leaves the filtered results and the count decreases. Valid relationship values are single, relationship, and complicated.
Source code
import { defineCustomElements } from '@revolist/revogrid/loader';import { AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, PaginationPlugin, ColumnStretchPlugin, RowOddPlugin,} from '@revolist/revogrid-pro';import { currentTheme } from '../composables/useRandomData';import { createRemotePaginationColumns } from './pagination.remote.utils';import { startRemotePagination } from './pagination.remote.bootstrap';
defineCustomElements();
export function load(parentSelector: string) { const parent = document.querySelector(parentSelector); if (!parent) throw new Error('Remote pagination container not found.'); const shell = document.createElement('section'); shell.className = 'pagination-remote-demo'; Object.assign(shell.style, { minHeight: '0', height: '360px', display: 'flex', flexDirection: 'column', flex: '1 1 auto', }); parent.appendChild(shell); const lifetime = new AbortController(); const status = document.createElement('p'); status.setAttribute('role', 'status'); status.textContent = 'Starting demo backend…'; shell.appendChild(status); let grid: HTMLRevoGridElement | undefined;
void startRemotePagination(lifetime.signal, () => grid) .then(({ pagination, eventManager }) => { if (lifetime.signal.aborted) return; grid = document.createElement('revo-grid'); grid.className = 'overflow-hidden cell-border'; grid.style.cssText = 'height: 100%; min-height: 0; flex: 1 1 0;'; grid.columns = createRemotePaginationColumns(); const filterConfig = { predefinedFilters: true, groupedFilter: { remote: true, openByDefault: true }, }; grid.filter = filterConfig; grid.addEventListener('externalediterror', () => { status.setAttribute('role', 'alert'); status.textContent = 'Could not save changes.'; shell.appendChild(status); }); grid.stretch = 'all'; grid.pagination = pagination; grid.eventManager = eventManager; grid.plugins = [ PaginationPlugin, AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, ColumnStretchPlugin, RowOddPlugin, ]; grid.theme = currentTheme().isDark() ? 'darkMaterial' : 'material'; grid.hideAttribution = true; shell.appendChild(grid); grid.source = []; status.remove(); }) .catch((error) => { if (lifetime.signal.aborted) return; status.setAttribute('role', 'alert'); status.textContent = error.message; });
return () => { lifetime.abort(); grid?.remove(); shell.remove(); };}<template> <section class="pagination-remote-demo" style=" min-height: 0; height: 360px; display: flex; flex-direction: column; flex: 1 1 auto; " > <p v-if="startupError" role="alert">{{ startupError }}</p> <VGrid v-else-if="pagination" class="overflow-hidden cell-border" style="height: 100%; min-height: 0; flex: 1 1 0" :theme="isDark ? 'darkMaterial' : 'material'" :columns="columns" :source="source" :pagination.prop="pagination" stretch="all" :filter="filterConfig" :event-manager.prop="eventManager" @aftergridinit="connectGrid" @externalediterror="editError = 'Could not save changes.'" :plugins="plugins" hide-attribution /> <p v-else role="status">Starting demo backend…</p> <p v-if="editError" role="alert">{{ editError }}</p> </section></template>
<script setup lang="ts">import { onMounted, onBeforeUnmount, ref, shallowRef } from 'vue';import { VGrid } from '@revolist/vue3-datagrid';import { AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, PaginationPlugin, ColumnStretchPlugin, RowOddPlugin,} from '@revolist/revogrid-pro';import type { PaginationFullConfig } from '@revolist/revogrid-pro';import { currentThemeVue } from '../composables/useRandomData';import { createRemotePaginationColumns, createRemoteUsersEventManager,} from './pagination.remote.utils';import { startRemotePagination } from './pagination.remote.bootstrap';import type { RemoteUser } from './backend/contracts';
const { isDark } = currentThemeVue();const source = ref<RemoteUser[]>([]);const columns = createRemotePaginationColumns();const plugins = [ PaginationPlugin, AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, ColumnStretchPlugin, RowOddPlugin,];const filterConfig = { predefinedFilters: true, groupedFilter: { remote: true, openByDefault: true },};let grid: HTMLRevoGridElement | undefined;const connectGrid = (event: Event) => { grid = event.target as HTMLRevoGridElement;};const eventManager = shallowRef<ReturnType<typeof createRemoteUsersEventManager>>();const editError = ref('');const pagination = shallowRef<PaginationFullConfig>();const startupError = ref('');const lifetime = new AbortController();onBeforeUnmount(() => lifetime.abort());onMounted(async () => { try { const config = await startRemotePagination(lifetime.signal, () => grid); eventManager.value = config.eventManager; pagination.value = config.pagination; } catch (error) { if (!lifetime.signal.aborted) startupError.value = (error as Error).message; }});</script>import React, { useEffect, useMemo, useRef, useState } from 'react';import { RevoGrid } from '@revolist/react-datagrid';import { AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, PaginationPlugin, ColumnStretchPlugin, RowOddPlugin,} from '@revolist/revogrid-pro';import type { PaginationFullConfig } from '@revolist/revogrid-pro';import { currentTheme } from '../composables/useRandomData';import { createRemotePaginationColumns, createRemoteUsersEventManager,} from './pagination.remote.utils';import { startRemotePagination } from './pagination.remote.bootstrap';import type { RemoteUser } from './backend/contracts';
export default function PaginationRemote(_props: { rows?: unknown[] }) { const source = useMemo<RemoteUser[]>(() => [], []); const columns = useMemo(createRemotePaginationColumns, []); const plugins = useMemo( () => [ PaginationPlugin, AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, ColumnStretchPlugin, RowOddPlugin, ], [], ); const grid = useRef<HTMLRevoGridElement | undefined>(undefined); const [eventManager, setEventManager] = useState<ReturnType<typeof createRemoteUsersEventManager>>(); const [editError, setEditError] = useState(''); const filterConfig = useMemo( () => ({ predefinedFilters: true, groupedFilter: { remote: true, openByDefault: true }, }), [], ); const [pagination, setPagination] = useState<PaginationFullConfig>(); const [startupError, setStartupError] = useState(''); useEffect(() => { const lifetime = new AbortController(); void startRemotePagination(lifetime.signal, () => grid.current) .then((config) => { if (!lifetime.signal.aborted) { setEventManager(config.eventManager); setPagination(config.pagination); } }) .catch((error) => { if (!lifetime.signal.aborted) setStartupError(error.message); }); return () => lifetime.abort(); }, []);
return ( <section className="pagination-remote-demo" style={{ minHeight: 0, height: 360, display: 'flex', flexDirection: 'column', flex: '1 1 auto', }} > {startupError ? ( <p role="alert">{startupError}</p> ) : !pagination ? ( <p role="status">Starting demo backend…</p> ) : ( <RevoGrid className="overflow-hidden cell-border" style={{ height: '100%', minHeight: 0, flex: '1 1 0' }} columns={columns} source={source} pagination={pagination} stretch="all" filter={filterConfig} eventManager={eventManager} onAftergridinit={(event) => { grid.current = event.target as HTMLRevoGridElement; grid.current.addEventListener('externalediterror', () => setEditError('Could not save changes.'), ); }} hide-attribution theme={currentTheme().isDark() ? 'darkMaterial' : 'material'} plugins={plugins} /> )} {editError && <p role="alert">{editError}</p>} </section> );}import { Component, ViewEncapsulation, NO_ERRORS_SCHEMA, signal,} from '@angular/core';import type { OnInit, OnDestroy } from '@angular/core';import { RevoGrid } from '@revolist/angular-datagrid';import { AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, PaginationPlugin, ColumnStretchPlugin, RowOddPlugin,} from '@revolist/revogrid-pro';import type { PaginationFullConfig } from '@revolist/revogrid-pro';import { currentTheme } from '../composables/useRandomData';import { createRemotePaginationColumns, createRemoteUsersEventManager,} from './pagination.remote.utils';import { startRemotePagination } from './pagination.remote.bootstrap';import type { RemoteUser } from './backend/contracts';
@Component({ selector: 'pagination-remote-grid', standalone: true, imports: [RevoGrid], template: ` <section class="pagination-remote-demo" style="height: 360px; min-height: 0; display: flex; flex-direction: column; flex: 1 1 auto" > @if (startupError()) { <p role="alert">{{ startupError() }}</p> } @else if (pagination(); as config) { <revo-grid class="overflow-hidden cell-border" [columns]="columns" [source]="source" [filter]="filterConfig" [eventManager]="eventManager()" (aftergridinit)="connectGrid($event)" (externalediterror)="editError.set('Could not save changes.')" stretch="all" [pagination]="config" hide-attribution [theme]="theme" [plugins]="plugins" style="height: 100%; min-height: 0; flex: 1 1 0;" ></revo-grid> } @else { <p role="status">Starting demo backend…</p> } @if (editError()) { <p role="alert">{{ editError() }}</p> } </section> `, encapsulation: ViewEncapsulation.None, schemas: [NO_ERRORS_SCHEMA],})export class PaginationRemoteGridComponent implements OnInit, OnDestroy { theme = currentTheme().isDark() ? 'darkMaterial' : 'material'; source: RemoteUser[] = []; columns = createRemotePaginationColumns(); plugins = [ PaginationPlugin, AdvanceFilterPlugin, EventManagerPlugin, HistoryPlugin, ColumnStretchPlugin, RowOddPlugin, ]; filterConfig = { predefinedFilters: true, groupedFilter: { remote: true, openByDefault: true }, }; private grid?: HTMLRevoGridElement; connectGrid(event: Event) { this.grid = event.target as HTMLRevoGridElement; } eventManager = signal< ReturnType<typeof createRemoteUsersEventManager> | undefined >(undefined); editError = signal(''); pagination = signal<PaginationFullConfig | undefined>(undefined); startupError = signal(''); private lifetime = new AbortController();
ngOnInit() { void startRemotePagination(this.lifetime.signal, () => this.grid) .then((config) => { if (!this.lifetime.signal.aborted) { this.eventManager.set(config.eventManager); this.pagination.set(config.pagination); } }) .catch((error) => { if (!this.lifetime.signal.aborted) this.startupError.set(error.message); }); } ngOnDestroy() { this.lifetime.abort(); }}import type { ColumnRegular } from '@revolist/revogrid';import { createExternalEditHistoryCommands, PaginationPlugin, serializeFilterCollection, serializeMultiFilterItems,} from '@revolist/revogrid-pro';import type { CommandReceipt, EventManagerConfig, PaginationLoadData,} from '@revolist/revogrid-pro';import { ensureDemoBackendActive } from '@revolist/revogrid-examples/demo-api-mocks';import type { RemoteUser, UsersPage, UserEditResult,} from './backend/contracts';
export function createRemotePaginationColumns(): ColumnRegular[] { return [ { name: 'First Name', prop: 'firstName', sortable: true }, { name: 'Last Name', prop: 'lastName', sortable: true }, { name: 'Relationship', prop: 'status', sortable: true }, ];}
/** Real HTTP client: no access to mock services or seed data. */export function createRemoteUsersLoader( apiUrl: string,): PaginationLoadData<RemoteUser> { return async ( skip, take, sort, filter, filterItems, _quickFilter, _temporal, filterAst, _execution, context, ): Promise<UsersPage> => { await ensureDemoBackendActive(context?.signal); const url = new URL( `${apiUrl}/users`, globalThis.location?.href ?? 'http://localhost', ); url.searchParams.set('skip', String(skip)); url.searchParams.set('take', String(take)); if (sort && Object.keys(sort).length) url.searchParams.set('sort', JSON.stringify(sort)); if (filterAst) url.searchParams.set('filterAst', JSON.stringify(filterAst)); else if (filterItems) url.searchParams.set( 'filterItems', JSON.stringify(serializeMultiFilterItems(filterItems) ?? {}), ); else if (filter) url.searchParams.set( 'filter', JSON.stringify(serializeFilterCollection(filter) ?? {}), ); const response = await fetch(url, { signal: context?.signal }); if (!response.ok) { const body = await response.json().catch(() => ({})); throw Object.assign( new Error( typeof body?.message === 'string' ? body.message : `HTTP ${response.status}`, ), { status: response.status }, ); } return response.json(); };}
export function createRemoteUsersEventManager( apiUrl: string, getGrid: () => HTMLRevoGridElement | undefined,): EventManagerConfig & { externalEdit: NonNullable<EventManagerConfig['externalEdit']>;} { const getPagination = async () => (await getGrid()?.getPlugins())?.find( (plugin) => plugin instanceof PaginationPlugin, ) as PaginationPlugin | undefined; const historyUrl = `${apiUrl}/users/history`; async function readReceipt( url: string, init: RequestInit, ): Promise<CommandReceipt<null, string | number, unknown>> { await ensureDemoBackendActive(init.signal ?? undefined); const response = await fetch(url, init); if (!response.ok) throw new Error(`History request failed (HTTP ${response.status}).`); return response.json(); } return { externalEdit: { sourceVersion: apiUrl, getRowKey: (row) => row.id as number, history: createExternalEditHistoryCommands({ resourceId: apiUrl, idempotent: true, submit: (envelope, { signal }) => readReceipt(historyUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(envelope), signal, }), recover: ({ operationId }, { signal }) => readReceipt(`${historyUrl}/${encodeURIComponent(operationId)}`, { signal, }), source: { async accepted() { const pagination = await getPagination(); if (pagination && !(await pagination.captureMutationRefresh()())) { throw new Error('The current page could not be refreshed.'); } }, }, }), async apply({ candidates, signal }): Promise<UserEditResult[]> { const refresh = (await getPagination())?.captureMutationRefresh(); await ensureDemoBackendActive(signal); const response = await fetch(`${apiUrl}/users/edits`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal, body: JSON.stringify({ candidates: candidates.map( ({ id, rowKey, prop, previousValue, proposedValue }) => ({ id, rowKey, prop, previousValue, proposedValue, }), ), }), }); if (!response.ok) throw new Error(`Could not save changes (HTTP ${response.status}).`); const results = (await response.json()) as UserEditResult[]; if (results.some((result) => result.status === 'changed')) { // The server has committed. A failed read cannot change the edit outcome. await refresh?.().catch(() => {}); } return results; }, }, };}import { startDemoBackend } from '@revolist/revogrid-examples/demo-api-mocks';import type { PaginationFullConfig } from '@revolist/revogrid-pro';import { createRemoteUsersLoader, createRemoteUsersEventManager,} from './pagination.remote.utils';
/** Host-only setup. An aborted mount also disposes a session that starts late. */export async function startRemotePagination( signal: AbortSignal, getGrid: () => HTMLRevoGridElement | undefined = () => undefined,): Promise<{ pagination: PaginationFullConfig; eventManager: ReturnType<typeof createRemoteUsersEventManager>;}> { signal.throwIfAborted(); const { remotePaginationBackend } = await import('./backend/module'); signal.throwIfAborted(); const session = await startDemoBackend(remotePaginationBackend); if (signal.aborted) { session.dispose(); signal.throwIfAborted(); } signal.addEventListener('abort', () => session.dispose(), { once: true }); return { eventManager: createRemoteUsersEventManager(session.apiUrl, getGrid), pagination: { itemsPerPage: 10, initialPage: 0, total: 0, buttonCount: 5, query: { staleTime: 30_000 }, loadData: createRemoteUsersLoader(session.apiUrl), }, };}import { http, HttpResponse } from 'msw';import type { CommandEnvelope, CommandReceipt, ExternalEditHistoryCommand,} from '@revolist/revogrid-pro';import type { DemoBackendModule } from '@revolist/revogrid-examples/demo-api-mocks';import { createUsersSeed } from './seed';import { queryUsers, updateUsers, UsersQueryError } from './service';
export const remotePaginationBackend: DemoBackendModule = { id: 'pagination', create({ apiUrl }) { const users = createUsersSeed(); let revision = 0; // Scoped to this mocked server session. A real server persists the receipt and write together. const receipts = new Map< string, { payload: string; receipt: CommandReceipt<null, number> } >(); return { handlers: [ http.post(`${apiUrl}/users/history`, async ({ request }) => { const envelope = (await request.json()) as CommandEnvelope< ExternalEditHistoryCommand, number >; const { operationId, resourceId, command, expectedRevision } = envelope; if ( typeof operationId !== 'string' || resourceId !== apiUrl || !['undo', 'redo'].includes(command?.direction) || !Array.isArray(command?.changes) || !command.changes.length || command.changes.some((change) => change?.type !== 'rgRow') ) { return HttpResponse.json( { message: 'Invalid history command.' }, { status: 400 }, ); } const payload = JSON.stringify(envelope); const previous = receipts.get(operationId); if (previous) { return previous.payload === payload ? HttpResponse.json(previous.receipt) : HttpResponse.json( { message: 'Operation ID is already in use.' }, { status: 409 }, ); } const staged = users.map((row) => ({ ...row })); let receipt: CommandReceipt<null, number>; if (expectedRevision !== undefined && expectedRevision !== revision) { receipt = { operationId, status: 'conflict', message: 'The dataset revision has changed.', authoritative: null, revision, }; } else { try { const outcomes = updateUsers( staged, command.changes.map((change, id) => ({ ...change, id })), ); if (outcomes.every((result) => result.status === 'changed')) { users.splice(0, users.length, ...staged); receipt = { operationId, status: 'accepted', changes: null, revision: ++revision, }; } else { receipt = { operationId, status: 'rejected', message: 'A row has changed or a value is invalid.', }; } } catch (error) { if (!(error instanceof UsersQueryError)) throw error; receipt = { operationId, status: 'rejected', message: error.message, }; } } receipts.set(operationId, { payload, receipt }); return HttpResponse.json(receipt); }), http.get(`${apiUrl}/users/history/:operationId`, ({ params }) => { const operationId = String(params.operationId); return HttpResponse.json( receipts.get(operationId)?.receipt ?? { operationId, status: 'unknown', }, ); }), http.post(`${apiUrl}/users/edits`, async ({ request }) => { try { const body = (await request.json()) as { candidates?: unknown }; const results = updateUsers(users, body?.candidates); if (results.some((result) => result.status === 'changed')) revision++; return HttpResponse.json(results); } catch (error) { if ( error instanceof UsersQueryError || error instanceof SyntaxError ) return HttpResponse.json( { message: error.message }, { status: 400 }, ); throw error; } }), http.get(`${apiUrl}/users`, ({ request }) => { try { return HttpResponse.json( queryUsers(users, new URL(request.url).searchParams), ); } catch (error) { if (error instanceof UsersQueryError) return HttpResponse.json( { message: error.message }, { status: 400 }, ); throw error; } }), ], }; },};import { filterCoreFunctionsIndexedByType } from '@revolist/revogrid';import type { MultiFilterItem, SortingOrder } from '@revolist/revogrid';import { collectFilterAstFields, compileFilterAst, multiFilterItemsToFilterAst, validateFilterAst,} from '@revolist/revogrid-pro';import type { FilterAst } from '@revolist/revogrid-pro';import { REMOTE_USER_FIELDS } from './contracts';import type { RemoteUser, UsersPage } from './contracts';
const fields = new Set<string>(REMOTE_USER_FIELDS);export class UsersQueryError extends Error {}function record(value: unknown): value is Record<string, unknown> { return !!value && typeof value === 'object' && !Array.isArray(value);}function json(search: URLSearchParams, name: string): unknown { const raw = search.get(name); if (raw === null) return undefined; try { return JSON.parse(raw); } catch { throw new UsersQueryError(`Invalid ${name} JSON.`); }}function offset( search: URLSearchParams, name: string, fallback: number,): number { const raw = search.get(name); if (raw === null) return fallback; const value = Number(raw); if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < 0) { throw new UsersQueryError(`${name} must be a nonnegative integer.`); } return value;}function parseSort(search: URLSearchParams): SortingOrder { const sort = json(search, 'sort'); if (sort === undefined) return {}; if ( !record(sort) || Object.entries(sort).some( ([field, order]) => !fields.has(field) || (order !== 'asc' && order !== 'desc'), ) ) { throw new UsersQueryError('Invalid sorting fields or direction.'); } return sort as SortingOrder;}function parseFilter(search: URLSearchParams): FilterAst | undefined { let ast = json(search, 'filterAst'); if (ast === undefined) { let items = json(search, 'filterItems'); if (items === undefined) { const collection = json(search, 'filter'); if (collection !== undefined) { if ( !record(collection) || Object.values(collection).some((item) => !record(item)) ) { throw new UsersQueryError('Invalid filter collection.'); } items = Object.fromEntries( Object.entries(collection).map(([field, item]) => [ field, [{ ...(item as object), id: 0 }], ]), ); } } if (items === undefined) return undefined; if ( !record(items) || Object.entries(items).some( ([field, conditions]) => !fields.has(field) || !Array.isArray(conditions) || conditions.some( (item) => !record(item) || typeof item.type !== 'string' || (item.relation !== undefined && item.relation !== 'and' && item.relation !== 'or'), ), ) ) { throw new UsersQueryError('Invalid filter items.'); } ast = multiFilterItemsToFilterAst(items as MultiFilterItem); if (!ast) return undefined; } if (!validateFilterAst(ast).valid) throw new UsersQueryError('Invalid or unsupported filter expression.'); if ( [...collectFilterAstFields(ast as FilterAst)].some( (field) => !fields.has(field), ) ) { throw new UsersQueryError('Unknown filter field.'); } return ast as FilterAst;}/** Backend query independent of HTTP/MSW and client Query caching. */export function queryUsers( rows: readonly RemoteUser[], search: URLSearchParams,): UsersPage { const skip = offset(search, 'skip', 0); const take = offset(search, 'take', 10); if (take > 1000) throw new UsersQueryError('take must not exceed 1000.'); const sort = parseSort(search); const ast = parseFilter(search); // Reuse supported evaluators, including multi-condition and selection semantics. const predicate = ast && compileFilterAst(ast, { columns: REMOTE_USER_FIELDS.map((prop) => ({ prop })), operators: filterCoreFunctionsIndexedByType, }); const filtered = rows.filter((row) => !predicate || predicate.matches(row)); const clauses = Object.entries(sort); const ordered = filtered.sort((a, b) => { for (const [field, direction] of clauses) { const left = a[field as keyof RemoteUser]; const right = b[field as keyof RemoteUser]; const comparison = typeof left === 'number' && typeof right === 'number' ? left - right : String(left) .toLowerCase() .localeCompare(String(right).toLowerCase()); if (comparison) return direction === 'desc' ? -comparison : comparison; } return a.id - b.id; }); return { data: ordered.slice(skip, skip + take), count: ordered.length };}
/** Apply edits by stable row id, rejecting stale or invalid values. */export function updateUsers( rows: RemoteUser[], input: unknown,): import('./contracts').UserEditResult[] { if ( !Array.isArray(input) || input.some( (c) => !record(c) || !Number.isSafeInteger(c.id) || !Number.isSafeInteger(c.rowKey) || typeof c.prop !== 'string', ) ) throw new UsersQueryError('Invalid edit candidates.'); return input.map((c) => { const row = rows.find((r) => r.id === c.rowKey); const prop = c.prop as 'firstName' | 'lastName' | 'status'; const reject = (message: string) => ({ id: c.id as number, status: 'rejected' as const, message, }); if (!row || !['firstName', 'lastName', 'status'].includes(prop)) return reject('Unknown row or field.'); if (row[prop] !== c.previousValue) return reject('The value has changed.'); if ( typeof c.proposedValue !== 'string' || !c.proposedValue.trim() || (prop === 'status' && !['single', 'relationship', 'complicated'].includes(c.proposedValue)) ) return reject('Invalid value.'); if (row[prop] === c.proposedValue) return { id: c.id as number, status: 'unchanged' as const }; if (prop === 'status') row.status = c.proposedValue as RemoteUser['status']; else row[prop] = c.proposedValue; return { id: c.id as number, status: 'changed' as const, value: c.proposedValue, }; });}import { makeData } from '../../composables/makeData';import type { RemoteUser } from './contracts';
/** The existing generator is deterministic by row ID; each call owns fresh records. */export function createUsersSeed(): RemoteUser[] { return makeData(102).map(({ id, firstName, lastName, status }) => ({ id: Number(id), firstName, lastName, status, }));}export interface RemoteUser { id: number; firstName: string; lastName: string; status: 'relationship' | 'complicated' | 'single';}export interface UsersPage { data: RemoteUser[]; count: number;}export const REMOTE_USER_FIELDS = [ 'id', 'firstName', 'lastName', 'status',] as const;
export type UserEditResult = | { id: number; status: 'changed'; value: string } | { id: number; status: 'unchanged' } | { id: number; status: 'rejected'; message: string };Send the AST with remote pagination
Section titled “Send the AST with remote pagination”Register AdvanceFilterPlugin and PaginationPlugin. The pagination plugin intercepts filter changes, resets to the first page, and passes the AST and execution context to loadData. Send those values along with the page request:
import { AdvanceFilterPlugin, PaginationPlugin } from '@revolist/revogrid-pro';
grid.plugins = [PaginationPlugin, AdvanceFilterPlugin];grid.filter = { predefinedFilters: true, groupedFilter: { remote: true, openByDefault: true },};grid.pagination = { itemsPerPage: 10, initialPage: 0, total: 0, query: { staleTime: 30_000 }, loadData: async ( skip, take, order, _filter, _filterItems, _quickFilter, _temporalContext, filterAst, executionContext, context, ) => { const response = await fetch('/api/users/search', { method: 'POST', headers: { 'content-type': 'application/json' }, signal: context?.signal, body: JSON.stringify({ skip, take, order, filterAst, executionContext }), }); if (!response.ok) throw new Error(`Request failed: ${response.status}`); return response.json(); // { data: User[], count: number } },};Pagination uses the built-in Query engine for remote reads. It caches filtered pages and retries transient read failures. For more options, see Loading and Caching Server Data.
When the filter is cleared, filterAst can be absent. The server should treat that as an unfiltered request. Apply the filter and sort before slicing the requested page, and return the count after filtering but before paging. Send the execution context so relative dates and blank-value policies can be evaluated consistently. If your application also enables quick search or separate temporal filter state, forward and implement those inputs as needed.
Validate the tree and allow-list fields and operators on the server. Translate it to your backend’s query language using parameterized queries; RevoGrid does not automatically generate SQL, REST, or GraphQL. The live example uses validateFilterAst, collectFilterAstFields, and compileFilterAst against an in-memory dataset.
For a custom remote datasource without PaginationPlugin, configure the advanced filter with external: true or cancel beforefilterapply, send its AST and execution context to your service, and replace the grid rows with the result. See events and remote ownership for the event details and remote pagination for the complete loader contract.
Save edits through the server
Section titled “Save edits through the server”The live example registers EventManagerPlugin and configures eventManager.externalEdit. Its getRowKey uses the stable user ID, and apply sends candidate IDs, row keys, fields, old values and proposed values to the backend. The backend returns one changed, unchanged or rejected result for each candidate. After a successful write, the client runs the refresh returned by PaginationPlugin.captureMutationRefresh(). This invalidates the cached pages and reloads the current filter, sort and page. See the HTTP client and Backend service source tabs for the complete implementation and the external-editing guide for the Event Manager contract.
With the grid focused, use its Undo or Redo shortcut to replay an edit after changing pages or filters. The demo sends a separate history command by stable row ID, then refreshes the current page after the mock backend commits. See replay outside the loaded view for the production receipt contract.