Framework
A support lead might need every open ticket while a colleague wants only their own queue. A table perspective remembers each arrangement of columns, filters and sort order so both people can return to the view they use.
Table perspectives let operators bookmark how a DataTable is presented: column order, hidden fields, filters, sorting and search input are all persisted per table. The feature is discoverable anywhere the backend renders DataTable with a perspective prop.
perspectives.use – required to open the Perspectives drawer, switch between saved views and store personal defaults.perspectives.role_defaults – additionally required to publish a perspective for selected roles or mark one as a role default.Both permissions are seeded by mercato auth setup. If you introduce new roles manually, remember to add the features to their ACLs.
<DataTable
columns={columns}
data={rows}
perspective={{ tableId: 'customers.people.list' }}
/* ... */
/>
The tableId can be any unique string; it scopes the stored data and maps to the /api/perspectives/{tableId} endpoints from the perspectives module.
A saved view is dense: on every save it records an explicit true/false for every leaf
column the table currently renders, not just the ones the user touched. A column a view
never names – because it registered after the view was saved, such as a custom field or a
widget-injected column – falls back to that column's own meta.hidden default instead of
defaulting to visible.
When a user lands on the table for the first time, the client component normally downloads perspectives and applies the selected view afterwards. To hydrate the table with the right layout from the start, fetch the initial state on the server and pass it down:
import { fetchInitialPerspectiveState } from '@open-mercato/core/modules/perspectives/utils/initialState'
import CustomersPageClient from './PageClient'
export default async function CustomersPage() {
const perspective = await fetchInitialPerspectiveState('customers.people.list')
return <CustomersPageClient initialPerspective={perspective ?? undefined} />
}
Then forward initialPerspective to DataTable:
<DataTable
columns={columns}
data={rows}
perspective={{
tableId: 'customers.people.list',
initialState: perspective,
}}
/>
fetchInitialPerspectiveState() reads the user’s cookie and calls the perspectives API using the incoming request credentials. It returns the saved response payload, the id that should be activated, and a sanitized copy of the perspective settings. The client uses that information to render the table with the correct columns immediately while still revalidating the data once hydrated.
On the initial load, DataTable shows its loading state until isLoading clears and injected columns finish loading. If the host builds columns from asynchronous custom-field definitions, include that query's loading state in isLoading alongside the row request. Hidden defaults and injected-column placement are applied before the header appears; later data refreshes retain the header.
Keep definition-query identity tied to the organization scope, rather than a row-reload counter. Refetch the existing definitions so established columns remain available while the request runs. A real tenant or organization change must use a separate query identity and must not reuse the previous scope's definitions.
The DataTable component keeps a lightweight snapshot in localStorage so subsequent navigations reapply the last view even before React Query has revalidated against the API. The snapshot is invalidated automatically when a perspective is deleted or a role default is cleared.
Reach for showSaveViewButton first: it is the recommended way to give a table a save affordance, and a hand-built control is reserved for hosts that already pass a custom toolbar. The built-in button keeps the placement, styling and copy identical on every screen, which is exactly the drift a per-module button reintroduces.
<DataTable
perspective={{ tableId: 'sales:orders' }}
showSaveViewButton
…
/>
The perspectives sidebar stays the default save path, and the button is off by default, so no existing screen changes until a host opts in. Three additive props expose the state and the action:
| Prop | Purpose |
|---|---|
showSaveViewButton | Renders the built-in “Save view” button next to the views switcher. Off by default; the recommended path. |
viewApiRef | Imperative handle: getCurrentSettings(), getDirtyState(), saveCurrentView(input?), openViewsSidebar(). For hosts that render their own control. |
onColumnsDirtyChange | Read-only callback fired whenever the unsaved-changes state changes. Only fires for tables that wire perspective. |
A custom toolbar prop replaces the built-in toolbar entirely, so showSaveViewButton has no effect there. Such a host renders the same affordance from viewApiRef and onColumnsDirtyChange – still without patching DataTable:
const viewApi = React.useRef<DataTableViewApi | null>(null)
const [dirty, setDirty] = React.useState<DataTableViewDirtyState | null>(null)
<Button
type="button"
variant="outline"
disabled={!dirty?.isDirty}
onClick={async () => {
const result = await viewApi.current?.saveCurrentView()
// No personal view is active yet — let the user name it in the sidebar.
if (result && !result.ok && result.reason === 'name-required') viewApi.current?.openViewsSidebar()
}}
>
Save view{dirty?.changedCount ? ` (${dirty.changedCount})` : ''}
</Button>
<DataTable
perspective={{ tableId: 'sales:orders' }}
viewApiRef={viewApi}
onColumnsDirtyChange={setDirty}
…
/>
DataTableViewDirtyState reports isDirty, the changedKeys (columnOrder, columnVisibility, columnSizing, sorting, filters, searchValue), changedCount, activePerspectiveId, and canSaveToActiveView – the last one is false for role perspectives and for “No view”, where a save needs an explicit name.
“Dirty” is measured against the settings the view was last applied or saved from, so restoring a view on page load never flags changes the user did not make. pageSize is not compared: the live settings never carry one.
saveCurrentView() returns a result instead of throwing: { ok: true, perspectiveId }, or { ok: false, reason: 'perspectives-disabled' | 'not-ready' | 'name-required' | 'failed' }. not-ready means the perspectives permission check has not resolved yet – nothing was saved and nothing is wrong, so retry rather than telling the user views are disabled. Edit conflicts (HTTP 409 optimistic_lock_conflict or record_lock_conflict) are surfaced by the shared conflict bar exactly as in the sidebar flow. Creating a view (no target view) never overwrites: a name another personal view already uses resolves { ok: false, reason: 'failed' } with the 409 duplicate_name in error, so pass that view's perspectiveId to save over it.
openViewsSidebar() is a no-op for a user without the perspectives.use feature (the sidebar closes again on the next render), so gate a host-rendered “Manage views” action on the same permission instead of expecting an error. The dirty state and the imperative handle are only computed for tables that pass at least one of these three props – a table that opts out pays nothing.
/api/perspectives/{tableId}
: GET fetches personal and role perspectives for the current user. POST creates or updates the personal entry and optionally pushes a copy to roles. Without perspectiveId it updates the personal view of the same name, if any; send createOnly: true to get a 409 duplicate_name instead.
/api/perspectives/{tableId}/{perspectiveId}
: DELETE soft-deletes the personal perspective.
/api/perspectives/{tableId}/roles/{roleId}
: DELETE removes a role default. Requires perspectives.role_defaults.
All endpoints live in the perspectives module and are included automatically by yarn generate.
yarn generate and restart the dev server so the new module routes are generated.sanitizePerspectiveSettings helper before invoking the API directly.