@kivacore/ui-pro-shared 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/package.json +167 -1
  2. package/src/.kiva/config.json +27 -0
  3. package/src/components/avatar-group.tsx +222 -0
  4. package/src/components/kiva/bulk-update-dialog/bulk-update-dialog.tsx +240 -0
  5. package/src/components/kiva/bulk-update-dialog/index.tsx +6 -0
  6. package/src/components/kiva/bulk-update-dialog/types.ts +33 -0
  7. package/src/components/kiva/calendar/animations.ts +40 -0
  8. package/src/components/kiva/calendar/calendar-body.tsx +106 -0
  9. package/src/components/kiva/calendar/calendar-sidebar.tsx +103 -0
  10. package/src/components/kiva/calendar/calendar.tsx +243 -0
  11. package/src/components/kiva/calendar/constants.ts +12 -0
  12. package/src/components/kiva/calendar/contexts/calendar-context.tsx +696 -0
  13. package/src/components/kiva/calendar/contexts/dnd-context.tsx +173 -0
  14. package/src/components/kiva/calendar/dialogs/add-edit-event-dialog.tsx +287 -0
  15. package/src/components/kiva/calendar/dialogs/delete-event-dialog.tsx +73 -0
  16. package/src/components/kiva/calendar/dialogs/event-details-dialog.tsx +163 -0
  17. package/src/components/kiva/calendar/dialogs/events-list-dialog.tsx +122 -0
  18. package/src/components/kiva/calendar/dnd/draggable-event.tsx +66 -0
  19. package/src/components/kiva/calendar/dnd/droppable-area.tsx +53 -0
  20. package/src/components/kiva/calendar/dnd/resizable-event.tsx +190 -0
  21. package/src/components/kiva/calendar/header/calendar-header.tsx +84 -0
  22. package/src/components/kiva/calendar/header/date-navigator.tsx +188 -0
  23. package/src/components/kiva/calendar/header/filter.tsx +80 -0
  24. package/src/components/kiva/calendar/header/today-button.tsx +49 -0
  25. package/src/components/kiva/calendar/header/user-select.tsx +111 -0
  26. package/src/components/kiva/calendar/header/view-tabs.tsx +144 -0
  27. package/src/components/kiva/calendar/helpers.ts +617 -0
  28. package/src/components/kiva/calendar/hooks/use-disclosure.ts +19 -0
  29. package/src/components/kiva/calendar/hooks/use-local-storage.ts +40 -0
  30. package/src/components/kiva/calendar/hooks/use-media-query.ts +25 -0
  31. package/src/components/kiva/calendar/hooks.ts +5 -0
  32. package/src/components/kiva/calendar/index.tsx +27 -0
  33. package/src/components/kiva/calendar/interfaces.ts +35 -0
  34. package/src/components/kiva/calendar/schemas.ts +20 -0
  35. package/src/components/kiva/calendar/settings/settings.tsx +116 -0
  36. package/src/components/kiva/calendar/skeletons/calendar-header-skeleton.tsx +27 -0
  37. package/src/components/kiva/calendar/skeletons/calendar-skeleton.tsx +19 -0
  38. package/src/components/kiva/calendar/skeletons/day-view-skeleton.tsx +40 -0
  39. package/src/components/kiva/calendar/skeletons/month-view-skeleton.tsx +36 -0
  40. package/src/components/kiva/calendar/skeletons/week-view-skeleton.tsx +48 -0
  41. package/src/components/kiva/calendar/skeletons/year-view-skeleton.tsx +42 -0
  42. package/src/components/kiva/calendar/types.ts +25 -0
  43. package/src/components/kiva/calendar/views/agenda-view/agenda-events.tsx +150 -0
  44. package/src/components/kiva/calendar/views/month-view/calendar-month-view.tsx +82 -0
  45. package/src/components/kiva/calendar/views/month-view/day-cell.tsx +218 -0
  46. package/src/components/kiva/calendar/views/month-view/event-bullet.tsx +46 -0
  47. package/src/components/kiva/calendar/views/month-view/month-event-badge.tsx +154 -0
  48. package/src/components/kiva/calendar/views/timeline/calendar-timeline-view.tsx +100 -0
  49. package/src/components/kiva/calendar/views/timeline/lib/timeline-layout.ts +130 -0
  50. package/src/components/kiva/calendar/views/timeline/lib/timeline-model.ts +504 -0
  51. package/src/components/kiva/calendar/views/timeline/timeline-event-bar.tsx +68 -0
  52. package/src/components/kiva/calendar/views/timeline/timeline-grid-header.tsx +125 -0
  53. package/src/components/kiva/calendar/views/timeline/timeline-row.tsx +159 -0
  54. package/src/components/kiva/calendar/views/timeline/timeline-section.tsx +61 -0
  55. package/src/components/kiva/calendar/views/timeline/use-timeline-sections.ts +278 -0
  56. package/src/components/kiva/calendar/views/week-and-day-view/calendar-day-view.tsx +277 -0
  57. package/src/components/kiva/calendar/views/week-and-day-view/calendar-time-line.tsx +47 -0
  58. package/src/components/kiva/calendar/views/week-and-day-view/calendar-week-view.tsx +229 -0
  59. package/src/components/kiva/calendar/views/week-and-day-view/day-view-multi-day-events-row.tsx +79 -0
  60. package/src/components/kiva/calendar/views/week-and-day-view/event-block.tsx +116 -0
  61. package/src/components/kiva/calendar/views/week-and-day-view/render-grouped-events.tsx +54 -0
  62. package/src/components/kiva/calendar/views/week-and-day-view/week-view-multi-day-events-row.tsx +159 -0
  63. package/src/components/kiva/calendar/views/year-view/calendar-year-view.tsx +159 -0
  64. package/src/components/kiva/data-table-side-filters/components/side-filter-active-chips.tsx +137 -0
  65. package/src/components/kiva/data-table-side-filters/components/side-filter-clear.tsx +34 -0
  66. package/src/components/kiva/data-table-side-filters/components/side-filter-search.tsx +67 -0
  67. package/src/components/kiva/data-table-side-filters/components/side-filter-section.tsx +77 -0
  68. package/src/components/kiva/data-table-side-filters/controllers/side-filter-async-options.tsx +354 -0
  69. package/src/components/kiva/data-table-side-filters/controllers/side-filter-boolean.tsx +66 -0
  70. package/src/components/kiva/data-table-side-filters/controllers/side-filter-checkbox-list.tsx +137 -0
  71. package/src/components/kiva/data-table-side-filters/controllers/side-filter-date-range.tsx +204 -0
  72. package/src/components/kiva/data-table-side-filters/controllers/side-filter-numeric-range.tsx +162 -0
  73. package/src/components/kiva/data-table-side-filters/controllers/side-filter-options-dropdown.tsx +191 -0
  74. package/src/components/kiva/data-table-side-filters/controllers/side-filter-text.tsx +53 -0
  75. package/src/components/kiva/data-table-side-filters/core/query-translator.ts +367 -0
  76. package/src/components/kiva/data-table-side-filters/core/types.ts +81 -0
  77. package/src/components/kiva/data-table-side-filters/data-table-side-filters.tsx +483 -0
  78. package/src/components/kiva/data-table-side-filters/hooks/use-data-table-side-filters.tsx +160 -0
  79. package/src/components/kiva/data-table-side-filters/hooks/use-show-more.tsx +62 -0
  80. package/src/components/kiva/data-table-side-filters/index.tsx +44 -0
  81. package/src/components/kiva/data-table-side-filters/lib/render-mode.ts +62 -0
  82. package/src/components/kiva/date-time-picker.tsx +163 -0
  83. package/src/components/kiva/editable-record-detail.tsx +809 -0
  84. package/src/components/kiva/enum-option-editor/enum-option-editor.tsx +891 -0
  85. package/src/components/kiva/enum-option-editor/index.tsx +26 -0
  86. package/src/components/kiva/enum-option-editor/kiva-enum-option-editor.tsx +320 -0
  87. package/src/components/kiva/enum-option-editor/types.ts +90 -0
  88. package/src/components/kiva/kanban.tsx +1376 -0
  89. package/src/components/kiva/kiva-data-export-menu.tsx +543 -0
  90. package/src/components/kiva/map.tsx +1631 -0
  91. package/src/components/kiva/pivot-calendar/components/group-sidebar.tsx +95 -0
  92. package/src/components/kiva/pivot-calendar/components/pivot-calendar-toolbar.tsx +113 -0
  93. package/src/components/kiva/pivot-calendar/components/stats-cell.tsx +126 -0
  94. package/src/components/kiva/pivot-calendar/helpers.ts +374 -0
  95. package/src/components/kiva/pivot-calendar/hooks/use-pivot-calendar.ts +222 -0
  96. package/src/components/kiva/pivot-calendar/index.tsx +32 -0
  97. package/src/components/kiva/pivot-calendar/pivot-calendar.tsx +107 -0
  98. package/src/components/kiva/pivot-calendar/types.ts +154 -0
  99. package/src/components/kiva/pivot-calendar/views/days-of-month-view.tsx +37 -0
  100. package/src/components/kiva/pivot-calendar/views/days-of-week-view.tsx +37 -0
  101. package/src/components/kiva/pivot-calendar/views/month-calendar-view.tsx +154 -0
  102. package/src/components/kiva/pivot-calendar/views/months-of-year-view.tsx +40 -0
  103. package/src/components/kiva/pivot-calendar/views/pivot-grid-view.tsx +251 -0
  104. package/src/components/kiva/pivot-filter/index.tsx +9 -0
  105. package/src/components/kiva/pivot-filter/pivot-filter-item.tsx +159 -0
  106. package/src/components/kiva/pivot-filter/pivot-filter-settings.tsx +161 -0
  107. package/src/components/kiva/pivot-filter/pivot-filter.tsx +187 -0
  108. package/src/components/kiva/pivot-filter/types.ts +82 -0
  109. package/src/components/kiva/pivot-grid/hooks/use-pivot-grid.ts +683 -0
  110. package/src/components/kiva/pivot-grid/index.tsx +23 -0
  111. package/src/components/kiva/pivot-grid/lib/pivot-grid-color-rules.ts +98 -0
  112. package/src/components/kiva/pivot-grid/lib/pivot-grid-export.ts +265 -0
  113. package/src/components/kiva/pivot-grid/lib/pivot-grid-model.ts +1110 -0
  114. package/src/components/kiva/pivot-grid/pivot-grid-demo-data.ts +200 -0
  115. package/src/components/kiva/pivot-grid/pivot-grid-export-menu.tsx +66 -0
  116. package/src/components/kiva/pivot-grid/pivot-grid-toolbar.tsx +85 -0
  117. package/src/components/kiva/pivot-grid/pivot-grid.tsx +601 -0
  118. package/src/components/kiva/pivot-grid/types.ts +195 -0
  119. package/src/components/kiva/place-autocomplete.tsx +484 -0
  120. package/src/components/kiva/record-delete-confirm-dialog/index.tsx +10 -0
  121. package/src/components/kiva/record-delete-confirm-dialog/record-delete-confirm-dialog.tsx +266 -0
  122. package/src/components/kiva/record-delete-confirm-dialog/types.ts +25 -0
  123. package/src/hooks/kiva/_internal/autonumber-setting.ts +112 -0
  124. package/src/hooks/kiva/_internal/form-layout-to-view.ts +665 -0
  125. package/src/hooks/kiva/_internal/kiva-hook-utils.ts +143 -0
  126. package/src/hooks/kiva/_internal/use-computed-field-evaluator.tsx +310 -0
  127. package/src/hooks/kiva/_internal/use-field-actions-evaluator.tsx +398 -0
  128. package/src/hooks/kiva/_internal/use-form-actions-evaluator.tsx +363 -0
  129. package/src/hooks/kiva/_internal/use-form-view-engine.tsx +2200 -0
  130. package/src/hooks/kiva/_internal/use-kiva-form-view-fields.tsx +190 -0
  131. package/src/hooks/kiva/_internal/use-kiva-kanban-cards.tsx +311 -0
  132. package/src/hooks/kiva/use-data-export.tsx +265 -0
  133. package/src/hooks/kiva/use-kiva-calendar.tsx +992 -0
  134. package/src/hooks/kiva/use-kiva-data-export.tsx +173 -0
  135. package/src/hooks/kiva/use-kiva-data-grid.tsx +4750 -0
  136. package/src/hooks/kiva/use-kiva-data-view-select.tsx +1273 -0
  137. package/src/hooks/kiva/use-kiva-form-view.tsx +1581 -0
  138. package/src/hooks/kiva/use-kiva-inventory.tsx +184 -0
  139. package/src/hooks/kiva/use-kiva-kanban.tsx +1750 -0
  140. package/src/hooks/kiva/use-kiva-map-view.tsx +2255 -0
  141. package/src/hooks/kiva/use-kiva-pivot-calendar.tsx +759 -0
  142. package/src/hooks/kiva/use-kiva-pivot-filter.tsx +1523 -0
  143. package/src/hooks/kiva/use-kiva-pivot-grid.tsx +543 -0
  144. package/src/hooks/kiva/use-kiva-tenant.tsx +313 -0
  145. package/src/hooks/kiva/use-parameter-persistence.ts +191 -0
@@ -0,0 +1,4750 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import {
6
+ useCallback,
7
+ useEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ type ReactNode
12
+ } from 'react';
13
+
14
+ import { type RestApiClient } from '@kivacore/api-client';
15
+ import { type DataForm, type DataSource, type DataSourceField } from '@kivacore/app-utils';
16
+ import {
17
+ keepPreviousData, useMutation, useQuery, useQueryClient
18
+ } from '@tanstack/react-query';
19
+ import {
20
+ type ColumnFiltersState,
21
+ type ColumnOrderState,
22
+ type ColumnPinningState,
23
+ type ColumnSizingState,
24
+ type ColumnSort,
25
+ type ExpandedState,
26
+ type GroupingState,
27
+ type PaginationState,
28
+ type SortingState,
29
+ type VisibilityState
30
+ } from '@tanstack/react-table';
31
+ import {
32
+ Download,
33
+ Loader2,
34
+ Mail,
35
+ MessageSquare,
36
+ Pencil,
37
+ RotateCw,
38
+ Search,
39
+ Trash2
40
+ } from 'lucide-react';
41
+ import { type RuleGroupType } from 'react-querybuilder';
42
+
43
+ import {
44
+ DataGridDisplayMenu,
45
+ DataGridExportMenu,
46
+ DataGridFieldsMenu,
47
+ DataGridFilterMenu,
48
+ DataGridGroupMenu,
49
+ DataGridRowHeightMenu,
50
+ DataGridSidePanel,
51
+ DataGridSortMenu,
52
+ type ColumnDef,
53
+ type DataGridAction,
54
+ type DataGridDisplayMode,
55
+ type RowChange,
56
+ type RowHeightValue,
57
+ type SavedDataGridView, applyViewToTable, getDataGridSelectColumn, useDataGrid
58
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid';
59
+ import {
60
+ DataGalleryCardConfigMenu,
61
+ DataGalleryDisplayMenu,
62
+ detectCardConfigFromFields,
63
+ DEFAULT_DATA_GALLERY_DISPLAY_CONFIG,
64
+ type DataGalleryCardConfig,
65
+ type DataGalleryCardConfigSerializable,
66
+ type DataGalleryDisplayConfig
67
+ } from '@kivacore/ui-pro-shared/components/kiva/data-gallery';
68
+ import { toServerRule } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/data-grid-server';
69
+ import {
70
+ isLabelResolvedRelationTarget,
71
+ readRelationCellDisplayValue,
72
+ resolveRelationCellOpts,
73
+ type RelationCellUserOption
74
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/relation-cell';
75
+ import {
76
+ buildRelationColumnEntries,
77
+ buildRelationColumnLabel,
78
+ buildRelationGroupLabel,
79
+ buildRelationSortToken,
80
+ parseRelationColumnId,
81
+ type RelationColumnEntry,
82
+ type RelationParentFieldsPayload
83
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/relation-columns';
84
+ import { DataGridAdvancedFilter } from '@kivacore/ui-pro-shared/components/kiva/data-grid/data-grid-advanced-filter';
85
+ import {
86
+ preserveAdvancedFilter,
87
+ readAdvancedFilterGroup,
88
+ readEmittableAdvancedFilterGroup,
89
+ withAdvancedFilter,
90
+ withoutAdvancedFilter
91
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/advanced-grid-filter';
92
+ import { normalizeFilterOperators } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/filter-operator-normalize';
93
+ import {
94
+ buildRelationFilterFieldMap,
95
+ keepEmittableRelationFilters,
96
+ resolveRelationFilterVariant,
97
+ type RelationFilterFieldConfig
98
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/relation-filters';
99
+ import {
100
+ extractUnservableColumnName,
101
+ matchesUnservableColumn
102
+ } from '@kivacore/ui-pro-shared/components/kiva/data-grid/lib/unservable-column';
103
+ import { type CellUserOption, type DataGridColumnOptions, type RelationNavigationArgs } from '@kivacore/ui-pro-shared/components/kiva/data-grid/types';
104
+ import {
105
+ type AsyncOptionsConfig,
106
+ type ColumnConfig,
107
+ type FilterStrategy
108
+ } from '@kivacore/ui-pro-shared/components/kiva/data-table-filter/core/types';
109
+ import { type Locale as DataTableFilterLocale } from '@kivacore/ui-pro-shared/components/kiva/data-table-filter/lib/i18n';
110
+ import {
111
+ DataTableSideFilters,
112
+ type SideFilterDefaults,
113
+ type SideFilterSectionGroup,
114
+ type DataTableSideFiltersProps, useDataTableSideFilters
115
+ } from '@kivacore/ui-pro-shared/components/kiva/data-table-side-filters';
116
+ import { KivaIcon } from '@kivacore/ui-pro-shared/components/kiva/kiva-icon';
117
+ import { DataGridViewSelect, type DataGridViewSelectVariant } from '@kivacore/ui-pro-shared/components/kiva/data-grid-view-select';
118
+ import { BulkUpdateDialog } from '@kivacore/ui-pro-shared/components/kiva/bulk-update-dialog';
119
+ import { EmailComposeDialog } from '@kivacore/ui-pro-shared/components/kiva/email-compose-dialog';
120
+ import { type EnumOption, type IField } from '@kivacore/ui-pro-shared/components/kiva/form-fields/types';
121
+ import { InstantMessageComposeDialog } from '@kivacore/ui-pro-shared/components/kiva/instant-message-compose-dialog';
122
+ import { RecordDeleteConfirmDialog } from '@kivacore/ui-pro-shared/components/kiva/record-delete-confirm-dialog';
123
+
124
+ import { Button } from '@kivacore/ui-pro-shared/components/button';
125
+ import {
126
+ DropdownMenu,
127
+ DropdownMenuContent,
128
+ DropdownMenuItem,
129
+ DropdownMenuTrigger
130
+ } from '@kivacore/ui-pro-shared/components/dropdown-menu';
131
+ import { Input } from '@kivacore/ui-pro-shared/components/input';
132
+ import { cn } from '@kivacore/ui-pro-shared/lib/utils';
133
+ import {
134
+ isDefaultDateFormatContext,
135
+ useDateFormat
136
+ } from '@kivacore/ui-pro-shared/hooks/kiva/use-date-format';
137
+ import {
138
+ isDefaultNumberFormatContext,
139
+ useNumberFormat
140
+ } from '@kivacore/ui-pro-shared/hooks/kiva/use-number-format';
141
+ import {
142
+ useDataExport,
143
+ type DataExportColumn
144
+ } from '@kivacore/ui-pro-shared/hooks/kiva/use-data-export';
145
+ import { getSharedKivaInventory } from '@kivacore/ui-pro-shared/hooks/kiva/use-kiva-inventory';
146
+ import { normalizeKivaUser, unwrapList, type KivaUserRecord } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/kiva-hook-utils';
147
+ import {
148
+ KivaDataExportMenu,
149
+ kivaDataExportColumnKeys,
150
+ encodeKivaDataExportColumn,
151
+ type KivaDataExportColumn,
152
+ type KivaDataExportFieldOption,
153
+ type KivaDataExportSelection
154
+ } from '@kivacore/ui-pro-shared/components/kiva/kiva-data-export-menu';
155
+ import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
156
+
157
+ import { AUTONUMBER_FIELD_SLUG, isAutonumberEditable } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/autonumber-setting';
158
+
159
+ import {
160
+ useKivaDataExport,
161
+ type KivaDataExportPayload
162
+ } from './use-kiva-data-export';
163
+ import {
164
+ buildTanstackColumnDef, extractEnumOptions, getCellOpts, toIField
165
+ } from './use-kiva-field-component';
166
+ import {
167
+ useKivaDataViewSelect,
168
+ type UseKivaDataViewSelectOptions,
169
+ type UseKivaDataViewSelectResult
170
+ } from './use-kiva-data-view-select';
171
+ import {
172
+ KivaPivotFilterGroup,
173
+ type KivaPivotFilterGroupField,
174
+ type PivotFilterRule
175
+ } from './use-kiva-pivot-filter';
176
+ import {
177
+ buildPersistKey,
178
+ resolvePersistConfig,
179
+ useParameterPersistence,
180
+ type PersistStateProp
181
+ } from './use-parameter-persistence';
182
+
183
+ /**
184
+ * Shape of a TanStack DB collection generated by `@kivacore/tanstack-db-generator`.
185
+ * Only `list` is required by this hook; consumers may pass the full collection.
186
+ */
187
+ export interface KivaDataGridCollection<TData> {
188
+ list: (params?: Record<string, unknown>) => Promise<Array<TData> | { data: Array<TData> }>;
189
+ /** PATCH `/items/bulk` — used for inline change save and bulk-update dialog. */
190
+ updateMany?: (body: {
191
+ records: Array<{ id: string } & Record<string, unknown>>;
192
+ enableAutomation?: boolean;
193
+ enableChangeLogging?: boolean;
194
+ }) => Promise<unknown>;
195
+ /** DELETE `/items` — used for bulk delete from the selection toolbar. */
196
+ deleteMany?: (body: {
197
+ recordIds: Array<string>;
198
+ childActions?: Record<string, 'keep' | 'delete' | 'user_decides'>;
199
+ }) => Promise<unknown>;
200
+ }
201
+
202
+ /**
203
+ * Built-in bulk actions surfaced when one or more rows are selected.
204
+ *
205
+ * `email` / `message` are **schema-gated**: they only render when the data
206
+ * source actually has a `field-email` / `field-phone` column (and a `client`
207
+ * is available). Listing them has no effect on grids without those fields.
208
+ */
209
+ export type KivaDataGridBulkAction = 'update' | 'delete' | 'export' | 'email' | 'message';
210
+
211
+ /** Field types whose values seed the batch email composer. */
212
+ export const EMAIL_FIELD_TYPES: ReadonlySet<string> = new Set(['field-email']);
213
+ /** Field types whose values seed the batch SMS / WhatsApp composer. */
214
+ export const PHONE_FIELD_TYPES: ReadonlySet<string> = new Set(['field-phone']);
215
+
216
+ /** Collect the slugs of every field whose `type` is in `types`. */
217
+ export function collectFieldSlugsByType(
218
+ fields: ReadonlyArray<{ slug?: unknown; type?: unknown }> | undefined,
219
+ types: ReadonlySet<string>
220
+ ): string[] {
221
+ if (!fields) return [];
222
+
223
+ const slugs: string[] = [];
224
+
225
+ for (const field of fields) {
226
+ if (typeof field.slug === 'string' && typeof field.type === 'string' && types.has(field.type)) {
227
+ slugs.push(field.slug);
228
+ }
229
+ }
230
+
231
+ return slugs;
232
+ }
233
+
234
+ /**
235
+ * Pull the de-duplicated string values held by `slugs` across `rows` — used to
236
+ * pre-fill the batch email / message composer with the selected rows' contact
237
+ * points.
238
+ */
239
+ export function collectRecipientValues<TData>(
240
+ rows: ReadonlyArray<TData>,
241
+ slugs: ReadonlyArray<string>
242
+ ): string[] {
243
+ const seen = new Set<string>();
244
+ const out: string[] = [];
245
+
246
+ for (const row of rows) {
247
+ const record = row as Record<string, unknown>;
248
+
249
+ for (const slug of slugs) {
250
+ const raw = record[slug];
251
+
252
+ if (typeof raw !== 'string') continue;
253
+
254
+ const value = raw.trim();
255
+
256
+ if (!value || seen.has(value)) continue;
257
+
258
+ seen.add(value);
259
+ out.push(value);
260
+ }
261
+ }
262
+
263
+ return out;
264
+ }
265
+
266
+ /**
267
+ * Field slugs the legacy Vue exporter dropped before forwarding the column
268
+ * list to `query-export`. They're either internal bookkeeping (parent IDs,
269
+ * sort_order, …) or duplicates of presentation metadata (`icon`, `color`).
270
+ */
271
+ /*
272
+ * Decode HTML entities in strings returned by the backend (e.g. `&amp;` → `&`).
273
+ * Uses a temporary textarea so the browser's HTML parser does the work — safe
274
+ * in all client-only contexts (SSR would need a library like `he`).
275
+ */
276
+ function decodeHtmlEntities(str: string): string {
277
+ const txt = document.createElement('textarea');
278
+
279
+ txt.innerHTML = str;
280
+
281
+ return txt.value;
282
+ }
283
+
284
+ /*
285
+ * Separator for the `excludeFieldSlugs` content key. A character that can
286
+ * never appear in a slug is used so the join/split round-trip is exact.
287
+ */
288
+ const EXCLUDE_SLUG_KEY_SEPARATOR = '\u0000';
289
+
290
+ const DEFAULT_SERVER_EXPORT_EXCLUDED_SLUGS: ReadonlyArray<string> = [
291
+ 'data',
292
+ 'document',
293
+ 'parent_data_source_id',
294
+ 'parent_record_id',
295
+ 'icon',
296
+ 'color',
297
+ 'mentions',
298
+ 'followers',
299
+ 'type',
300
+ 'tenant_view_id',
301
+ 'tenant_data_source_id',
302
+ 'sort_order',
303
+ 'editor_view_id'
304
+ ];
305
+
306
+ /**
307
+ * Target field types whose value arrives from a nested projection as a bare
308
+ * `{ id }` (or, for the multi-valued sibling, an array of bare id strings) that
309
+ * only the tenant user roster can resolve.
310
+ *
311
+ * This is the COMPLETE list, not a sample. Every other type a borrowed column
312
+ * can be built on either carries its own label (select / status / enum resolve
313
+ * to `{ id, name }`) or is a scalar. Relation targets never reach a column at
314
+ * all: the catalogue is one hop only.
315
+ */
316
+ const USER_VALUED_RELATION_TARGET_TYPES = new Set<string>(['field-userSelect', 'field-userMultiSelect']);
317
+
318
+ /**
319
+ * Field types whose values aren't stored on the row and therefore don't
320
+ * round-trip through the export pipeline (action buttons, etc.).
321
+ */
322
+ const DEFAULT_SERVER_EXPORT_EXCLUDED_TYPES: ReadonlyArray<string> = ['field-action', 'action'];
323
+
324
+ /**
325
+ * Cell variants whose value is an id, a list of ids or a reference object.
326
+ * A file built in the browser writes the label the cell shows instead.
327
+ */
328
+ const LABELLED_EXPORT_VARIANTS = new Set<string>([
329
+ 'select',
330
+ 'status',
331
+ 'enum',
332
+ 'multi-select',
333
+ 'tag-select',
334
+ 'user',
335
+ 'user-multi-select',
336
+ 'relation',
337
+ 'file',
338
+ 'image'
339
+ ]);
340
+
341
+ /** A column's export header: the label the grid shows, else the field name, else the slug. */
342
+ function exportColumnLabel(label: unknown, fieldName: unknown, slug: string): string {
343
+ if (typeof label === 'string' && label.length > 0) return label;
344
+ if (typeof fieldName === 'string' && fieldName.length > 0) return fieldName;
345
+
346
+ return slug;
347
+ }
348
+
349
+ /** Keys a reference object keeps its display text under, in order of preference. */
350
+ const EXPORT_LABEL_KEYS: ReadonlyArray<string> = [
351
+ 'name',
352
+ 'label',
353
+ 'filename',
354
+ 'file_name'
355
+ ];
356
+
357
+ /**
358
+ * The text a labelled cell shows. Option and user labels come from the cell's
359
+ * option list, relation and file names from the value itself. An id with no
360
+ * label is left out rather than written as a uuid; an `enum` value is readable
361
+ * as it is, so it is kept.
362
+ */
363
+ function formatExportLabel(
364
+ value: unknown,
365
+ cell: { variant?: string; options?: ReadonlyArray<{ value: string; label: string }> } | undefined
366
+ ): string {
367
+ const labelOf = (item: unknown): string => {
368
+ if (item === null || item === undefined || item === '') return '';
369
+
370
+ if (typeof item === 'string' || typeof item === 'number') {
371
+ const label = cell?.options?.find(option => option.value === String(item))?.label;
372
+
373
+ return label ?? (cell?.variant === 'enum' ? String(item) : '');
374
+ }
375
+
376
+ if (typeof item !== 'object') return String(item);
377
+
378
+ const record = item as Record<string, unknown>;
379
+
380
+ for (const key of EXPORT_LABEL_KEYS) {
381
+ const text = record[key];
382
+
383
+ if (typeof text === 'string' && text.length > 0) return text;
384
+ }
385
+
386
+ const fullName = [record.firstname, record.lastname]
387
+ .filter((part): part is string => typeof part === 'string' && part.length > 0)
388
+ .join(' ');
389
+
390
+ if (fullName) return fullName;
391
+
392
+ return record.id === undefined ? '' : labelOf(record.id);
393
+ };
394
+
395
+ return (Array.isArray(value) ? value : [value])
396
+ .map(labelOf)
397
+ .filter(label => label.length > 0)
398
+ .join(', ');
399
+ }
400
+
401
+ /**
402
+ * Shape of `ZodSelectQueryPayload` parameters passed to the items endpoint.
403
+ * Mirrors the docs guide at `docs/guides/kiva-api-query-guide.md`.
404
+ */
405
+ export interface KivaDataGridListParams {
406
+ columns?: string;
407
+ filters?: RuleGroupType | Record<string, unknown>;
408
+ filterKeyword?: string;
409
+ orderBy?: string | { field: string; direction?: 'asc' | 'desc' } | Array<{ field: string; direction?: 'asc' | 'desc' }>;
410
+ limit?: number;
411
+ offset?: number;
412
+ fullCount?: boolean;
413
+ expand?: Array<string>;
414
+ expandTypes?: Array<'user' | 'enum' | 'relation'>;
415
+ [key: string]: unknown;
416
+ }
417
+
418
+ /** Convenience alias to the parameter shape consumed by `useDataGrid`. */
419
+ type UseDataGridParams<TData> = Parameters<typeof useDataGrid<TData>>[0];
420
+
421
+ /**
422
+ * Configuration for the optional side-panel filter rail rendered alongside
423
+ * the grid. The hook wires the panel's emitted `RuleGroupType` into the
424
+ * items request, ANDed with the saved view's `filterQuery` and any
425
+ * toolbar filter rules.
426
+ */
427
+ export interface KivaDataGridSideFiltersConfig<TData> {
428
+ /**
429
+ * Filter columns shown in the side panel. Mirrors the `columnsConfig`
430
+ * accepted by `useDataTableFilters` / `useDataTableSideFilters`.
431
+ */
432
+ columnsConfig: ReadonlyArray<ColumnConfig<TData, any, any, any>>;
433
+ /**
434
+ * Filter strategy passed to `useDataTableSideFilters`. Server-paged grids
435
+ * should use `'server'` (the default) so values are surfaced as
436
+ * `RuleGroupType` rules; `'client'` filters in-memory.
437
+ */
438
+ strategy?: FilterStrategy;
439
+ /** Per-column UI hints (collapsed / mode / threshold / hidden / sticky / etc.). */
440
+ defaults?: SideFilterDefaults;
441
+ /** Optional grouping of filter sections into named blocks. */
442
+ sections?: ReadonlyArray<SideFilterSectionGroup>;
443
+ /** Visual variant for the panel container. */
444
+ variant?: DataTableSideFiltersProps<TData>['variant'];
445
+ /** Header title. Pass `null` to hide. Default `'Filters'`. */
446
+ title?: DataTableSideFiltersProps<TData>['title'];
447
+ /** Show the active-filter chip strip below the header. Default `true`. */
448
+ showActiveChips?: boolean;
449
+ /** Show "Clear all" button next to the title when any filter is active. Default `true`. */
450
+ showClearAll?: boolean;
451
+ /**
452
+ * When `true`, renders a search input above the sections. Pass a column id
453
+ * to drive a specific text-typed column.
454
+ */
455
+ searchable?: boolean | string;
456
+ /** Override for the "Clear all" label. Default `'Clear all'`. */
457
+ clearAllLabel?: string;
458
+ /** Override for the per-section "Clear" label. Default `'Clear'`. */
459
+ clearLabel?: string;
460
+ /** Locale forwarded to the underlying filter UI. Default `'en'`. */
461
+ locale?: DataTableFilterLocale;
462
+ /** Extra className for the panel root. */
463
+ className?: string;
464
+ /** Override for the collapse-button accessible label. Default `'Collapse filters'`. */
465
+ collapseAriaLabel?: string;
466
+ /** Override for the expand-button accessible label. Default `'Expand filters'`. */
467
+ expandAriaLabel?: string;
468
+ /** Width of the collapsed rail (number → px). Default `36`. */
469
+ collapsedWidth?: number | string;
470
+ }
471
+
472
+ /**
473
+ * Serializable snapshot of the data-grid's user-editable view parameters,
474
+ * persisted via `persistState`. Row selection and the current page index are
475
+ * intentionally excluded (stale / disorienting on restore).
476
+ */
477
+ export interface DataGridPersistSnapshot {
478
+ searchInput?: string;
479
+ sorting?: SortingState;
480
+ columnFilters?: ColumnFiltersState;
481
+ pageSize?: number;
482
+ columnVisibility?: VisibilityState;
483
+ columnOrder?: ColumnOrderState;
484
+ columnPinning?: ColumnPinningState;
485
+ columnSizing?: ColumnSizingState;
486
+ grouping?: GroupingState;
487
+ expanded?: ExpandedState;
488
+ rowHeight?: RowHeightValue;
489
+ displayMode?: DataGridDisplayMode;
490
+ pivotFilterRule?: Array<PivotFilterRule> | null;
491
+ }
492
+
493
+ const USERS_PAGE_SIZE = 1000;
494
+
495
+ /**
496
+ * Every user of the tenant. `/v1/users` pages without an order, so stepping
497
+ * through it by offset can skip or repeat people: when the first page is not
498
+ * all of them, the rest come in one request sized by the total it reports.
499
+ */
500
+ async function fetchAllUsers(client: RestApiClient): Promise<Array<KivaUserRecord>> {
501
+ const first = await client.get<unknown>('/v1/users', { limit: USERS_PAGE_SIZE });
502
+ const total = (first as { meta?: { total?: unknown } } | null)?.meta?.total;
503
+ const response = typeof total === 'number' && total > USERS_PAGE_SIZE ? await client.get<unknown>('/v1/users', { limit: total }) : first;
504
+
505
+ return unwrapList<Record<string, unknown>>(response)
506
+ .map(normalizeKivaUser)
507
+ .filter((user): user is KivaUserRecord => user !== null);
508
+ }
509
+
510
+ function usersDirectoryQueryOptions(client: RestApiClient) {
511
+ return {
512
+ queryKey: ['kiva-users', 'all'] as const,
513
+ queryFn: () => fetchAllUsers(client),
514
+ staleTime: 5 * 60_000
515
+ };
516
+ }
517
+
518
+ interface UserFilterOption {
519
+ value: string;
520
+ label: string;
521
+ secondaryLabel?: string;
522
+ imageUrl?: string;
523
+ }
524
+
525
+ function toUserFilterOption(user: KivaUserRecord): UserFilterOption {
526
+ const name = user.name?.trim() || [user.firstname, user.lastname].filter(Boolean).join(' ');
527
+ const label = name || user.email || user.id;
528
+
529
+ return {
530
+ value: user.id,
531
+ label,
532
+ ...(user.email && user.email !== label ? { secondaryLabel: user.email } : {}),
533
+ ...(user.photo ? { imageUrl: user.photo } : {})
534
+ };
535
+ }
536
+
537
+ /** Folds case, accents and the Turkish dotted and dotless i, so "behlul" finds "Behlül" and "idris" finds "İdris". */
538
+ function foldForSearch(text: string): string {
539
+ return text.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/ı/g, 'i').toLowerCase();
540
+ }
541
+
542
+ /** The options whose name or email holds every word of the search. */
543
+ function filterUserOptions(options: ReadonlyArray<UserFilterOption>, search: string | undefined): Array<UserFilterOption> {
544
+ const words = foldForSearch(search ?? '').split(/\s+/).filter(Boolean);
545
+
546
+ if (words.length === 0) return [...options];
547
+
548
+ return options.filter((option) => {
549
+ const text = foldForSearch(`${option.label} ${option.secondaryLabel ?? ''}`);
550
+
551
+ return words.every(word => text.includes(word));
552
+ });
553
+ }
554
+
555
+ function withUserIcon(option: UserFilterOption) {
556
+ return option.imageUrl ? option : {
557
+ ...option,
558
+ icon: (
559
+ <KivaIcon
560
+ icon="huge user-circle-02"
561
+ className="size-6 text-muted-foreground" />
562
+ )
563
+ };
564
+ }
565
+
566
+ export interface UseKivaDataGridOptions<TData> extends UseKivaDataViewSelectOptions {
567
+ /**
568
+ * Pre-resolved rows. When provided, the hook skips its internal items query
569
+ * — supply your own data, refetch, etc. Takes precedence over `collection`.
570
+ */
571
+ data?: Array<TData>;
572
+ /**
573
+ * TanStack DB collection generated by `@kivacore/tanstack-db-generator`
574
+ * (e.g., the result of `useBaseOrganizationCollection()`). The hook will
575
+ * call `collection.list(listParams)` inside a `useQuery` to fetch rows.
576
+ */
577
+ collection?: KivaDataGridCollection<TData>;
578
+ /**
579
+ * Extra query params merged on top of the params derived from the active
580
+ * view (columns, filters, orderBy) and the toolbar search input
581
+ * (filterKeyword). Use this for `expand`, `limit`/`offset`, `fullCount`, etc.
582
+ */
583
+ listParams?: KivaDataGridListParams;
584
+ /**
585
+ * Stack one or more pivot filter strips above the grid toolbar. Each entry
586
+ * configures a `<PivotFilter>` (status, priority, user, date bucket, …)
587
+ * via `useKivaPivotFilter` internally. The strips render automatically
588
+ * inside the returned `toolbar`, selections are AND-merged into the items
589
+ * query filter, and pill counts cross-react bidirectionally — no consumer
590
+ * glue required.
591
+ *
592
+ * Example: `pivotFilters: [{ fieldSlug: 'status' }, { fieldSlug: 'priority' }]`.
593
+ */
594
+ pivotFilters?: ReadonlyArray<KivaPivotFilterGroupField>;
595
+ /** Default page size when no `limit` is supplied via `listParams`. Default `100`. */
596
+ defaultLimit?: number;
597
+ /**
598
+ * Fallback Kiva saved-form `layout` used when the active view has no bound
599
+ * form (`SavedDataGridView.formId` empty). Surfaced through the returned
600
+ * `formViewProps.formLayout`. When this is omitted too, `formViewProps` falls
601
+ * back to a single-column auto-form built from the data-source fields
602
+ * (`{ formLayout: null, gridColumns: 1 }`). Has no effect on the grid itself —
603
+ * it only feeds a companion `useKivaFormView` for record create/edit.
604
+ */
605
+ defaultFormLayout?: Record<string, unknown> | null;
606
+ /**
607
+ * Disable the internal items query. Useful when you want toolbar wiring
608
+ * without fetching rows. Default `true` when no `data` is provided.
609
+ */
610
+ enableItemsQuery?: boolean;
611
+ /** Prepend a row-select checkbox column as the first column. Default `true`. */
612
+ showSelectColumn?: boolean;
613
+ /** Show 1-based row markers on the select column when not selected. Default `true`. */
614
+ enableRowMarkers?: boolean;
615
+ /** Override the default `getDataGridSelectColumn` definition entirely. */
616
+ selectColumn?: ColumnDef<TData>;
617
+ /**
618
+ * Optional actions column rendered as the **second** column (right after the
619
+ * select column). Build it with `getDataGridActionsColumn({ cell: ... })`
620
+ * and supply your own action buttons via `cell`.
621
+ */
622
+ actionsColumn?: ColumnDef<TData>;
623
+ /** Extra columns prepended after the select + actions columns. */
624
+ extraColumns?: Array<ColumnDef<TData>>;
625
+ /**
626
+ * Row identity. Without it TanStack keys rows by index, so a cached cell
627
+ * value survives into whatever row lands at that index next — switching
628
+ * views leaves an `accessorFn` column showing the previous row's value.
629
+ */
630
+ getRowId?: (row: TData, index: number, parent?: unknown) => string;
631
+ /**
632
+ * Enum options for fields the API reports without any. A `field-status` /
633
+ * `field-select` whose enum set was never registered arrives with an empty
634
+ * `enums`, which leaves the filter picker, the grouping menu and the cell
635
+ * renderer with nothing to offer. Supplying them here fills every one of
636
+ * those surfaces at once; fields that already carry options are untouched.
637
+ */
638
+ fieldEnums?: Record<string, Array<{ id: string; name: string; color?: string }>>;
639
+ /** Per-field column override. Return `null` to skip a field entirely. */
640
+ mapColumn?: (
641
+ field: DataSourceField,
642
+ defaultColumn: ColumnDef<TData>
643
+ ) => ColumnDef<TData> | null;
644
+ /**
645
+ * Translate / override every column's header label before it is rendered.
646
+ * Called with the schema-derived label (`field.name` / the column's string
647
+ * `header`) and its `meta.label`; return the string to display. Lets
648
+ * consumers map headers from their own i18n dictionaries without a per-field
649
+ * `mapColumn`. Applied after `mapColumn`, so it also translates whatever
650
+ * `header` a `mapColumn` override produced (string headers only — a custom
651
+ * `header` render function is left untouched).
652
+ */
653
+ dynamicLabelTranslator?: (label: string) => string;
654
+ /**
655
+ * Translate / override each enum option's display label before it is
656
+ * rendered in cells, filter dropdowns, and grouped-value headers. Called
657
+ * once per option with the option and its owning field; return the text to
658
+ * show. Options carry a stable, language-independent `slug` — build keys like
659
+ * `enums.<field.slug>.<option.slug>` and translate `name` while `slug` /
660
+ * `color` / `icon` are preserved. Return `option.name` unchanged for anything
661
+ * you don't want to translate. Applied to static enum fields
662
+ * (`field-select`, `field-status`, …); the translated names flow into the
663
+ * cell, the filter menu, and row-group values from one place.
664
+ */
665
+ dynamicEnumOptionTranslator?: (option: EnumOption, field: IField) => string;
666
+ /** Forwarded to `useDataGrid`. */
667
+ enableSearch?: boolean;
668
+ /** Forwarded to `useDataGrid`. Default `true` (required for the row-grouping picker to populate). */
669
+ enableGrouping?: boolean;
670
+ /** Forwarded to `useDataGrid`. Default `true`. */
671
+ readOnly?: boolean;
672
+ /** Toolbar feature toggles (all default to `true`). */
673
+ enableViewSelect?: boolean;
674
+ /**
675
+ * Variant for the view picker. Default `'horizontal-tabs'`. Use
676
+ * `'dropdown'` for a compact toolbar (single Select-style trigger) or
677
+ * `'vertical-tabs'` for sidebar layouts.
678
+ */
679
+ viewSelectVariant?: DataGridViewSelectVariant;
680
+ /**
681
+ * Maximum number of view tabs to render inline in the
682
+ * `'horizontal-tabs'` variant. Overflow tabs collapse into the active
683
+ * view's overflow menu. Ignored for `'dropdown'` and `'vertical-tabs'`.
684
+ */
685
+ viewSelectMaxVisible?: number;
686
+ enableSearchInput?: boolean;
687
+ enableFilterMenu?: boolean;
688
+ enableGroupMenu?: boolean;
689
+ enableSortMenu?: boolean;
690
+ enableRowHeightMenu?: boolean;
691
+ enableDisplayMenu?: boolean;
692
+ enableFieldsMenu?: boolean;
693
+ enableReloadButton?: boolean;
694
+ /**
695
+ * Gallery display-mode configuration. The in-grid gallery (`displayMode:
696
+ * 'gallery'`) renders the shared `DataGalleryCard` (8 field slots, 5
697
+ * variants, render hooks). This is the initial / fallback card config —
698
+ * it's overridden by the active saved view's `galleryCardConfig`, and when
699
+ * neither is set the hook auto-detects sensible slot bindings from the data
700
+ * source fields. Supply `renderCover` / `renderAvatar` / etc. here to
701
+ * customize slot rendering.
702
+ */
703
+ cardConfig?: DataGalleryCardConfig<TData>;
704
+ /**
705
+ * Initial / fallback gallery display config (variant, density, cover style,
706
+ * column count, card size, header/footer/label toggles). Overridden by the
707
+ * active saved view's `galleryDisplayConfig`. Merged over
708
+ * `DEFAULT_DATA_GALLERY_DISPLAY_CONFIG`.
709
+ */
710
+ galleryDisplayConfig?: Partial<DataGalleryDisplayConfig>;
711
+ /**
712
+ * Show the gallery display + card-fields menus in the toolbar when the grid
713
+ * is in `displayMode: 'gallery'`. Default `true`. The same config is also
714
+ * editable (and persisted) from the view editor's "Gallery View" section.
715
+ */
716
+ enableGalleryMenus?: boolean;
717
+ /** Fires when a gallery card body (not the checkbox) is clicked. */
718
+ onCardClick?: (record: TData, rowIndex: number) => void;
719
+ /**
720
+ * Show the server-side data export dropdown in the toolbar. Pulls all rows
721
+ * matching the active view's filters/keyword from
722
+ * `POST /v1/edge/run/query-export`. Default `true`.
723
+ */
724
+ enableServerExportMenu?: boolean;
725
+ /**
726
+ * Show the client-side export dropdown in the toolbar (row scope + column
727
+ * scope). Off by default: redundant while the server export is on.
728
+ */
729
+ enableClientExportMenu?: boolean;
730
+ /**
731
+ * Paging mode used when the saved view carries no paging setting. Default
732
+ * `'virtual-scroll'` (unchanged behaviour). Hosts whose data sources exceed
733
+ * the single-request row cap can opt into `'standard'` paging instead.
734
+ */
735
+ defaultPagingMode?: 'standard' | 'virtual-scroll';
736
+ /**
737
+ * Let users reorder columns — "Move left / right" in the column menu and
738
+ * drag-and-drop on the header row. Off by default.
739
+ */
740
+ enableColumnReorder?: boolean;
741
+ /**
742
+ * Draw a small always-visible chevron on dropdown cells (select, status,
743
+ * multi-select, tags) so they read as editable before interaction. Off by
744
+ * default.
745
+ */
746
+ showDropdownChevron?: boolean;
747
+ /** Row cap forwarded to the server export endpoint. Default `10000`. */
748
+ serverExportLimit?: number;
749
+ /**
750
+ * Field types to skip when picking columns for the server export. Defaults
751
+ * to virtual / non-stored types like `field-action`.
752
+ */
753
+ serverExportExcludedFieldTypes?: ReadonlyArray<string>;
754
+ /**
755
+ * Field slugs to skip when picking columns for the server export. Defaults
756
+ * to internal metadata columns mirroring the legacy Vue exporter.
757
+ */
758
+ serverExportExcludedSlugs?: ReadonlyArray<string>;
759
+ /**
760
+ * Called when the toolbar reload button is clicked, after the items
761
+ * query refetches. The toolbar button refetches records only — it does
762
+ * not reload data source metadata or views. Use the returned `reload`
763
+ * function (or `refetch`) when you need a full hard refresh.
764
+ */
765
+ onReload?: () => void;
766
+ /** Toolbar search input config. */
767
+ searchPlaceholder?: string;
768
+ /** Debounce in ms before applying the search input. Default `300`. */
769
+ searchDebounceMs?: number;
770
+ /** Extra className for the toolbar root. */
771
+ toolbarClassName?: string;
772
+ /**
773
+ * Custom node prepended to the left side of the built-in toolbar (next to
774
+ * the view tabs and search input). Use for app-specific buttons or
775
+ * filters that should sit alongside the standard controls.
776
+ */
777
+ toolbarStartContent?: ReactNode;
778
+ /**
779
+ * Custom node appended to the right side of the built-in toolbar (after
780
+ * the reload button). Use for app-specific actions like "Add record",
781
+ * "Refresh metrics", etc.
782
+ */
783
+ toolbarEndContent?: ReactNode;
784
+ /**
785
+ * Extra controls rendered in the pagination footer (`pagingMode: 'standard'`
786
+ * only), after the built-in page-size select + reload button and behind a
787
+ * separator. Forwarded to `<DataGrid paginationExtraSlots>` via `gridProps`.
788
+ */
789
+ paginationExtraSlots?: ReactNode;
790
+ /**
791
+ * Extra row-selection actions appended to the floating action bar after
792
+ * the built-in `bulkActions` (`update`, `delete`, `export`). Each entry's
793
+ * `onAction(selectedRows)` (or `render(selectedRows)`) receives the
794
+ * currently selected rows so handlers can drive their own logic.
795
+ */
796
+ extraBulkActions?: Array<DataGridAction<TData>>;
797
+ /**
798
+ * Track inline cell edits and surface a save/discard banner. Forwarded to
799
+ * `useDataGrid` as `enableChangeTracking`. Default `true`.
800
+ *
801
+ * When enabled and the user clicks "Save", the hook batches every changed
802
+ * row into a single `PATCH /items/bulk` call (`enableAutomation: false`,
803
+ * `enableChangeLogging: false` per the bulk endpoint defaults). Override
804
+ * via `onSaveChanges`.
805
+ */
806
+ trackChanges?: boolean;
807
+ /** Custom save-changes handler. Receives the changed rows + new full data array. */
808
+ onSaveChanges?: (changes: Array<RowChange>, data: Array<TData>) => void | Promise<void>;
809
+ /**
810
+ * Selection-bar bulk action toggles. Default:
811
+ * `['update', 'delete', 'export', 'email', 'message']`. The `email` /
812
+ * `message` actions are **schema-gated** — they only appear when the data
813
+ * source actually has a `field-email` / `field-phone` column, so the default
814
+ * is safe for every grid. `email` opens the `EmailComposer`, `message` opens
815
+ * the SMS / WhatsApp `InstantMessageComposer`, both pre-filled with the
816
+ * selected rows' addresses. Pass `false` (or an empty array) to hide the bar
817
+ * entirely.
818
+ */
819
+ bulkActions?: false | ReadonlyArray<KivaDataGridBulkAction>;
820
+ /**
821
+ * Which fields to include when the user picks Export. `'visible'` (default) uses
822
+ * the table's currently-visible columns; `'all'` includes every data-source field;
823
+ * an explicit array picks specific slugs in order.
824
+ */
825
+ exportColumns?: 'visible' | 'all' | ReadonlyArray<string>;
826
+ /** File name (without extension) for exports. Default = `dataSourceSlug`. */
827
+ exportFileName?: string;
828
+ /**
829
+ * Tenant-wide users list to seed `field-userSelect` /
830
+ * `field-userMultiSelect` cell options. When supplied, those cells render
831
+ * avatars + labels using this list instead of the row's expanded payload
832
+ * (which is still used as a fallback when a row references a user not in
833
+ * the list). Typical usage: fetch `/v1/users` once at app boot and pass
834
+ * the result here on every grid mount.
835
+ */
836
+ users?: ReadonlyArray<CellUserOption>;
837
+ /**
838
+ * Resolve a navigation target for a relation cell. When this returns a
839
+ * truthy href, the grid renders a small "open related record" affordance
840
+ * inside the cell next to the label. Receives the raw foreign-key id
841
+ * (read from `row.original[columnId]`, not the projected display label)
842
+ * plus relation metadata declared on the column.
843
+ *
844
+ * Use this for SPA-style navigation where `<a href>` keeps middle-click /
845
+ * ctrl-click / "open in new tab" semantics. Return `undefined` for rows
846
+ * the host can't route to.
847
+ */
848
+ getRelationHref?: (args: RelationNavigationArgs<TData>) => string | undefined;
849
+ /**
850
+ * Imperative variant of `getRelationHref` — wired for apps using
851
+ * programmatic routing (e.g. `router.push`). When both are supplied,
852
+ * `getRelationHref` wins (the affordance stays a real `<a>`). When only
853
+ * this handler is set, the affordance renders as a `<button>` and
854
+ * invokes the callback on click.
855
+ */
856
+ onOpenRelation?: (args: RelationNavigationArgs<TData>) => void;
857
+ /**
858
+ * Per-relation-column icon source. Maps a relation field slug to the slug
859
+ * of a field on the **related** data source that holds the record's
860
+ * display icon — a `field-icon` string identifier (e.g.
861
+ * `'huge ai-brain-03'`) or a `field-image` value (URL string, or
862
+ * `{ signed_url, file_name }` shape). When configured, the cell prefixes
863
+ * the name with the icon and the items-query projection grows from
864
+ * `<relationSlug>(id, name, autonumber_id)` to
865
+ * `<relationSlug>(id, name, autonumber_id, <iconFieldSlug>)` so the
866
+ * server returns the icon value alongside the name.
867
+ *
868
+ * Example:
869
+ * ```ts
870
+ * relationIconFields: {
871
+ * organization: 'company_icon', // field-icon on the org DSO
872
+ * country: 'flag_image' // field-image on the country DSO
873
+ * }
874
+ * ```
875
+ *
876
+ * The relation field slugs are keyed on this grid's data source. The
877
+ * value (`iconFieldSlug`) is a column slug on the **related** data
878
+ * source. Unknown relation slugs are ignored.
879
+ */
880
+ relationIconFields?: Record<string, string>;
881
+ /**
882
+ * Offer columns BORROWED from a related data source — "the Matter's Project
883
+ * Lead next to each time entry".
884
+ *
885
+ * Off by default because it costs one extra request per data source
886
+ * (`/v1/dev/data-sources/:id/fields?expand=parent`) and widens the Fields
887
+ * menu considerably. When on, every relation field on this schema is paired
888
+ * with every non-relation field of the data source it points at; the
889
+ * resulting columns start HIDDEN, so nothing changes until the user picks
890
+ * one. Picking one adds its field to that relation's projection group and
891
+ * makes it filterable through `rel_<relation>/<field>` — with the
892
+ * positive-only operator set `lib/relation-filters.ts` explains.
893
+ */
894
+ enableRelationColumns?: boolean;
895
+ /**
896
+ * Tenant-aware date formatter used by `DateCell`. Pass
897
+ * `dateUtils.formatDate` from `@kivacore/app-utils` so saved-view cells
898
+ * render dates in the account's regional format.
899
+ */
900
+ formatDate?: (value: unknown) => string;
901
+ /**
902
+ * Tenant-aware datetime formatter used by `DateTimeCell`. Pass
903
+ * `dateUtils.formatDateTime` from `@kivacore/app-utils`.
904
+ */
905
+ formatDateTime?: (value: unknown) => string;
906
+ /**
907
+ * Tenant-aware numeric formatter used by `NumberCell` /
908
+ * `CurrencyCell` / `PercentCell`. Pass a function that wraps
909
+ * `numberUtils.formatNumber` / `numberUtils.formatCurrency` /
910
+ * `numberUtils.formatPercent` from `@kivacore/app-utils`.
911
+ */
912
+ formatNumber?: (
913
+ value: unknown,
914
+ opts?: { variant?: 'number' | 'currency' | 'percent'; currency?: string }
915
+ ) => string;
916
+ /**
917
+ * Conditional row color rules forwarded to `useDataGrid`. Each rule's
918
+ * predicate runs against the row data and tints matching rows.
919
+ */
920
+ rowColorRules?: UseDataGridParams<TData>['rowColorRules'];
921
+ /**
922
+ * Conditional cell color rules forwarded to `useDataGrid`. Targets
923
+ * specific column ids and tints individual cells when their predicate
924
+ * matches.
925
+ */
926
+ cellColorRules?: UseDataGridParams<TData>['cellColorRules'];
927
+ /**
928
+ * Accessible label for a row, surfaced via `aria-label` on row elements
929
+ * and used by the change-tracking save banner. Forwarded to `useDataGrid`.
930
+ */
931
+ getRowLabel?: UseDataGridParams<TData>['getRowLabel'];
932
+ /**
933
+ * Inline "Add row" handler. When supplied, the grid renders the add-row
934
+ * footer cell and Tab-out-of-last-cell shortcut. Forwarded to
935
+ * `useDataGrid`. The handler may return a `CellPosition` to focus the
936
+ * newly added cell.
937
+ */
938
+ onRowAdd?: UseDataGridParams<TData>['onRowAdd'];
939
+ /**
940
+ * Bulk "add N rows" handler used by the paste flow when the clipboard has
941
+ * more rows than the grid. Forwarded to `useDataGrid`. Without it the paste
942
+ * expansion falls back to calling `onRowAdd` once per needed row.
943
+ */
944
+ onRowsAdd?: UseDataGridParams<TData>['onRowsAdd'];
945
+ /**
946
+ * Row delete handler. When supplied, the grid enables the context-menu
947
+ * "Delete rows" item and the Ctrl/Cmd+Delete shortcut. Forwarded to
948
+ * `useDataGrid`.
949
+ */
950
+ onRowsDelete?: UseDataGridParams<TData>['onRowsDelete'];
951
+ /**
952
+ * Live cell-mutation channel. Called with the full next data array on every
953
+ * inline edit, paste and clear. Forwarded to `useDataGrid`.
954
+ *
955
+ * Supply this to persist edits as they happen. Combined with
956
+ * `trackChanges: false` it replaces the Save/Discard bar, since
957
+ * `useDataGrid` then emits unconditionally and keeps no pending state.
958
+ */
959
+ onDataChange?: UseDataGridParams<TData>['onDataChange'];
960
+ /**
961
+ * Enables clipboard paste (Ctrl/Cmd+V) into the selected cell range.
962
+ * Forwarded to `useDataGrid`. Row expansion during paste additionally needs
963
+ * `onRowsAdd` (or `onRowAdd`).
964
+ */
965
+ enablePaste?: UseDataGridParams<TData>['enablePaste'];
966
+ /**
967
+ * Extra `TableMeta` entries merged into the meta this hook builds. Use it for
968
+ * host-owned slots such as `columnHeaderActions`; the hook's own wiring
969
+ * (formatters, cell option loader, column options) always wins.
970
+ */
971
+ meta?: UseDataGridParams<TData>['meta'];
972
+ /**
973
+ * Initial TanStack Table state (sorting, columnFilters, rowSelection,
974
+ * pagination, …). Forwarded to `useDataGrid`. Note that the active
975
+ * saved view still drives the running state via `applyViewToTable`; use
976
+ * this only for one-time defaults applied before any view is loaded.
977
+ */
978
+ initialState?: UseDataGridParams<TData>['initialState'];
979
+ /**
980
+ * Activate the side-panel filter rail rendered alongside the grid. When
981
+ * `true`, the hook's `sideFilters` return value renders a
982
+ * `<DataTableSideFilters>` panel and feeds its emitted `RuleGroupType`
983
+ * into the items request (ANDed with the saved view filter and any
984
+ * toolbar filter menu rules). The toolbar filter menu remains available
985
+ * — both can be used together. Default `false`.
986
+ *
987
+ * Requires `sideFiltersConfig` to be supplied with a `columnsConfig`.
988
+ */
989
+ enableSideFilters?: boolean;
990
+ /**
991
+ * Required side-panel configuration when `enableSideFilters` is `true`.
992
+ * Exposes the filter `columnsConfig`, optional section grouping, and
993
+ * presentation overrides.
994
+ */
995
+ sideFiltersConfig?: KivaDataGridSideFiltersConfig<TData>;
996
+ /**
997
+ * Initial expanded state for the side panel. When `false`, the panel
998
+ * mounts collapsed and renders a vertical rail with a 90°-rotated
999
+ * "Filters" label that re-expands the panel on click. Default `true`.
1000
+ */
1001
+ sideFiltersDefaultExpanded?: boolean;
1002
+ /**
1003
+ * Controlled expanded state. Pair with `onSideFiltersExpandedChange`. When
1004
+ * omitted, the hook manages the state internally.
1005
+ */
1006
+ sideFiltersExpanded?: boolean;
1007
+ /** Called when the user toggles the side-panel collapse/expand control. */
1008
+ onSideFiltersExpandedChange?: (expanded: boolean) => void;
1009
+ /**
1010
+ * Width of the side panel when expanded. Number → px. Default `280`.
1011
+ * Applied via inline `style.width` on the wrapper.
1012
+ */
1013
+ sideFiltersWidth?: number | string;
1014
+ /**
1015
+ * Field slugs to drop from the data source metadata before anything else
1016
+ * consumes it — columns, items query payload, saved view restoration,
1017
+ * filter / sort menus, exports. Useful when the backend schema still
1018
+ * advertises a field that the underlying DB no longer has (the items
1019
+ * endpoint returns `column "X" does not exist` in that case).
1020
+ *
1021
+ * Prefer fixing the backend metadata; use this as an escape hatch when
1022
+ * that isn't available.
1023
+ */
1024
+ excludeFieldSlugs?: ReadonlyArray<string>;
1025
+ /**
1026
+ * Persist the user's manually-edited view parameters (search keyword,
1027
+ * toolbar + pivot filters, sort, row grouping, row height, column
1028
+ * visibility / order / pinning / sizing, page size) to storage and restore
1029
+ * them on the next mount. Keyed per active saved view, so each view
1030
+ * remembers its own tweaks.
1031
+ *
1032
+ * `true` → session storage. Pass `{ storage: 'local' }` to survive restarts,
1033
+ * or `{ key: '…' }` to override the data-source segment of the storage key.
1034
+ * Row selection and the current page index are intentionally not persisted.
1035
+ */
1036
+ persistState?: PersistStateProp;
1037
+ }
1038
+
1039
+ /**
1040
+ * Ready-to-spread subset of `UseKivaFormViewOptions` describing which form
1041
+ * the active view should render. Spread straight into `useKivaFormView`.
1042
+ */
1043
+ export interface KivaDataGridFormViewProps {
1044
+ /**
1045
+ * Saved-form `layout` for the active view's bound form, or the
1046
+ * `defaultFormLayout` fallback. `null` → no form: `useKivaFormView`
1047
+ * auto-builds the form from the data-source fields.
1048
+ */
1049
+ formLayout: Record<string, unknown> | null;
1050
+ /**
1051
+ * Grid column count for the auto-form fallback (single column). Set only
1052
+ * when no form layout is available; omitted when a form is bound so the
1053
+ * form's own column count (derived from its layout) wins.
1054
+ */
1055
+ gridColumns?: 1 | 2 | 3 | 4;
1056
+ /**
1057
+ * The grid's already-resolved data-source schema. Passing it into
1058
+ * `useKivaFormView` lets a record form (e.g. opened from a row) reuse the
1059
+ * schema the grid already fetched instead of issuing its own `getBySlug` on
1060
+ * every dialog open. `undefined` until the grid's schema query resolves.
1061
+ */
1062
+ dataSource?: DataSource;
1063
+ }
1064
+
1065
+ export interface UseKivaDataGridResult<TData>
1066
+ extends UseKivaDataViewSelectResult {
1067
+ /** TanStack Table instance — pass to `<DataGrid>` and any toolbar building blocks. */
1068
+ table: ReturnType<typeof useDataGrid<TData>>['table'];
1069
+ /**
1070
+ * Id of the saved form bound to the active view (`SavedDataGridView.formId`),
1071
+ * or `undefined` when the active view has no form bound.
1072
+ */
1073
+ activeViewFormId: string | undefined;
1074
+ /**
1075
+ * The resolved `DataForm` bound to the active view, or `undefined`. Looked up
1076
+ * from `forms` by `activeViewFormId`.
1077
+ */
1078
+ activeViewForm: DataForm | undefined;
1079
+ /**
1080
+ * Spread into `useKivaFormView({ client, appSlug, dataSourceSlug, ...formViewProps })`
1081
+ * to render the active view's bound form — or the single-column fallback when
1082
+ * no form is bound and no `defaultFormLayout` was supplied.
1083
+ */
1084
+ formViewProps: KivaDataGridFormViewProps;
1085
+ /**
1086
+ * Currently selected rows (the row `original` objects). Reactive — reading
1087
+ * this in a parent's render re-renders when the selection changes, so a
1088
+ * page header can show a bulk-action button without `useEffect`/ref glue.
1089
+ */
1090
+ selectedRows: Array<TData>;
1091
+ /** Count of currently selected rows (equivalent to `selectedRows.length`). */
1092
+ selectedRowCount: number;
1093
+ /**
1094
+ * Spread onto `<DataGrid table={table} {...gridProps} />`. Includes the
1095
+ * bulk-action descriptors so the built-in floating selection bar lights up
1096
+ * automatically.
1097
+ */
1098
+ gridProps: Omit<ReturnType<typeof useDataGrid<TData>>, 'table' | 'selectedRows' | 'selectedRowCount'> & {
1099
+ actions?: Array<DataGridAction<TData>>;
1100
+ /** True while a background refetch is in flight (e.g. toolbar reload). */
1101
+ isReloading?: boolean;
1102
+ /**
1103
+ * Reload handler for the pagination footer's reload button — the same
1104
+ * `reloadItems` the toolbar reload button calls, so both share one handler
1105
+ * and one `isReloading` state.
1106
+ */
1107
+ onReload?: () => void;
1108
+ /** Consumer controls for the pagination footer (from the `paginationExtraSlots` option). */
1109
+ paginationExtraSlots?: ReactNode;
1110
+ /**
1111
+ * Resolved gallery card config (rich — 8 slots + render hooks) for the
1112
+ * grid's `displayMode: 'gallery'`. Hydrated from the active saved view,
1113
+ * the `cardConfig` option, then auto-detection.
1114
+ */
1115
+ galleryCardConfig?: DataGalleryCardConfig<TData>;
1116
+ /** Resolved gallery display config (variant / density / cover / columns …). */
1117
+ galleryDisplayConfig?: DataGalleryDisplayConfig;
1118
+ /** Card-body click handler forwarded to the gallery cards. */
1119
+ onCardClick?: (record: TData, rowIndex: number) => void;
1120
+ };
1121
+ /**
1122
+ * Pre-wired toolbar element ready to render above the grid. When
1123
+ * `pivotFilters` is provided, the strips are stacked at the top of this
1124
+ * element automatically.
1125
+ */
1126
+ toolbar: ReactNode;
1127
+ /**
1128
+ * Current AND-combined filter rule produced by the pivot filter strips
1129
+ * (when `pivotFilters` is set), or `null` when no pivot has a selection.
1130
+ * Already merged into the grid's items query — exposed for inspection
1131
+ * and persistence (e.g. "1 pivot filter active" badge).
1132
+ */
1133
+ pivotFilterRule: Array<PivotFilterRule> | null;
1134
+ /**
1135
+ * Interactive `<KivaPivotFilterGroup>` element — the same one the
1136
+ * built-in toolbar mounts. `null` when no `pivotFilters` were
1137
+ * configured. Exposed so downstream hooks (e.g. `useKivaDataGallery`)
1138
+ * can compose the strip into their own toolbar without duplicating the
1139
+ * pivot state.
1140
+ */
1141
+ pivotFiltersStrip: ReactNode;
1142
+ /**
1143
+ * Pre-wired side panel element. `null` for `'horizontal-tabs'` and
1144
+ * `'dropdown'` view variants. Returns a `<DataGridSidePanel>` containing
1145
+ * the vertical view picker when `viewSelectVariant === 'vertical-tabs'`.
1146
+ * Render to the left of `<DataGrid>` (e.g. inside a flex row) when
1147
+ * non-null.
1148
+ */
1149
+ sidePanel: ReactNode;
1150
+ /**
1151
+ * Pre-wired side-panel filter element. `null` when `enableSideFilters`
1152
+ * is `false`. Renders the full panel when expanded and a thin vertical
1153
+ * rail (with a 90°-rotated "Filters" label) when collapsed. Render to
1154
+ * the left of `<DataGrid>` (typically inside the same flex row as
1155
+ * `sidePanel`).
1156
+ */
1157
+ sideFilters: ReactNode;
1158
+ /** Current expanded state of the side filter panel. */
1159
+ sideFiltersExpanded: boolean;
1160
+ /** Programmatically toggle the side filter panel expanded state. */
1161
+ setSideFiltersExpanded: (expanded: boolean) => void;
1162
+ /**
1163
+ * Current `RuleGroupType` emitted by the side filter panel, or
1164
+ * `undefined` when no rules are active. Already merged into the items
1165
+ * request — exposed for inspection / persistence.
1166
+ */
1167
+ sideFiltersQuery: RuleGroupType | undefined;
1168
+ /** Resolved rows passed to the grid — from `data`, `collection.list()`, or the direct items fetch. */
1169
+ items: Array<TData>;
1170
+ /** The list params actually sent to the backend (after merging view state, search, and `listParams`). */
1171
+ resolvedListParams: KivaDataGridListParams;
1172
+ /**
1173
+ * Resolved paging mode for the active view. Pass to `<DataGrid pagingMode>`
1174
+ * so the standard footer renders only when the view enables it.
1175
+ */
1176
+ pagingMode: 'standard' | 'virtual-scroll' | undefined;
1177
+ /** Triggers `refetch()` (data source + views + items) and the optional `onReload` callback. */
1178
+ reload: () => void;
1179
+ }
1180
+
1181
+ /** Fill every required display key from the defaults so a partial view config is safe. */
1182
+ function mergeGalleryDisplay(
1183
+ override: Partial<DataGalleryDisplayConfig> | undefined
1184
+ ): DataGalleryDisplayConfig {
1185
+ return { ...DEFAULT_DATA_GALLERY_DISPLAY_CONFIG, ...override };
1186
+ }
1187
+
1188
+ /** Pick only the serializable card-config keys (drop the render hooks) for state / persistence. */
1189
+ function toSerializableCardConfig<TData>(
1190
+ config: DataGalleryCardConfig<TData> | undefined
1191
+ ): DataGalleryCardConfigSerializable {
1192
+ if (!config) return {};
1193
+
1194
+ return {
1195
+ titleField: config.titleField,
1196
+ descriptionField: config.descriptionField,
1197
+ subtitleField: config.subtitleField,
1198
+ avatarField: config.avatarField,
1199
+ coverImageField: config.coverImageField,
1200
+ badgeField: config.badgeField,
1201
+ timelineField: config.timelineField,
1202
+ bodyFields: config.bodyFields,
1203
+ footerFields: config.footerFields,
1204
+ variant: config.variant
1205
+ };
1206
+ }
1207
+
1208
+ export function useKivaDataGrid<TData>(
1209
+ options: UseKivaDataGridOptions<TData>
1210
+ ): UseKivaDataGridResult<TData> {
1211
+ const {
1212
+ data: providedData,
1213
+ collection,
1214
+ listParams,
1215
+ pivotFilters,
1216
+ defaultLimit = 100,
1217
+ defaultFormLayout,
1218
+ enableItemsQuery = providedData === undefined,
1219
+ showSelectColumn = true,
1220
+ enableRowMarkers = true,
1221
+ selectColumn,
1222
+ actionsColumn,
1223
+ extraColumns,
1224
+ getRowId,
1225
+ fieldEnums,
1226
+ mapColumn,
1227
+ dynamicLabelTranslator,
1228
+ dynamicEnumOptionTranslator,
1229
+ enableSearch = false,
1230
+ enableGrouping = true,
1231
+ readOnly = true,
1232
+ enableViewSelect = true,
1233
+ viewSelectVariant = 'horizontal-tabs',
1234
+ viewSelectMaxVisible,
1235
+ enableSearchInput = true,
1236
+ enableFilterMenu = true,
1237
+ enableGroupMenu = true,
1238
+ enableSortMenu = true,
1239
+ enableRowHeightMenu = true,
1240
+ enableDisplayMenu = true,
1241
+ enableFieldsMenu = true,
1242
+ enableReloadButton = true,
1243
+ cardConfig: cardConfigProp,
1244
+ galleryDisplayConfig: galleryDisplayConfigProp,
1245
+ enableGalleryMenus = true,
1246
+ onCardClick,
1247
+ enableServerExportMenu = true,
1248
+ enableClientExportMenu = false,
1249
+ defaultPagingMode = 'virtual-scroll',
1250
+ enableColumnReorder = false,
1251
+ showDropdownChevron = false,
1252
+ serverExportLimit = 10000,
1253
+ serverExportExcludedFieldTypes,
1254
+ serverExportExcludedSlugs,
1255
+ onReload,
1256
+ searchPlaceholder = 'Search…',
1257
+ searchDebounceMs = 300,
1258
+ toolbarClassName,
1259
+ toolbarStartContent,
1260
+ toolbarEndContent,
1261
+ paginationExtraSlots,
1262
+ extraBulkActions,
1263
+ trackChanges = true,
1264
+ onSaveChanges,
1265
+ bulkActions = [
1266
+ 'update',
1267
+ 'delete',
1268
+ 'export',
1269
+ 'email',
1270
+ 'message'
1271
+ ],
1272
+ exportColumns = 'visible',
1273
+ exportFileName,
1274
+ users,
1275
+ getRelationHref,
1276
+ onOpenRelation,
1277
+ relationIconFields,
1278
+ enableRelationColumns = false,
1279
+ formatDate,
1280
+ formatDateTime,
1281
+ formatNumber,
1282
+ rowColorRules,
1283
+ cellColorRules,
1284
+ getRowLabel,
1285
+ onRowAdd,
1286
+ onRowsAdd,
1287
+ onRowsDelete,
1288
+ onDataChange,
1289
+ enablePaste,
1290
+ meta: metaOverrides,
1291
+ initialState,
1292
+ enableSideFilters = false,
1293
+ sideFiltersConfig,
1294
+ sideFiltersDefaultExpanded = true,
1295
+ sideFiltersExpanded: sideFiltersExpandedProp,
1296
+ onSideFiltersExpandedChange,
1297
+ sideFiltersWidth = 280,
1298
+ excludeFieldSlugs,
1299
+ persistState,
1300
+ ...viewSelectOptions
1301
+ } = options;
1302
+
1303
+ /*
1304
+ * Resolve `persistState` to primitive values so an inline object literal
1305
+ * (`persistState={{ storage: 'local' }}`) doesn't churn the memo / effect
1306
+ * deps every render.
1307
+ */
1308
+ const persistConfig = resolvePersistConfig(persistState);
1309
+ const persistEnabled = persistConfig !== null;
1310
+ const persistStorage = persistConfig?.storage ?? 'session';
1311
+ const persistKeyOverride = persistConfig?.key ?? '';
1312
+
1313
+ /*
1314
+ * Fall back to the surrounding `<DateFormatProvider>` /
1315
+ * `<NumberFormatProvider>` context (typically installed by
1316
+ * `<KivaTenantProvider>`) when the caller doesn't pass formatter
1317
+ * props explicitly. Caller props still win when supplied.
1318
+ *
1319
+ * Only inject the context formatter when a *real* provider is
1320
+ * mounted. With no provider the hooks return their no-provider
1321
+ * sentinel (raw `String(value)`), and shadowing the cell's own
1322
+ * locale-aware fallback (e.g. `Intl.NumberFormat` for currency /
1323
+ * percent in `NumberCell`) would be a regression for apps that
1324
+ * haven't adopted `<KivaTenantProvider>` yet.
1325
+ */
1326
+ const dateFormatCtx = useDateFormat();
1327
+ const numberFormatCtx = useNumberFormat();
1328
+ const hasDateProvider = !isDefaultDateFormatContext(dateFormatCtx);
1329
+ const hasNumberProvider = !isDefaultNumberFormatContext(numberFormatCtx);
1330
+ const effectiveFormatDate = formatDate ?? (hasDateProvider ? dateFormatCtx.formatDate : undefined);
1331
+ const effectiveFormatDateTime = formatDateTime ?? (hasDateProvider ? dateFormatCtx.formatDateTime : undefined);
1332
+ const effectiveFormatNumber = formatNumber ?? (hasNumberProvider ? numberFormatCtx.formatNumber : undefined);
1333
+
1334
+ /*
1335
+ * Apply the schema escape hatch as early as possible — every downstream
1336
+ * derivation (column build, list params, exports, view restoration)
1337
+ * should see the filtered shape so stale metadata can't leak into a
1338
+ * request that the backend will reject.
1339
+ *
1340
+ * The Set is memoized by *content* (joined string key), not by array
1341
+ * identity. Callers tend to pass inline literals like
1342
+ * `excludeFieldSlugs: ['foo', 'bar']` — keying on the array reference
1343
+ * would rebuild the Set every render, cascade through `dataSource` /
1344
+ * `fields` / `gridViewSelectProps` / `resolvedListParams` (all derived
1345
+ * via `useMemo` from the Set), and ultimately re-key the items query
1346
+ * + re-attach every Radix `composeRefs` chain on the view picker, which
1347
+ * shows up as a `Maximum update depth exceeded` loop.
1348
+ */
1349
+ /*
1350
+ * The Set is derived from the content key rather than from the array, so
1351
+ * the only dependency is a value the body actually uses. Callers tend to
1352
+ * pass inline literals; keying on the array reference would rebuild the Set
1353
+ * every render and cascade through every memo derived from it.
1354
+ */
1355
+ const excludeFieldSlugsKey = excludeFieldSlugs ? excludeFieldSlugs.join(EXCLUDE_SLUG_KEY_SEPARATOR) : '';
1356
+ const excludeFieldSlugSet = useMemo<Set<string> | null>(() => {
1357
+ if (!excludeFieldSlugsKey) return null;
1358
+
1359
+ return new Set<string>(excludeFieldSlugsKey.split(EXCLUDE_SLUG_KEY_SEPARATOR));
1360
+ }, [excludeFieldSlugsKey]);
1361
+
1362
+ const bulkActionSet = useMemo(() => {
1363
+ if (bulkActions === false) return new Set<KivaDataGridBulkAction>();
1364
+
1365
+ return new Set<KivaDataGridBulkAction>(bulkActions);
1366
+ }, [bulkActions]);
1367
+
1368
+ /*
1369
+ * Slot the items-query refetch into a ref so the bulk-action handlers
1370
+ * (declared higher in the hook than `itemsQuery`) can refresh the grid
1371
+ * after a successful mutation.
1372
+ */
1373
+ const itemsRefetchRef = useRef<(() => Promise<unknown>) | null>(null);
1374
+
1375
+ /*
1376
+ * Stays in `viewSelectOptions` so it's forwarded to `useKivaDataViewSelect`,
1377
+ * but we also read it locally to seed the table grouping.
1378
+ */
1379
+ const { defaultRowGroupingColumn } = viewSelectOptions;
1380
+
1381
+ /*
1382
+ * When `persistState` is on, the active-view id follows the same storage
1383
+ * backend (session/local) and the same `docyrus:view-params` namespace as
1384
+ * the persisted view parameters — under the reserved `__active-view__`
1385
+ * segment so it can't collide with a per-view params entry. The fallback
1386
+ * segment includes `appId` (mirroring the legacy key) because saved-view
1387
+ * lists are appId-scoped — without it, two surfaces on the same data
1388
+ * source distinguished only by `appId` would clobber each other's entry.
1389
+ * Explicit `activeViewStorage` / `persistKey` options still win. Without
1390
+ * `persistState` the view-select keeps its historical default (always-on
1391
+ * localStorage under `docyrus:data-grid-view:…`).
1392
+ */
1393
+ const viewSelect = useKivaDataViewSelect(persistEnabled ? {
1394
+ ...viewSelectOptions,
1395
+ activeViewStorage: viewSelectOptions.activeViewStorage ?? persistStorage,
1396
+ persistKey: viewSelectOptions.persistKey ?? buildPersistKey([persistKeyOverride || [viewSelectOptions.appSlug, viewSelectOptions.dataSourceSlug, viewSelectOptions.appId].filter(Boolean).join(':'), '__active-view__'])
1397
+ } : viewSelectOptions);
1398
+ const {
1399
+ dataSource: rawDataSource,
1400
+ fields: rawFields,
1401
+ gridViewSelectProps: rawGridViewSelectProps,
1402
+ refetch: refetchViewSelect,
1403
+ views,
1404
+ activeViewId
1405
+ } = viewSelect;
1406
+
1407
+ /*
1408
+ * Apply `excludeFieldSlugs` once at the source so every downstream
1409
+ * consumer (columns, list params, view editor, filter menu) sees a
1410
+ * schema without the dropped slugs. Without this the items endpoint
1411
+ * would 500 with `column "<slug>" does not exist` whenever the saved
1412
+ * metadata advertises a field the underlying DB no longer has.
1413
+ */
1414
+ /*
1415
+ * Fill in options for fields the API sends with an empty `enums`. Every enum
1416
+ * surface — filter picker, grouping, cell renderer — reads the field, so
1417
+ * this is the one place that has to know.
1418
+ */
1419
+ const applyFieldEnums = useCallback(
1420
+ (list: Array<any>) => {
1421
+ if (!fieldEnums) return list;
1422
+
1423
+ return list.map((field: any) => {
1424
+ const injected = typeof field?.slug === 'string' ? fieldEnums[field.slug] : undefined;
1425
+
1426
+ if (!injected || (Array.isArray(field.enums) && field.enums.length > 0)) return field;
1427
+
1428
+ return { ...field, enums: injected };
1429
+ });
1430
+ },
1431
+ [fieldEnums]
1432
+ );
1433
+
1434
+ const dataSource = useMemo(() => {
1435
+ if (!rawDataSource) return rawDataSource;
1436
+ if (!excludeFieldSlugSet && !fieldEnums) return rawDataSource;
1437
+
1438
+ const sourceFields = rawDataSource.fields ?? [];
1439
+ const kept = excludeFieldSlugSet ? sourceFields.filter((field: { slug: string }) => !excludeFieldSlugSet.has(field.slug)) : sourceFields;
1440
+
1441
+ return { ...rawDataSource, fields: applyFieldEnums(kept) } as typeof rawDataSource;
1442
+ }, [
1443
+ rawDataSource,
1444
+ excludeFieldSlugSet,
1445
+ applyFieldEnums,
1446
+ fieldEnums
1447
+ ]);
1448
+
1449
+ /*
1450
+ * ── Columns borrowed from a related data source ───────────────────────────
1451
+ *
1452
+ * VALIDATE EVERY BORROWED COLUMN AGAINST THE TARGET'S LIVE SCHEMA. An inner
1453
+ * field the target data source does not have is a HARD error that fails the
1454
+ * WHOLE request — `Field 'project_lead' not found in data source '…'` — so the
1455
+ * grid renders "no records" with the base columns taken down alongside it.
1456
+ * That is not hypothetical: a CUSTOM field exists on the tenant that asked for
1457
+ * it and not on the next one, so shipping an unvalidated token empties the
1458
+ * grid everywhere else.
1459
+ *
1460
+ * The catalogue built from the parent-fields endpoint IS the validator: an id
1461
+ * absent from it never becomes a token, and the grid degrades to its base
1462
+ * columns instead of breaking.
1463
+ */
1464
+ const relationFieldsQuery = useQuery({
1465
+ queryKey: ['kiva', 'kivaDataGridRelationFields', dataSource?.id ?? null] as const,
1466
+ queryFn: () => viewSelectOptions.client.get<{
1467
+ parent_fields?: RelationParentFieldsPayload;
1468
+ data?: { parent_fields?: RelationParentFieldsPayload };
1469
+ }>(`/v1/dev/data-sources/${dataSource?.id}/fields`, { expand: 'parent' }),
1470
+ enabled: enableRelationColumns && Boolean(dataSource?.id),
1471
+ staleTime: 5 * 60_000
1472
+ });
1473
+
1474
+ const relationColumnCatalogue = useMemo(
1475
+ () => {
1476
+ const payload = relationFieldsQuery.data;
1477
+ const parentFields = payload?.parent_fields ?? payload?.data?.parent_fields;
1478
+
1479
+ return buildRelationColumnEntries(
1480
+ dataSource?.fields as Array<Record<string, unknown>> | undefined,
1481
+ parentFields
1482
+ );
1483
+ },
1484
+ [relationFieldsQuery.data, dataSource?.fields]
1485
+ );
1486
+
1487
+ /*
1488
+ * Localize the catalogue's labels. It reads the TARGET schema's raw `name`,
1489
+ * which is the SYSTEM (English) label, while this grid's own columns go
1490
+ * through `dynamicLabelTranslator` — leaving these raw puts English section
1491
+ * headings and English field names directly beneath translated base fields in
1492
+ * the same picker.
1493
+ *
1494
+ * The PARTS are translated, never the composed string: a translator matches a
1495
+ * whole schema label, and "Name (Client)" is not a label any schema declares.
1496
+ * Both composed forms are then rebuilt by the same two functions the pure
1497
+ * module uses, so a heading and the label it sits above cannot drift apart,
1498
+ * and `shortenRelationColumnLabel` can still undo the composition.
1499
+ */
1500
+ const relationColumnSpecs = useMemo<Array<RelationColumnEntry>>(() => {
1501
+ if (!dynamicLabelTranslator || relationColumnCatalogue.length === 0) {
1502
+ return relationColumnCatalogue;
1503
+ }
1504
+
1505
+ return relationColumnCatalogue.map((entry) => {
1506
+ const fieldLabel = dynamicLabelTranslator(entry.fieldLabel);
1507
+ const relationLabel = dynamicLabelTranslator(entry.relationLabel);
1508
+ const targetDataSourceLabel = entry.targetDataSourceLabel === '' ? '' : dynamicLabelTranslator(entry.targetDataSourceLabel);
1509
+
1510
+ return {
1511
+ ...entry,
1512
+ fieldLabel,
1513
+ relationLabel,
1514
+ targetDataSourceLabel,
1515
+ label: buildRelationColumnLabel(fieldLabel, relationLabel),
1516
+ group: buildRelationGroupLabel(relationLabel, targetDataSourceLabel)
1517
+ };
1518
+ });
1519
+ }, [relationColumnCatalogue, dynamicLabelTranslator]);
1520
+
1521
+ /**
1522
+ * Tenant roster in the shape the borrowed-value formatter reads. A user-valued
1523
+ * target projects as `{ id }` (or, for its multi-valued sibling, an array of
1524
+ * bare id strings), so the label has to come from here or the cell would print
1525
+ * a uuid.
1526
+ */
1527
+ const relationCellUsers = useMemo<Array<RelationCellUserOption>>(
1528
+ () => (users ?? []).map(user => ({ id: user.value, label: user.label })),
1529
+ [users]
1530
+ );
1531
+
1532
+ /*
1533
+ * Only the borrowed columns whose TARGET field type can be filtered honestly
1534
+ * get a wire path. The rest keep `meta.filterable: false`, which the filter
1535
+ * menu and the column header already honour. See `lib/relation-filters.ts`
1536
+ * for why an option-valued target is not among them.
1537
+ */
1538
+ const filterableRelationColumnSpecs = useMemo(
1539
+ () => relationColumnSpecs.filter(
1540
+ spec => resolveRelationFilterVariant(spec.fieldType) !== null
1541
+ ),
1542
+ [relationColumnSpecs]
1543
+ );
1544
+
1545
+ /*
1546
+ * Built from the CATALOGUE, never from a column id found in saved state: the
1547
+ * catalogue is the only thing that has checked the relation and the target
1548
+ * field against the live schema, and an id it does not vouch for becomes a
1549
+ * path that hard-errors the whole response.
1550
+ */
1551
+ const relationFilterFieldMap = useMemo<Record<string, RelationFilterFieldConfig>>(
1552
+ () => buildRelationFilterFieldMap(filterableRelationColumnSpecs),
1553
+ [filterableRelationColumnSpecs]
1554
+ );
1555
+
1556
+ const filterableRelationColumnIds = useMemo(
1557
+ () => new Set(filterableRelationColumnSpecs.map(spec => spec.id)),
1558
+ [filterableRelationColumnSpecs]
1559
+ );
1560
+
1561
+ /*
1562
+ * The borrowed columns the user has actually turned on, mirrored out of the
1563
+ * table so the PROJECTION can react to the Fields menu.
1564
+ *
1565
+ * The grid's own columns do not need this — their projection is derived from
1566
+ * the saved view, and hiding one only hides an already-fetched value. A
1567
+ * borrowed column is the opposite: it is in no view, so until it is switched
1568
+ * on the request must not ask for it (each one widens the projection with a
1569
+ * relation join), and the moment it is switched on the request must.
1570
+ */
1571
+ const [visibleRelationColumnIds, setVisibleRelationColumnIds] = useState<Array<string>>([]);
1572
+
1573
+ const fields = useMemo(() => {
1574
+ if (!excludeFieldSlugSet) return applyFieldEnums(rawFields as Array<any>) as typeof rawFields;
1575
+
1576
+ return applyFieldEnums(rawFields.filter((field) => {
1577
+ /*
1578
+ * `FullField` types the slug via its underlying option-list union
1579
+ * (resolved as `unknown`). Narrow defensively rather than trusting
1580
+ * the upstream type — the exclusion is a string-keyed set.
1581
+ */
1582
+ const slug = typeof field.slug === 'string' ? field.slug : '';
1583
+
1584
+ return !excludeFieldSlugSet.has(slug);
1585
+ }) as Array<any>) as typeof rawFields;
1586
+ }, [rawFields, excludeFieldSlugSet, applyFieldEnums]);
1587
+
1588
+ /*
1589
+ * Re-pack `gridViewSelectProps` with the filtered fields so the view
1590
+ * editor's column picker / filter row / column-visibility list don't
1591
+ * resurrect a slug we deliberately dropped. The view-select hook itself
1592
+ * stays unaware of the exclusion — keeps that hook reusable for callers
1593
+ * that don't need the escape hatch.
1594
+ */
1595
+ const baseGridViewSelectProps = useMemo(() => {
1596
+ if (!excludeFieldSlugSet) return rawGridViewSelectProps;
1597
+
1598
+ return { ...rawGridViewSelectProps, fields };
1599
+ }, [rawGridViewSelectProps, fields, excludeFieldSlugSet]);
1600
+
1601
+ const activeView = useMemo<SavedDataGridView | undefined>(
1602
+ () => views.find(view => view.id === activeViewId),
1603
+ [views, activeViewId]
1604
+ );
1605
+
1606
+ /*
1607
+ * Resolve the saved form bound to the active view (if any). The binding
1608
+ * (`formId`) rides in the view's persisted `columns` blob; the embedded form
1609
+ * — with its `layout` — comes from the data source's `expand=forms` fetch.
1610
+ * `formViewProps` is a ready-to-spread payload for a companion
1611
+ * `useKivaFormView`: the bound form's layout, the `defaultFormLayout`
1612
+ * fallback, or a single-column auto-form when neither is available.
1613
+ */
1614
+ const activeViewFormId = activeView?.formId;
1615
+
1616
+ const activeViewForm = useMemo<DataForm | undefined>(
1617
+ () => (activeViewFormId ? viewSelect.forms.find(form => form.id === activeViewFormId) : undefined),
1618
+ [viewSelect.forms, activeViewFormId]
1619
+ );
1620
+
1621
+ const formViewProps = useMemo<KivaDataGridFormViewProps>(() => {
1622
+ const boundLayout = (activeViewForm?.layout ?? null) as Record<string, unknown> | null;
1623
+
1624
+ /*
1625
+ * Forward the grid's already-resolved schema (excludeFieldSlugs applied) so
1626
+ * a record form reuses it instead of issuing its own getBySlug per dialog.
1627
+ */
1628
+ if (boundLayout) return { formLayout: boundLayout, dataSource };
1629
+ if (defaultFormLayout) return { formLayout: defaultFormLayout, dataSource };
1630
+
1631
+ return { formLayout: null, gridColumns: 1, dataSource };
1632
+ }, [activeViewForm, defaultFormLayout, dataSource]);
1633
+
1634
+ /*
1635
+ * ─── Gallery (card display mode) config ────────────────────────────────
1636
+ *
1637
+ * The in-grid gallery display mode renders the shared `DataGalleryCard`
1638
+ * (same engine as the standalone `<DataGallery>`). The hook owns the live
1639
+ * card + display config so it can be edited from BOTH the toolbar gallery
1640
+ * menus AND the view editor's "Gallery View" section, and persisted into
1641
+ * the saved view. Hydration priority on a view switch:
1642
+ * 1. active view's saved `galleryCardConfig` / `galleryDisplayConfig`
1643
+ * 2. the caller's `cardConfig` / `galleryDisplayConfig` option
1644
+ * 3. auto-detection from the data source fields
1645
+ */
1646
+ const [galleryCardConfig, setGalleryCardConfig] = useState<DataGalleryCardConfigSerializable>(
1647
+ () => toSerializableCardConfig(cardConfigProp)
1648
+ );
1649
+ const [galleryDisplayConfig, setGalleryDisplayConfig] = useState<DataGalleryDisplayConfig>(
1650
+ () => mergeGalleryDisplay(galleryDisplayConfigProp)
1651
+ );
1652
+
1653
+ /*
1654
+ * Render-time hydration (React 19 set-state-during-render — discards and
1655
+ * restarts the render with the new state, no extra commit round-trip and no
1656
+ * `@eslint-react/set-state-in-effect` violation). Keyed per active view so
1657
+ * swapping views re-hydrates the gallery config from that view.
1658
+ */
1659
+ const lastAppliedGalleryViewIdRef = useRef<string | null>(null);
1660
+
1661
+ {
1662
+ const galleryViewId = activeView?.id ?? '__no_view__';
1663
+ const sourceFields = dataSource?.fields;
1664
+
1665
+ if (sourceFields && sourceFields.length > 0 && lastAppliedGalleryViewIdRef.current !== galleryViewId) {
1666
+ lastAppliedGalleryViewIdRef.current = galleryViewId;
1667
+
1668
+ if (activeView?.galleryCardConfig) {
1669
+ setGalleryCardConfig(activeView.galleryCardConfig);
1670
+ } else if (cardConfigProp) {
1671
+ setGalleryCardConfig(toSerializableCardConfig(cardConfigProp));
1672
+ } else {
1673
+ setGalleryCardConfig(detectCardConfigFromFields(sourceFields));
1674
+ }
1675
+
1676
+ setGalleryDisplayConfig(
1677
+ mergeGalleryDisplay({
1678
+ ...galleryDisplayConfigProp,
1679
+ ...activeView?.galleryDisplayConfig
1680
+ })
1681
+ );
1682
+ }
1683
+ }
1684
+
1685
+ /*
1686
+ * Merge the caller's non-serializable render hooks (renderCover / renderAvatar
1687
+ * / …) back onto the live serializable config so custom slot rendering keeps
1688
+ * working while the field bindings stay user-editable + persisted.
1689
+ */
1690
+ const resolvedGalleryCardConfig = useMemo<DataGalleryCardConfig<TData>>(
1691
+ () => ({ ...cardConfigProp, ...galleryCardConfig }),
1692
+ [cardConfigProp, galleryCardConfig]
1693
+ );
1694
+
1695
+ /*
1696
+ * Wrap the view-select props so (a) the view editor's "Gallery View" section
1697
+ * is a controlled editor over the live gallery config, and (b) saving /
1698
+ * creating a view injects the current gallery config into the persisted
1699
+ * payload. `useKivaDataGallery` wraps this again with its own config,
1700
+ * which correctly wins for gallery pages.
1701
+ */
1702
+ const gridViewSelectProps = useMemo(() => {
1703
+ const original = baseGridViewSelectProps;
1704
+
1705
+ return {
1706
+ ...original,
1707
+ galleryCardConfig,
1708
+ galleryDisplayConfig,
1709
+ onGalleryCardConfigChange: setGalleryCardConfig,
1710
+ onGalleryDisplayConfigChange: setGalleryDisplayConfig,
1711
+ onViewSave: (view: SavedDataGridView) => {
1712
+ original.onViewSave?.({ ...view, galleryCardConfig, galleryDisplayConfig });
1713
+ },
1714
+ onViewCreate: (
1715
+ view: SavedDataGridView,
1716
+ position?: { afterViewId?: string; beforeViewId?: string }
1717
+ ) => {
1718
+ original.onViewCreate?.({ ...view, galleryCardConfig, galleryDisplayConfig }, position);
1719
+ }
1720
+ };
1721
+ }, [baseGridViewSelectProps, galleryCardConfig, galleryDisplayConfig]);
1722
+
1723
+ /*
1724
+ * Standard paging means the user explicitly opted into a paginated view.
1725
+ * Virtual-scroll (the default) keeps every loaded row in a single
1726
+ * virtualized viewport — no `limit/offset` round-trips, no manual
1727
+ * pagination on the table.
1728
+ */
1729
+ const viewDrivenPagingMode = activeView?.pagingEnabled === true ? activeView.pagingMode ?? 'virtual-scroll' : undefined;
1730
+ const resolvedPagingMode: 'standard' | 'virtual-scroll' = viewDrivenPagingMode ?? defaultPagingMode;
1731
+
1732
+ const isStandardPaging = resolvedPagingMode === 'standard';
1733
+
1734
+ const initialPageSize = activeView?.pageSize ?? defaultLimit;
1735
+
1736
+ const [pagination, setPagination] = useState<PaginationState>(() => ({
1737
+ pageIndex: 0,
1738
+ pageSize: initialPageSize
1739
+ }));
1740
+
1741
+ const [searchInput, setSearchInput] = useState('');
1742
+ const [debouncedSearch, setDebouncedSearch] = useState('');
1743
+ const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
1744
+
1745
+ /*
1746
+ * Live table sorting, lifted out of `useDataGrid`'s internal store so it can
1747
+ * feed the server query (`buildListParams` → `orderBy`). The column-header
1748
+ * dropdown and the Sort menu both mutate the table's sorting via
1749
+ * `table.setSorting`, which fires `useDataGrid`'s `onSortingChange` prop —
1750
+ * we mirror it here. On a server-paged grid only the live sort can re-order
1751
+ * rows beyond the current page; without lifting it the request kept using
1752
+ * the saved view's preset sort and the user's clicks had no effect.
1753
+ *
1754
+ * `applyViewToTable` also routes through this setter on a view switch
1755
+ * (`table.setSorting(view.sorting)`), so the lifted state seeds itself from
1756
+ * the active view — `buildListParams` falls back to the view preset while
1757
+ * this is empty, producing an identical `orderBy` and therefore no extra
1758
+ * fetch when the seeding lands.
1759
+ */
1760
+ const [liveSorting, setLiveSorting] = useState<SortingState>([]);
1761
+
1762
+ /*
1763
+ * The TanStack table fires `onColumnFiltersChange` synchronously from
1764
+ * inside its `setColumnFilters` action. Some library-internal codepaths
1765
+ * end up calling that action while a descendant of the toolbar (typically
1766
+ * `<DataGridFilterMenu>`) is mid-render — React 19 surfaces that as
1767
+ * "Cannot update a component (TasksPageInner) while rendering a different
1768
+ * component (DataGridFilterMenu)". Routing the parent setter through a
1769
+ * microtask breaks the synchronous chain while still flushing the update
1770
+ * inside the same task tick, so the filter chip remains responsive.
1771
+ */
1772
+ const deferredSetColumnFilters = useCallback<typeof setColumnFilters>(
1773
+ (updater) => {
1774
+ queueMicrotask(() => setColumnFilters(previous => preserveAdvancedFilter(
1775
+ /*
1776
+ * Keep the advanced filter group alive across a table-driven rewrite of
1777
+ * `columnFilters`.
1778
+ *
1779
+ * `DataGridFilterMenu.onFiltersChange` replaces the WHOLE array from its
1780
+ * own chip state, which never carries the reserved entry — so editing any
1781
+ * chip (and "clear all" in particular) would otherwise delete the
1782
+ * advanced group, and it would read as flakiness rather than as a bug.
1783
+ * Only the reserved id is carried: preserving every unknown id would also
1784
+ * revive filters on non-filterable columns that are dropped today.
1785
+ *
1786
+ * The panel's own writes bypass this wrapper (they go through
1787
+ * `setColumnFilters`), so clearing the group still works.
1788
+ */
1789
+ typeof updater === 'function' ? updater(previous) : updater,
1790
+ previous
1791
+ )));
1792
+ },
1793
+ []
1794
+ );
1795
+
1796
+ const advancedFilterGroup = useMemo(
1797
+ () => readAdvancedFilterGroup(columnFilters),
1798
+ [columnFilters]
1799
+ );
1800
+
1801
+ const handleAdvancedFilterChange = useCallback(
1802
+ (group: RuleGroupType | undefined) => {
1803
+ setColumnFilters(previous => withAdvancedFilter(previous, group));
1804
+ },
1805
+ []
1806
+ );
1807
+
1808
+ /*
1809
+ * The empty state's "Clear filters" must clear the advanced group too.
1810
+ * `deferredSetColumnFilters` deliberately re-inserts the reserved entry on
1811
+ * every table-driven write (so editing a chip cannot drop the group), and
1812
+ * `table.resetColumnFilters()` is such a write — so without this the button
1813
+ * clears the chips, leaves the group, and the grid stays empty however often
1814
+ * it is pressed. Writing through `setColumnFilters` bypasses the carry.
1815
+ */
1816
+ const handleClearAllFilters = useCallback(() => {
1817
+ setColumnFilters([]);
1818
+ setSearchInput('');
1819
+ }, []);
1820
+
1821
+ /*
1822
+ * Re-sync pagination + clear toolbar filters when the upstream "key"
1823
+ * inputs change — store-and-compare pattern (per the React docs:
1824
+ * "You Might Not Need an Effect" → adjust state during render). This
1825
+ * avoids the `set-state-in-effect` lint and the extra render churn.
1826
+ *
1827
+ * - active view change → reset page + clear toolbar filters
1828
+ * (different views can carry different `pageSize` settings, and
1829
+ * transient relation filters from one view shouldn't leak into the
1830
+ * next)
1831
+ * - initialPageSize change → reset page
1832
+ * - search/columnFilters → reset pageIndex (the underlying total
1833
+ * shrinks, so a stale pageIndex could land out of bounds)
1834
+ * - listParams.filters change → reset pageIndex (caller-supplied base
1835
+ * filter swaps the row set; a stale page index lands out of bounds
1836
+ * and shows "No data" even though rows exist on page 1)
1837
+ */
1838
+ const baseFilterKey = useMemo(
1839
+ () => (listParams?.filters ? JSON.stringify(listParams.filters) : ''),
1840
+ [listParams?.filters]
1841
+ );
1842
+
1843
+ /*
1844
+ * Declared here (before store-and-compare) so pivotFilterRule is available
1845
+ * as a reset signal. The setter is passed down to KivaPivotFilterGroup.
1846
+ */
1847
+ const [pivotFilterRule, setPivotFilterRule] = useState<Array<PivotFilterRule> | null>(null);
1848
+
1849
+ const pivotFilterKey = useMemo(
1850
+ () => (pivotFilterRule ? JSON.stringify(pivotFilterRule) : ''),
1851
+ [pivotFilterRule]
1852
+ );
1853
+
1854
+ const [trackedActiveViewId, setTrackedActiveViewId] = useState(activeViewId);
1855
+ const [trackedInitialPageSize, setTrackedInitialPageSize] = useState(initialPageSize);
1856
+ const [trackedDebouncedSearch, setTrackedDebouncedSearch] = useState(debouncedSearch);
1857
+ const [trackedColumnFilters, setTrackedColumnFilters] = useState(columnFilters);
1858
+ const [trackedSorting, setTrackedSorting] = useState(liveSorting);
1859
+ const [trackedBaseFilterKey, setTrackedBaseFilterKey] = useState(baseFilterKey);
1860
+ const [trackedPivotFilterKey, setTrackedPivotFilterKey] = useState(pivotFilterKey);
1861
+
1862
+ if (trackedActiveViewId !== activeViewId) {
1863
+ setTrackedActiveViewId(activeViewId);
1864
+ setTrackedInitialPageSize(initialPageSize);
1865
+ setPagination({ pageIndex: 0, pageSize: initialPageSize });
1866
+ /*
1867
+ * `setColumnFilters` is intentionally NOT called here. It's wired
1868
+ * through `useDataGrid`'s `onColumnFiltersChange` prop to the table's
1869
+ * internal store, which means calling it during a parent's render
1870
+ * synchronously cascades a state change into the child filter menu
1871
+ * that's about to render — React 19 surfaces that as "Cannot update a
1872
+ * component while rendering a different component". The reset moves to
1873
+ * a `useEffect` below so the column filters are cleared after commit.
1874
+ */
1875
+ } else if (trackedInitialPageSize !== initialPageSize) {
1876
+ setTrackedInitialPageSize(initialPageSize);
1877
+ setPagination({ pageIndex: 0, pageSize: initialPageSize });
1878
+ } else if (
1879
+ trackedDebouncedSearch !== debouncedSearch
1880
+ || trackedColumnFilters !== columnFilters
1881
+ || trackedSorting !== liveSorting
1882
+ || trackedBaseFilterKey !== baseFilterKey
1883
+ || trackedPivotFilterKey !== pivotFilterKey
1884
+ ) {
1885
+ setTrackedDebouncedSearch(debouncedSearch);
1886
+ setTrackedColumnFilters(columnFilters);
1887
+ setTrackedSorting(liveSorting);
1888
+ setTrackedBaseFilterKey(baseFilterKey);
1889
+ setTrackedPivotFilterKey(pivotFilterKey);
1890
+ if (pagination.pageIndex !== 0) {
1891
+ setPagination(prev => ({ ...prev, pageIndex: 0 }));
1892
+ }
1893
+ }
1894
+
1895
+ /*
1896
+ * Saved-view switch → clear toolbar / column filters from the previous
1897
+ * view. Lives in an effect (instead of being wired into the render-time
1898
+ * tracker above) so the setter fires after commit; otherwise the cascade
1899
+ * into the table store happens while a descendant (filter menu) is mid-
1900
+ * render. `trackedActiveViewId` is the post-update sentinel, so this
1901
+ * effect runs exactly once per view change.
1902
+ */
1903
+ const columnFiltersLengthRef = useRef(columnFilters.length);
1904
+
1905
+ columnFiltersLengthRef.current = columnFilters.length;
1906
+
1907
+ useEffect(() => {
1908
+ if (columnFiltersLengthRef.current === 0) return undefined;
1909
+
1910
+ const timeout = window.setTimeout(() => {
1911
+ setColumnFilters([]);
1912
+ }, 0);
1913
+
1914
+ return () => window.clearTimeout(timeout);
1915
+ }, [trackedActiveViewId]);
1916
+
1917
+ useEffect(() => {
1918
+ const timeout = window.setTimeout(() => {
1919
+ setDebouncedSearch(searchInput);
1920
+ }, searchDebounceMs);
1921
+
1922
+ return () => window.clearTimeout(timeout);
1923
+ }, [searchInput, searchDebounceMs]);
1924
+
1925
+ const groupingRequiredSlugs = useMemo<Array<string>>(() => {
1926
+ const fromView = activeView?.grouping ?? [];
1927
+
1928
+ if (fromView.length > 0) return fromView;
1929
+ if (defaultRowGroupingColumn) return [defaultRowGroupingColumn];
1930
+
1931
+ return [];
1932
+ }, [activeView, defaultRowGroupingColumn]);
1933
+
1934
+ /*
1935
+ * Side-panel filter state. `useDataTableSideFilters` is a thin wrapper
1936
+ * around `useDataTableFilters` that emits a `RuleGroupType` whenever the
1937
+ * underlying `FiltersState` changes — we feed that rule group through
1938
+ * `buildFiltersParam` (alongside the saved view filter and toolbar
1939
+ * filter rules) so the items request stays in sync. The hook is always
1940
+ * called (Rules of Hooks), but with an empty `columnsConfig` when the
1941
+ * consumer hasn't enabled the side panel.
1942
+ */
1943
+ const sideFiltersColumnsConfig = useMemo(
1944
+ () => sideFiltersConfig?.columnsConfig ?? ([] as ReadonlyArray<ColumnConfig<TData, any, any, any>>),
1945
+ [sideFiltersConfig?.columnsConfig]
1946
+ );
1947
+ const sideFiltersStrategy: FilterStrategy = sideFiltersConfig?.strategy ?? 'server';
1948
+ const [sideFiltersQuery, setSideFiltersQuery] = useState<RuleGroupType | undefined>(undefined);
1949
+ const sideFilterDtf = useDataTableSideFilters<TData, ReadonlyArray<ColumnConfig<TData, any, any, any>>, FilterStrategy>({
1950
+ columnsConfig: sideFiltersColumnsConfig,
1951
+ strategy: sideFiltersStrategy,
1952
+ data: [],
1953
+ defaults: sideFiltersConfig?.defaults,
1954
+ sections: sideFiltersConfig?.sections,
1955
+ onQueryChange: setSideFiltersQuery
1956
+ });
1957
+ const sideFiltersActiveQuery = enableSideFilters ? sideFiltersQuery : undefined;
1958
+
1959
+ const [internalSideFiltersExpanded, setInternalSideFiltersExpanded] = useState<boolean>(sideFiltersDefaultExpanded);
1960
+ const isSideFiltersControlled = sideFiltersExpandedProp !== undefined;
1961
+ const sideFiltersExpanded = isSideFiltersControlled ? sideFiltersExpandedProp ?? false : internalSideFiltersExpanded;
1962
+
1963
+ const setSideFiltersExpanded = useCallback((next: boolean) => {
1964
+ if (!isSideFiltersControlled) setInternalSideFiltersExpanded(next);
1965
+ onSideFiltersExpandedChange?.(next);
1966
+ }, [isSideFiltersControlled, onSideFiltersExpandedChange]);
1967
+
1968
+ /*
1969
+ * `externalFilterChain` is the filter chain WITHOUT the pivot's own rule —
1970
+ * fed back into `<KivaPivotFilterGroup activeFilters>` so the pill
1971
+ * counts cross-react when the user adds toolbar / side / saved-view
1972
+ * filtering (without recursing on the pivot's own selection).
1973
+ */
1974
+ const externalFilterChain = useMemo(
1975
+ () => buildFiltersParam(
1976
+ activeView?.filterQuery,
1977
+ columnFilters,
1978
+ sideFiltersActiveQuery,
1979
+ undefined,
1980
+ relationFilterFieldMap,
1981
+ filterableRelationColumnIds
1982
+ ),
1983
+ [
1984
+ activeView?.filterQuery,
1985
+ columnFilters,
1986
+ sideFiltersActiveQuery,
1987
+ relationFilterFieldMap,
1988
+ filterableRelationColumnIds
1989
+ ]
1990
+ );
1991
+
1992
+ const resolvedListParams = useMemo<KivaDataGridListParams>(
1993
+ () => buildListParams({
1994
+ fields: dataSource?.fields,
1995
+ view: activeView,
1996
+ filterKeyword: debouncedSearch.trim() || undefined,
1997
+ defaultLimit,
1998
+ override: listParams,
1999
+ requiredSlugs: groupingRequiredSlugs,
2000
+ pagination: isStandardPaging ? pagination : undefined,
2001
+ toolbarFilters: columnFilters,
2002
+ sideFilters: sideFiltersActiveQuery,
2003
+ pivotRules: pivotFilterRule,
2004
+ liveSorting,
2005
+ relationIconFields,
2006
+ relationColumnIds: visibleRelationColumnIds,
2007
+ relationFilterFieldMap,
2008
+ filterableRelationColumnIds
2009
+ }),
2010
+ [
2011
+ dataSource?.fields,
2012
+ activeView,
2013
+ debouncedSearch,
2014
+ defaultLimit,
2015
+ listParams,
2016
+ groupingRequiredSlugs,
2017
+ isStandardPaging,
2018
+ pagination,
2019
+ columnFilters,
2020
+ sideFiltersActiveQuery,
2021
+ pivotFilterRule,
2022
+ liveSorting,
2023
+ relationIconFields,
2024
+ visibleRelationColumnIds,
2025
+ relationFilterFieldMap,
2026
+ filterableRelationColumnIds
2027
+ ]
2028
+ );
2029
+
2030
+ const itemsKey = useMemo(
2031
+ () => [
2032
+ 'kiva',
2033
+ 'kivaDataGridItems',
2034
+ viewSelectOptions.appSlug,
2035
+ viewSelectOptions.dataSourceSlug,
2036
+ collection ? 'collection' : 'direct',
2037
+ resolvedListParams
2038
+ ] as const,
2039
+ [
2040
+ viewSelectOptions.appSlug,
2041
+ viewSelectOptions.dataSourceSlug,
2042
+ collection,
2043
+ resolvedListParams
2044
+ ]
2045
+ );
2046
+
2047
+ /*
2048
+ * Gate the items query on the view metadata being fully ready so we don't
2049
+ * fire one request with all columns and a second with the active view's
2050
+ * whitelist. Specifically wait for:
2051
+ * - the data source + views queries to settle (so `dataSource.fields` and
2052
+ * `views` are populated, which feeds `resolvedListParams`),
2053
+ * - if any views exist, an `activeViewId` to be picked (the resolution
2054
+ * runs in a useEffect inside `useKivaDataViewSelect`).
2055
+ */
2056
+ const viewMetadataReady
2057
+ = !viewSelect.isLoading
2058
+ && (views.length === 0 || Boolean(activeViewId));
2059
+
2060
+ const itemsQuery = useQuery<{ items: Array<TData>; total: number | undefined }>({
2061
+ queryKey: itemsKey,
2062
+ queryFn: async () => {
2063
+ const response = collection ? await collection.list(resolvedListParams) : await fetchItemsWithColumnRecovery(
2064
+ viewSelectOptions.client,
2065
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items`,
2066
+ resolvedListParams
2067
+ );
2068
+
2069
+ return {
2070
+ items: unwrapItems<TData>(response),
2071
+ total: unwrapTotal(response)
2072
+ };
2073
+ },
2074
+ enabled: providedData === undefined
2075
+ && enableItemsQuery
2076
+ && Boolean(viewSelectOptions.appSlug)
2077
+ && Boolean(viewSelectOptions.dataSourceSlug)
2078
+ && viewMetadataReady,
2079
+ staleTime: viewSelectOptions.staleTime ?? 30_000,
2080
+ /*
2081
+ * Keep the previous page's payload (including `meta.total`) on screen
2082
+ * while the next page is in flight. Without this, switching pages
2083
+ * blanks `data` for the new query key — `rowCount` reverts to
2084
+ * `undefined`, and TanStack's manual-pagination fallback computes
2085
+ * `getPageCount()` from `data.length` plus the current `pageIndex`,
2086
+ * yielding bogus values like "2 pages" until the new response lands.
2087
+ * `keepPreviousData` makes the transition smooth: total stays at
2088
+ * `meta.total`, page count stays at `ceil(total / pageSize)`, and
2089
+ * the visible rows swap when the fetch resolves.
2090
+ */
2091
+ placeholderData: keepPreviousData
2092
+ });
2093
+
2094
+ itemsRefetchRef.current = itemsQuery.refetch as () => Promise<unknown>;
2095
+
2096
+ /*
2097
+ * Resolved row set passed into TanStack. With standard paging on local
2098
+ * data we slice ourselves so `manualPagination` sees only the current
2099
+ * page (groups then form within the visible window — same trade-off as
2100
+ * server paging). With virtual-scroll mode or no paging, hand the rows
2101
+ * straight through.
2102
+ */
2103
+ const items = useMemo<Array<TData>>(() => {
2104
+ if (providedData) {
2105
+ if (isStandardPaging) {
2106
+ const start = pagination.pageIndex * pagination.pageSize;
2107
+
2108
+ return providedData.slice(start, start + pagination.pageSize);
2109
+ }
2110
+
2111
+ return providedData;
2112
+ }
2113
+
2114
+ return itemsQuery.data?.items ?? [];
2115
+ }, [
2116
+ providedData,
2117
+ itemsQuery.data,
2118
+ isStandardPaging,
2119
+ pagination.pageIndex,
2120
+ pagination.pageSize
2121
+ ]);
2122
+
2123
+ /*
2124
+ * `rowCount` for the table:
2125
+ * - Local + standard paging: full data length (we sliced for `items`).
2126
+ * - Remote + standard paging: `meta.total` from the server (only
2127
+ * populated when `fullCount: true` was sent — handled in
2128
+ * `buildListParams`).
2129
+ * - Virtual-scroll: leave undefined; TanStack falls back to data length.
2130
+ */
2131
+ const rowCount = useMemo<number | undefined>(() => {
2132
+ if (!isStandardPaging) return undefined;
2133
+ if (providedData) return providedData.length;
2134
+
2135
+ return itemsQuery.data?.total;
2136
+ }, [isStandardPaging, providedData, itemsQuery.data]);
2137
+
2138
+ const reload = useCallback(() => {
2139
+ refetchViewSelect();
2140
+ if (providedData === undefined) {
2141
+ void itemsQuery.refetch();
2142
+ }
2143
+ onReload?.();
2144
+ }, [
2145
+ refetchViewSelect,
2146
+ itemsQuery,
2147
+ providedData,
2148
+ onReload
2149
+ ]);
2150
+
2151
+ /**
2152
+ * Toolbar reload — refetches records only. Keeps the data source
2153
+ * metadata + views queries intact so a routine refresh doesn't pay for
2154
+ * a full schema reload. Use `reload` when you need everything.
2155
+ */
2156
+ const reloadItems = useCallback(() => {
2157
+ if (providedData === undefined) {
2158
+ void itemsQuery.refetch();
2159
+ }
2160
+ onReload?.();
2161
+ }, [itemsQuery, providedData, onReload]);
2162
+
2163
+ /*
2164
+ * The record number is editable only where the data source's metadata says
2165
+ * so. Read for every view, not only those that edit cells: the view editor
2166
+ * shows the lock when inline editing is being turned on.
2167
+ */
2168
+ const autonumberEditable = isAutonumberEditable(dataSource);
2169
+
2170
+ /*
2171
+ * Forced read-only set: identity / autonumber columns and fields that
2172
+ * the data source itself flags as `readOnly: true`. These can NEVER be
2173
+ * toggled editable from the view editor — the editor's inline-editing
2174
+ * section reads `meta.forcedReadOnly` through `buildDraftColumns` and
2175
+ * renders the row as locked. The one exception is the record number when
2176
+ * its data source allows setting it by hand.
2177
+ */
2178
+ const forcedReadOnlySlugs = useMemo<Set<string>>(() => {
2179
+ const set = new Set<string>(['id', AUTONUMBER_FIELD_SLUG]);
2180
+
2181
+ for (const field of dataSource?.fields ?? []) {
2182
+ const fieldRecord = field as Record<string, unknown>;
2183
+
2184
+ if (field.slug === 'id' || field.slug === AUTONUMBER_FIELD_SLUG) {
2185
+ set.add(field.slug);
2186
+ }
2187
+
2188
+ if (fieldRecord.readOnly === true || fieldRecord.read_only === true) {
2189
+ set.add(field.slug);
2190
+ }
2191
+
2192
+ const fieldType = typeof fieldRecord.type === 'string' ? fieldRecord.type : '';
2193
+
2194
+ if (fieldType === 'field-autonumber' || fieldType === 'field-identity') {
2195
+ set.add(field.slug);
2196
+ }
2197
+ }
2198
+
2199
+ if (autonumberEditable) set.delete(AUTONUMBER_FIELD_SLUG);
2200
+
2201
+ return set;
2202
+ }, [dataSource?.fields, autonumberEditable]);
2203
+
2204
+ /*
2205
+ * Combined "column is read-only at runtime" set: forced + the user's
2206
+ * per-view choice. The cell render path uses this; the editor reads
2207
+ * forced and user lists separately.
2208
+ */
2209
+ const effectiveReadOnlySlugs = useMemo<Set<string>>(() => {
2210
+ const set = new Set<string>(forcedReadOnlySlugs);
2211
+
2212
+ for (const slug of activeView?.readOnlyColumns ?? []) {
2213
+ set.add(slug);
2214
+ }
2215
+
2216
+ return set;
2217
+ }, [forcedReadOnlySlugs, activeView?.readOnlyColumns]);
2218
+
2219
+ /*
2220
+ * Per-column runtime overrides toggled from the column header dropdown
2221
+ * (e.g. relation `showAutonumber`). Hydrated from the active saved view
2222
+ * via `applyViewToTable` → `onColumnOptionsReset`, captured back into the
2223
+ * next view through `captureViewSnapshot`. The map is merged into each
2224
+ * column's `meta.cell` below so cells stay backed by a single source of
2225
+ * truth and re-render when the user flips a toggle.
2226
+ */
2227
+ const [columnOptions, setColumnOptions] = useState<Record<string, DataGridColumnOptions>>({});
2228
+
2229
+ const onColumnOptionsChange = useCallback(
2230
+ (
2231
+ columnId: string,
2232
+ updater: (prev: DataGridColumnOptions | undefined) => DataGridColumnOptions
2233
+ ) => {
2234
+ setColumnOptions((prev) => {
2235
+ const nextEntry = updater(prev[columnId]);
2236
+ const hasMeaningfulValue = Object.values(nextEntry).some(value => value !== undefined);
2237
+ let next: Record<string, DataGridColumnOptions>;
2238
+
2239
+ if (!hasMeaningfulValue) {
2240
+ if (!(columnId in prev)) {
2241
+ next = prev;
2242
+ } else {
2243
+ next = { ...prev };
2244
+ delete next[columnId];
2245
+ }
2246
+ } else {
2247
+ next = { ...prev, [columnId]: nextEntry };
2248
+ }
2249
+
2250
+ return next;
2251
+ });
2252
+ },
2253
+ []
2254
+ );
2255
+
2256
+ const onColumnOptionsReset = useCallback(
2257
+ (next: Record<string, DataGridColumnOptions>) => {
2258
+ setColumnOptions(next);
2259
+ },
2260
+ []
2261
+ );
2262
+
2263
+ const columns = useMemo<Array<ColumnDef<TData>>>(() => {
2264
+ /*
2265
+ * Some Kiva data sources contain duplicate-slug fields (typically a
2266
+ * legacy artefact — e.g. `base/task` ships two `section` fields). Each
2267
+ * duplicate would produce a TanStack column with the same `id`, and the
2268
+ * table renders cell trees with `${rowId}_${columnId}` keys — so two
2269
+ * cells per row collide on `11_section`, `12_section`, etc. Dedupe by
2270
+ * slug here, keeping the first occurrence, before building columns.
2271
+ */
2272
+ const seenSlugs = new Set<string>();
2273
+ const uniqueFields = (dataSource?.fields ?? []).filter((field) => {
2274
+ if (seenSlugs.has(field.slug)) return false;
2275
+ seenSlugs.add(field.slug);
2276
+
2277
+ return true;
2278
+ });
2279
+
2280
+ /*
2281
+ * The label field (the record's title — e.g. `subject` on base/task) is the
2282
+ * data source's display field, and the API deliberately omits it from
2283
+ * `fields`. The metadata grid only builds columns from `fields`, so the
2284
+ * label column never existed: it was missing from the Fields menu and could
2285
+ * not be added to the table. Synthesize a column field for it (ahead of the
2286
+ * real fields) when the data source exposes a `labelField` not already in
2287
+ * `fields`. `labelField` is outside the typed `DataSource` shape, so read it
2288
+ * through the index signature and normalise the required column props.
2289
+ */
2290
+ const labelField = dataSource?.labelField as
2291
+ | {
2292
+ id?: string;
2293
+ slug?: string;
2294
+ type?: string;
2295
+ name?: string;
2296
+ }
2297
+ | undefined;
2298
+
2299
+ if (labelField?.slug && !seenSlugs.has(labelField.slug)) {
2300
+ const labelSlug = labelField.slug;
2301
+
2302
+ uniqueFields.unshift({
2303
+ id: labelField.id ?? labelSlug,
2304
+ /*
2305
+ * The API doesn't send a `name` for the label field, so humanise the
2306
+ * slug for the column header: `subject` → `Subject`, `start_date` →
2307
+ * `Start Date`.
2308
+ */
2309
+ name: labelField.name
2310
+ ?? labelSlug
2311
+ .replace(/[_-]+/g, ' ')
2312
+ .replace(/(?:^|\s)\S/g, char => char.toUpperCase()),
2313
+ slug: labelSlug,
2314
+ type: labelField.type ?? 'field-text'
2315
+ });
2316
+ seenSlugs.add(labelSlug);
2317
+ }
2318
+
2319
+ const fieldColumns = uniqueFields
2320
+ .map((field) => {
2321
+ /*
2322
+ * Translate enum option labels at the FIELD level (a cloned field with
2323
+ * remapped `enums[].name`) before the column is built. Because the
2324
+ * cell options, the filter-menu options, and the row-group value
2325
+ * renderer all derive from the field's `enums`, this single point
2326
+ * keeps every enum surface consistent.
2327
+ */
2328
+ const columnField = dynamicEnumOptionTranslator ? translateFieldEnumOptions(field, dynamicEnumOptionTranslator) : field;
2329
+
2330
+ const defaultColumn = buildTanstackColumnDef<TData>({
2331
+ field: columnField,
2332
+ appSlug: viewSelectOptions.appSlug,
2333
+ dataSourceSlug: viewSelectOptions.dataSourceSlug,
2334
+ users
2335
+ });
2336
+
2337
+ const rawColumn = mapColumn ? mapColumn(field, defaultColumn) : defaultColumn;
2338
+
2339
+ if (!rawColumn) return null;
2340
+
2341
+ /*
2342
+ * Translate the header + `meta.label` before rendering so consumers can
2343
+ * remap column titles from their own i18n dictionaries. Only string
2344
+ * headers are translated — a custom `header` render function is left
2345
+ * untouched so consumer JSX isn't clobbered.
2346
+ */
2347
+ const mapped = dynamicLabelTranslator ? translateColumnHeader(rawColumn, dynamicLabelTranslator) : rawColumn;
2348
+
2349
+ /*
2350
+ * Stamp `meta.readOnly` (runtime: row uses this to gate editing)
2351
+ * and `meta.forcedReadOnly` (structural: editor uses this to
2352
+ * render the toggle as locked) AFTER `mapColumn` so caller
2353
+ * overrides can't accidentally drop the protection on identity /
2354
+ * metadata-locked fields. The merge preserves any other meta
2355
+ * properties the consumer set.
2356
+ */
2357
+ const isForced = forcedReadOnlySlugs.has(field.slug);
2358
+ const isReadOnly = effectiveReadOnlySlugs.has(field.slug);
2359
+ const override = columnOptions[field.slug];
2360
+ const cellMeta = mapped.meta?.cell;
2361
+ const iconFieldSlug = relationIconFields?.[field.slug];
2362
+ const needsRelationOverride
2363
+ = cellMeta?.variant === 'relation'
2364
+ && (
2365
+ (override?.showAutonumber !== undefined
2366
+ && override.showAutonumber !== cellMeta.showAutonumber)
2367
+ || (typeof iconFieldSlug === 'string'
2368
+ && iconFieldSlug.length > 0
2369
+ && cellMeta.iconField !== iconFieldSlug)
2370
+ );
2371
+
2372
+ if (!isReadOnly && !isForced && !needsRelationOverride) return mapped;
2373
+
2374
+ return {
2375
+ ...mapped,
2376
+ meta: {
2377
+ ...mapped.meta,
2378
+ ...(isReadOnly || isForced ? { readOnly: isReadOnly, forcedReadOnly: isForced } : {}),
2379
+ ...(needsRelationOverride && cellMeta?.variant === 'relation' ? {
2380
+ cell: {
2381
+ ...cellMeta,
2382
+ ...(override?.showAutonumber !== undefined ? { showAutonumber: override.showAutonumber } : {}),
2383
+ ...(typeof iconFieldSlug === 'string' && iconFieldSlug.length > 0 ? { iconField: iconFieldSlug } : {})
2384
+ }
2385
+ } : {})
2386
+ }
2387
+ };
2388
+ })
2389
+ .filter((column): column is ColumnDef<TData> => column !== null);
2390
+
2391
+ const resolvedSelectColumn = showSelectColumn ? selectColumn
2392
+ ?? getDataGridSelectColumn<TData>({
2393
+ size: 44,
2394
+ minSize: 44,
2395
+ enableRowMarkers
2396
+ }) : null;
2397
+
2398
+ /*
2399
+ * Columns borrowed from a related data source. The value already rides in
2400
+ * the row the grid fetched (the projection puts it under
2401
+ * `row.<relation>.<field>`), so there is no extra request and no loading
2402
+ * state of its own.
2403
+ *
2404
+ * Read-only on purpose: an editable cell here would write to a different
2405
+ * record than the row represents. `meta.readOnly` is the lever every cell
2406
+ * variant honours — pinning the column to a text cell would be the wrong
2407
+ * one, and MEASURED it printed a borrowed date as
2408
+ * `2025-02-11T09:00:24.669098` and a borrowed money field as `300000`.
2409
+ *
2410
+ * `meta.group` is what lets the field picker separate these from the grid's
2411
+ * own fields. It is keyed on the RELATION FIELD, not on the data source the
2412
+ * value comes from: several relation fields can reach the same target, so a
2413
+ * group titled after the target would appear several times over.
2414
+ */
2415
+ const relationPathColumns: Array<ColumnDef<TData>> = relationColumnSpecs
2416
+ .map((entry) => {
2417
+ const parsed = parseRelationColumnId(entry.id);
2418
+
2419
+ if (!parsed) return null;
2420
+
2421
+ /*
2422
+ * The variant the FILTER menu types the column by, kept apart from the
2423
+ * `cell.variant` it RENDERS with: the two answer different questions —
2424
+ * which operators are honest, versus how the value reads. `null` means
2425
+ * this target type cannot be filtered honestly at all (an option-valued
2426
+ * target stores an id while the cell shows a label, so the filter would
2427
+ * compare a label against a uuid column and return zero rows with HTTP
2428
+ * 200), and `meta.filterable: false` is what suppresses it.
2429
+ */
2430
+ const filterVariant = resolveRelationFilterVariant(entry.fieldType);
2431
+
2432
+ /*
2433
+ * `getCellOpts` is the SAME map the grid's own columns go through, so a
2434
+ * borrowed date and a native one cannot drift apart. Option-, user- and
2435
+ * record-valued targets never reach it: they keep the label path,
2436
+ * because a typed variant would render blank where the label formatter
2437
+ * reads `{ id, name }`.
2438
+ */
2439
+ const cellOpts = isLabelResolvedRelationTarget(entry.fieldType) ? { variant: 'short-text' as const } : resolveRelationCellOpts(entry.fieldType, () => getCellOpts(
2440
+ { slug: entry.fieldSlug, name: entry.fieldLabel, type: entry.fieldType },
2441
+ {
2442
+ appSlug: viewSelectOptions.appSlug,
2443
+ dataSourceSlug: viewSelectOptions.dataSourceSlug,
2444
+ users
2445
+ }
2446
+ ));
2447
+
2448
+ /*
2449
+ * Derived from the variant we actually landed on, not from the type
2450
+ * list, so it covers BOTH ways a column ends up as text: a
2451
+ * label-resolved target, and a type `getCellOpts` does not map (it
2452
+ * defaults those to `short-text` too). Anything else got a cell chosen
2453
+ * FOR that field type, and such a cell must receive the STORED value.
2454
+ */
2455
+ const labelResolved = cellOpts.variant === 'short-text';
2456
+ const resolveUserIds = USER_VALUED_RELATION_TARGET_TYPES.has(entry.fieldType);
2457
+
2458
+ return {
2459
+ id: entry.id,
2460
+ accessorFn: (row: unknown) => readRelationCellDisplayValue(
2461
+ row,
2462
+ parsed.relationSlug,
2463
+ parsed.fieldSlug,
2464
+ { users: relationCellUsers, labelResolved, resolveUserIds }
2465
+ ),
2466
+ header: entry.label,
2467
+ enableSorting: true,
2468
+ enableColumnFilter: filterVariant !== null,
2469
+ meta: {
2470
+ label: entry.label,
2471
+ group: entry.group,
2472
+ groupable: false,
2473
+ readOnly: true,
2474
+ filterable: filterVariant !== null,
2475
+ ...(filterVariant ? { filterVariant } : {}),
2476
+ cell: cellOpts
2477
+ }
2478
+ } as ColumnDef<TData>;
2479
+ })
2480
+ .filter((column): column is ColumnDef<TData> => column !== null);
2481
+
2482
+ return [
2483
+ ...(resolvedSelectColumn ? [resolvedSelectColumn] : []),
2484
+ ...(actionsColumn ? [actionsColumn] : []),
2485
+ ...(extraColumns ?? []),
2486
+ ...fieldColumns,
2487
+ ...relationPathColumns
2488
+ ];
2489
+ }, [
2490
+ relationColumnSpecs,
2491
+ relationCellUsers,
2492
+ dataSource?.fields,
2493
+ dataSource?.labelField,
2494
+ extraColumns,
2495
+ mapColumn,
2496
+ dynamicLabelTranslator,
2497
+ dynamicEnumOptionTranslator,
2498
+ showSelectColumn,
2499
+ enableRowMarkers,
2500
+ selectColumn,
2501
+ actionsColumn,
2502
+ forcedReadOnlySlugs,
2503
+ effectiveReadOnlySlugs,
2504
+ columnOptions,
2505
+ viewSelectOptions.appSlug,
2506
+ viewSelectOptions.dataSourceSlug,
2507
+ users,
2508
+ relationIconFields
2509
+ ]);
2510
+
2511
+ /*
2512
+ * Only a view-driven or host-opted 'standard' mode is surfaced; the implicit
2513
+ * virtual-scroll default stays `undefined` so `<DataGrid>` keeps its own
2514
+ * default exactly as before.
2515
+ */
2516
+ const viewPagingMode = viewDrivenPagingMode !== undefined || defaultPagingMode === 'standard' ? resolvedPagingMode : undefined;
2517
+
2518
+ /*
2519
+ * Default save-changes handler: collect every changed row's full snapshot
2520
+ * (post-edit) into a single bulk PATCH. Per the bulk endpoint docs, the
2521
+ * inline-edit path keeps automation + change-logging *off* to stay within
2522
+ * request budgets — re-enable explicitly via `onSaveChanges` if needed.
2523
+ */
2524
+ const defaultSaveChanges = useCallback(
2525
+ async (changes: Array<RowChange>, data: Array<TData>): Promise<void> => {
2526
+ if (changes.length === 0) return;
2527
+
2528
+ /*
2529
+ * Only the edited cells go out, each row with its own. A grid row also
2530
+ * carries read-only and system columns the API refuses to write, and
2531
+ * `data` keeps the values from before the edit unless the caller tracks
2532
+ * `onDataChange`, so each value comes from the change itself. A row never
2533
+ * re-sends a value it did not edit, which could undo a change made since
2534
+ * the load (someone else's renumbering, say); the bulk update writes each
2535
+ * record by its own fields. An emptied record number is left out, as in
2536
+ * the form: a number can be replaced, not removed.
2537
+ */
2538
+ const records: Array<{ id: string } & Record<string, unknown>> = [];
2539
+
2540
+ for (const change of changes) {
2541
+ const row = data[change.rowIndex] as Record<string, unknown> | undefined;
2542
+ const id = row?.id;
2543
+
2544
+ if (typeof id !== 'string' || id.length === 0) continue;
2545
+
2546
+ const record: { id: string } & Record<string, unknown> = { id };
2547
+
2548
+ for (const [column, edited] of change.changes) {
2549
+ const emptiedNumber = column === AUTONUMBER_FIELD_SLUG && (edited.newValue === null || edited.newValue === undefined || edited.newValue === '');
2550
+
2551
+ if (!emptiedNumber) record[column] = edited.newValue;
2552
+ }
2553
+
2554
+ if (Object.keys(record).length > 1) records.push(record);
2555
+ }
2556
+
2557
+ if (records.length === 0) return;
2558
+
2559
+ const body = { records };
2560
+
2561
+ if (collection?.updateMany) {
2562
+ await collection.updateMany(body);
2563
+ } else {
2564
+ await viewSelectOptions.client.patch(
2565
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items/bulk`,
2566
+ body
2567
+ );
2568
+ }
2569
+ },
2570
+ [
2571
+ collection,
2572
+ viewSelectOptions.client,
2573
+ viewSelectOptions.appSlug,
2574
+ viewSelectOptions.dataSourceSlug
2575
+ ]
2576
+ );
2577
+
2578
+ const handleChangesSave = useCallback(
2579
+ async (changes: Array<RowChange>, data: Array<TData>): Promise<void> => {
2580
+ if (onSaveChanges) {
2581
+ await onSaveChanges(changes, data);
2582
+ } else {
2583
+ await defaultSaveChanges(changes, data);
2584
+ }
2585
+
2586
+ if (providedData === undefined) {
2587
+ void itemsRefetchRef.current?.();
2588
+ }
2589
+ },
2590
+ [onSaveChanges, defaultSaveChanges, providedData]
2591
+ );
2592
+
2593
+ /*
2594
+ * Inline-editing flips the table out of read-only mode when the active
2595
+ * view says so. It also force-enables change tracking — there's no
2596
+ * sensible way to surface in-flight edits to the user without a save /
2597
+ * discard banner, so we ignore a `trackChanges: false` override in this
2598
+ * mode (per the spec: "always use trackChanges when cell editing is
2599
+ * active").
2600
+ */
2601
+ const inlineEditingEnabled = activeView?.inlineEditingEnabled === true;
2602
+ const effectiveReadOnly = readOnly && !inlineEditingEnabled;
2603
+ const effectiveTrackChanges = inlineEditingEnabled ? true : trackChanges;
2604
+
2605
+ /*
2606
+ * Writes a status change to the server's `status-update` endpoint.
2607
+ *
2608
+ * A status change is not an ordinary cell write: the sub-status, note and
2609
+ * follow-up date live in a separate activity record, not on the row. The
2610
+ * hook is therefore only defined when a real Kiva data source is bound;
2611
+ * grids fed with local `data` leave it undefined and the status cell behaves
2612
+ * like a plain select. The cell still writes the value through
2613
+ * `onDataUpdate` — the endpoint only logs the activity, it does not update
2614
+ * the record (see `createStatusUpdateActivity` in kiva-core).
2615
+ */
2616
+ const statusUpdateEnabled = Boolean(
2617
+ dataSource?.id && viewSelectOptions.appSlug && viewSelectOptions.dataSourceSlug && !providedData
2618
+ );
2619
+
2620
+ const onStatusUpdate = useCallback(
2621
+ async (input: {
2622
+ rowIndex: number;
2623
+ columnId: string;
2624
+ value: string;
2625
+ secondaryValue?: string;
2626
+ description?: string;
2627
+ followupDate?: string;
2628
+ }) => {
2629
+ const record = items[input.rowIndex] as Record<string, unknown> | undefined;
2630
+ const recordId = record?.id;
2631
+
2632
+ if (typeof recordId !== 'string') return;
2633
+
2634
+ await viewSelectOptions.client.post(
2635
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/status-update/${encodeURIComponent(input.columnId)}`,
2636
+ {
2637
+ recordId,
2638
+ value: input.value,
2639
+ secondaryValue: input.secondaryValue ?? null,
2640
+ description: input.description ?? null,
2641
+ followupDate: input.followupDate ?? null
2642
+ }
2643
+ );
2644
+
2645
+ reload();
2646
+ },
2647
+ [
2648
+ items,
2649
+ viewSelectOptions.client,
2650
+ viewSelectOptions.appSlug,
2651
+ viewSelectOptions.dataSourceSlug,
2652
+ reload
2653
+ ]
2654
+ );
2655
+
2656
+ const {
2657
+ table,
2658
+ selectedRows,
2659
+ selectedRowCount,
2660
+ ...gridProps
2661
+ } = useDataGrid<TData>({
2662
+ data: items,
2663
+ columns,
2664
+ readOnly: effectiveReadOnly,
2665
+ enableSearch,
2666
+ enableGrouping,
2667
+ enableChangeTracking: effectiveTrackChanges,
2668
+ onChangesSave: handleChangesSave,
2669
+ pagingMode: viewPagingMode,
2670
+ pageSize: pagination.pageSize,
2671
+ rowColorRules,
2672
+ cellColorRules,
2673
+ getRowLabel,
2674
+ onRowAdd,
2675
+ onRowsAdd,
2676
+ onRowsDelete,
2677
+ onDataChange,
2678
+ enablePaste,
2679
+ initialState,
2680
+ ...(getRowId ? { getRowId } : {}),
2681
+ /*
2682
+ * Standard paging → manual pagination. TanStack stops slicing client-
2683
+ * side (so group rows can't inflate the page count), our query drives
2684
+ * the data, and the footer reads `getRowCount()` / `getPageCount()`
2685
+ * from the values we feed below.
2686
+ */
2687
+ manualPagination: isStandardPaging,
2688
+ rowCount,
2689
+ manualFiltering: providedData === undefined,
2690
+ state: { pagination, columnFilters },
2691
+ onPaginationChange: setPagination,
2692
+ onColumnFiltersChange: deferredSetColumnFilters,
2693
+ /*
2694
+ * Mirror the table's live sorting into hook state so it can drive the
2695
+ * server query's `orderBy` (see `liveSorting` + `buildListParams`). Fires
2696
+ * for column-header dropdown sorts, the Sort menu, and `applyViewToTable`
2697
+ * on a view switch.
2698
+ */
2699
+ onSortingChange: setLiveSorting,
2700
+ meta: {
2701
+ ...metaOverrides,
2702
+ ...(effectiveFormatDate ? { formatDate: effectiveFormatDate } : {}),
2703
+ ...(effectiveFormatDateTime ? { formatDateTime: effectiveFormatDateTime } : {}),
2704
+ ...(effectiveFormatNumber ? { formatNumber: effectiveFormatNumber } : {}),
2705
+ ...(getRelationHref ? { getRelationHref } : {}),
2706
+ ...(onOpenRelation ? { onOpenRelation } : {}),
2707
+ ...(viewSelectOptions.client ? { emailClient: viewSelectOptions.client } : {}),
2708
+ ...(viewSelectOptions.client ? { messageClient: viewSelectOptions.client } : {}),
2709
+ loadCellOptions: async (column, params) => {
2710
+ const config = getAsyncOptions(column);
2711
+
2712
+ if (!config) return { items: [], hasMore: false };
2713
+
2714
+ return config.load(params);
2715
+ },
2716
+ columnOptions,
2717
+ onColumnOptionsChange,
2718
+ onColumnOptionsReset,
2719
+ enableColumnReorder,
2720
+ showDropdownChevron,
2721
+ ...(statusUpdateEnabled ? { onStatusUpdate } : {})
2722
+ }
2723
+ });
2724
+
2725
+ useEffect(() => {
2726
+ if (providedData === undefined) return;
2727
+ table.setGlobalFilter(debouncedSearch || undefined);
2728
+ }, [debouncedSearch, providedData, table]);
2729
+
2730
+ /*
2731
+ * Apply the active view's full configuration (visibility, order, sort,
2732
+ * filters, color rules, paging, …) to the table whenever the active view
2733
+ * changes, including on initial mount AND when the same view's contents
2734
+ * change (e.g. the user saves new paging in the editor — the views query
2735
+ * refetches, `activeView` becomes a new object reference with the updated
2736
+ * fields, and we need to re-push the config to the table). The dep array
2737
+ * watches `activeView` directly so a same-id-but-different-content
2738
+ * refresh re-runs the effect.
2739
+ */
2740
+ useEffect(() => {
2741
+ if (!activeView) return;
2742
+ if (!dataSource?.fields || dataSource.fields.length === 0) return;
2743
+
2744
+ applyViewToTable(table, activeView);
2745
+
2746
+ const view = activeView;
2747
+
2748
+ /*
2749
+ * Force the active row-grouping column to stay visible even if the user
2750
+ * excluded it from the view — otherwise grouping silently breaks because
2751
+ * the column isn't part of the table's leaf columns rendered for the row.
2752
+ */
2753
+ const groupingForVisibility: Array<string>
2754
+ = (view.grouping ?? []).length > 0 ? view.grouping ?? [] : defaultRowGroupingColumn ? [defaultRowGroupingColumn] : [];
2755
+ const enhancedVisibility = buildEnhancedVisibility(
2756
+ dataSource.fields,
2757
+ view,
2758
+ groupingForVisibility
2759
+ );
2760
+
2761
+ table.setColumnVisibility(enhancedVisibility);
2762
+
2763
+ /*
2764
+ * Saved views store `columnOrder` with field slugs only (e.g.
2765
+ * `["name","email","phone","industry"]`). When TanStack applies a partial
2766
+ * order it appends unlisted columns at the end, so the row-select and
2767
+ * actions columns drift to the right. Re-pin them at the front.
2768
+ */
2769
+ const reservedIds: Array<string> = [];
2770
+
2771
+ if (showSelectColumn) reservedIds.push('select');
2772
+ if (actionsColumn) reservedIds.push('actions');
2773
+
2774
+ if (reservedIds.length > 0) {
2775
+ const orderFromView = view.columnOrder ?? [];
2776
+
2777
+ table.setColumnOrder([...reservedIds, ...orderFromView.filter(id => !reservedIds.includes(id))]);
2778
+
2779
+ /*
2780
+ * Pin select + actions to the left so they stay visible during
2781
+ * horizontal scroll. Merge into whatever the saved view specified
2782
+ * (so a user's existing pinning preference is preserved) and dedupe.
2783
+ */
2784
+ const viewPinning = view.columnPinning ?? { left: [], right: [] };
2785
+ const left = [...reservedIds, ...(viewPinning.left ?? []).filter(id => !reservedIds.includes(id))];
2786
+ const right = (viewPinning.right ?? []).filter(id => !reservedIds.includes(id));
2787
+
2788
+ table.setColumnPinning({ left, right });
2789
+ }
2790
+
2791
+ /*
2792
+ * If the saved view doesn't already specify a grouping but the consumer
2793
+ * passed `defaultRowGroupingColumn`, seed it as the initial grouping so
2794
+ * users land on a meaningful breakdown. Honors only fields that are
2795
+ * actually present in the data source.
2796
+ */
2797
+ const hasViewGrouping = (view.grouping ?? []).length > 0;
2798
+ const fieldSlugs = new Set(dataSource.fields.map(field => field.slug));
2799
+
2800
+ if (!hasViewGrouping && defaultRowGroupingColumn && fieldSlugs.has(defaultRowGroupingColumn)) {
2801
+ table.setGrouping([defaultRowGroupingColumn]);
2802
+ table.setExpanded(true);
2803
+ }
2804
+ }, [
2805
+ activeView,
2806
+ dataSource?.fields,
2807
+ table,
2808
+ showSelectColumn,
2809
+ actionsColumn,
2810
+ defaultRowGroupingColumn
2811
+ ]);
2812
+
2813
+ /*
2814
+ * `useDataGrid`'s `columnSizeVars` memo only depends on `[table, columnSizing]`,
2815
+ * so it doesn't recompute when the columns array changes. On initial mount
2816
+ * `dataSource.fields` is undefined and our columns are just `[select]`; once
2817
+ * fields load, new field columns are added but their `--col-*-size` CSS
2818
+ * variables are missing from the cached vars, leaving cells with invalid
2819
+ * `width: calc(undefined * 1px)`. Touching `columnSizing` forces the memo to
2820
+ * recompute against the now-complete header list. (Same trick the resize
2821
+ * handle uses, hence why a no-op resize click was "fixing" the layout.)
2822
+ */
2823
+ /*
2824
+ * Depends on a signature of the field slugs, not on the `fields` array
2825
+ * identity. `setColumnSizing` writes a brand-new object every time it runs,
2826
+ * and `useDataGrid`'s row-measuring layout effect depends on
2827
+ * `columnSizing`, so it re-measures the virtualizer, which notifies, which
2828
+ * re-renders. A caller whose `dataSource.fields` array is rebuilt on every
2829
+ * render therefore span the whole grid in an infinite render loop
2830
+ * ("Maximum update depth exceeded"). The signature only changes when the
2831
+ * column set really changes, which is all this poke was ever for.
2832
+ */
2833
+ const fieldSlugsSignature = (dataSource?.fields ?? [])
2834
+ .map(field => field.slug)
2835
+ .join(EXCLUDE_SLUG_KEY_SEPARATOR);
2836
+
2837
+ useEffect(() => {
2838
+ if (fieldSlugsSignature.length === 0) return;
2839
+ table.setColumnSizing(prev => ({ ...prev }));
2840
+ }, [fieldSlugsSignature, table]);
2841
+
2842
+ /*
2843
+ * ── View-parameter persistence ────────────────────────────────────────
2844
+ * Snapshot every manually-edited view parameter and (when `persistState` is
2845
+ * on) save it to session/local storage, keyed per active saved view. Restore
2846
+ * runs once per key — declared AFTER `applyViewToTable` so the persisted
2847
+ * overlay lands on top of the saved view's preset.
2848
+ */
2849
+ const persistStorageKey = useMemo(() => {
2850
+ if (!persistEnabled) return null;
2851
+
2852
+ const dataSourceSegment = persistKeyOverride
2853
+ || `${viewSelectOptions.appSlug}:${viewSelectOptions.dataSourceSlug}`;
2854
+
2855
+ return buildPersistKey([dataSourceSegment, activeViewId ?? 'default']);
2856
+ }, [
2857
+ persistEnabled,
2858
+ persistKeyOverride,
2859
+ viewSelectOptions.appSlug,
2860
+ viewSelectOptions.dataSourceSlug,
2861
+ activeViewId
2862
+ ]);
2863
+
2864
+ const persistReady = persistEnabled && !!dataSource?.fields && dataSource.fields.length > 0;
2865
+
2866
+ const gridTableState = table.getState();
2867
+ const currentRowHeight = table.options.meta?.rowHeight;
2868
+ const currentDisplayMode = table.options.meta?.displayMode;
2869
+
2870
+ /*
2871
+ * Borrowed columns start HIDDEN. TanStack treats a column with no entry in
2872
+ * `columnVisibility` as visible, so without this seeding a data source with a
2873
+ * dozen relations would open with a couple of hundred columns on screen and a
2874
+ * projection asking for every one of them. Only ids the state does not
2875
+ * mention are seeded, so a saved view (or restored session state) that
2876
+ * deliberately turns one on is never overwritten.
2877
+ */
2878
+ useEffect(() => {
2879
+ if (relationColumnSpecs.length === 0) return;
2880
+
2881
+ const missing = relationColumnSpecs.filter(
2882
+ spec => gridTableState.columnVisibility[spec.id] === undefined
2883
+ );
2884
+
2885
+ if (missing.length === 0) return;
2886
+
2887
+ table.setColumnVisibility((current) => {
2888
+ const next = { ...current };
2889
+
2890
+ for (const spec of missing) next[spec.id] = false;
2891
+
2892
+ return next;
2893
+ });
2894
+ }, [relationColumnSpecs, gridTableState.columnVisibility, table]);
2895
+
2896
+ /*
2897
+ * Mirror the borrowed columns the user has turned on out of the table, so the
2898
+ * projection can follow the Fields menu. Compared by value before storing:
2899
+ * `columnVisibility` changes on every toggle of any column, and a fresh array
2900
+ * identity here would rebuild the list params and refetch the grid each time.
2901
+ *
2902
+ * The table owns `columnVisibility` while the projection is built before the
2903
+ * table exists, so this mirror is the seam between the two. Deferred through
2904
+ * a microtask so the store is never written synchronously from the effect
2905
+ * (matching `deferredSetColumnFilters` above); the update still flushes in
2906
+ * the same task tick, so the refetch is not visibly delayed.
2907
+ */
2908
+ useEffect(() => {
2909
+ const next = relationColumnSpecs
2910
+ .filter(spec => gridTableState.columnVisibility[spec.id] === true)
2911
+ .map(spec => spec.id);
2912
+
2913
+ queueMicrotask(() => setVisibleRelationColumnIds(current => (
2914
+ current.length === next.length && current.every((id, index) => id === next[index]) ? current : next
2915
+ )));
2916
+ }, [relationColumnSpecs, gridTableState.columnVisibility]);
2917
+
2918
+ const persistSnapshot = useMemo(() => ({
2919
+ searchInput,
2920
+ sorting: liveSorting,
2921
+ columnFilters,
2922
+ pageSize: pagination.pageSize,
2923
+ columnVisibility: gridTableState.columnVisibility,
2924
+ columnOrder: gridTableState.columnOrder,
2925
+ columnPinning: gridTableState.columnPinning,
2926
+ columnSizing: gridTableState.columnSizing,
2927
+ grouping: gridTableState.grouping,
2928
+ expanded: gridTableState.expanded,
2929
+ rowHeight: currentRowHeight,
2930
+ displayMode: currentDisplayMode,
2931
+ pivotFilterRule
2932
+ }), [
2933
+ searchInput,
2934
+ liveSorting,
2935
+ columnFilters,
2936
+ pagination.pageSize,
2937
+ gridTableState.columnVisibility,
2938
+ gridTableState.columnOrder,
2939
+ gridTableState.columnPinning,
2940
+ gridTableState.columnSizing,
2941
+ gridTableState.grouping,
2942
+ gridTableState.expanded,
2943
+ currentRowHeight,
2944
+ currentDisplayMode,
2945
+ pivotFilterRule
2946
+ ]);
2947
+
2948
+ const restorePersistedParams = useCallback((restored: Partial<DataGridPersistSnapshot>) => {
2949
+ if (typeof restored.searchInput === 'string') setSearchInput(restored.searchInput);
2950
+ if (Array.isArray(restored.sorting)) table.setSorting(restored.sorting);
2951
+ if (typeof restored.pageSize === 'number') {
2952
+ setPagination(prev => ({ ...prev, pageSize: restored.pageSize as number }));
2953
+ }
2954
+ if (restored.columnVisibility) table.setColumnVisibility(restored.columnVisibility);
2955
+ if (Array.isArray(restored.columnOrder)) table.setColumnOrder(restored.columnOrder);
2956
+ if (restored.columnPinning) table.setColumnPinning(restored.columnPinning);
2957
+ if (restored.columnSizing) table.setColumnSizing(restored.columnSizing);
2958
+ if (Array.isArray(restored.grouping)) table.setGrouping(restored.grouping);
2959
+ if (restored.expanded !== undefined) table.setExpanded(restored.expanded);
2960
+ if (restored.rowHeight) table.options.meta?.onRowHeightChange?.(restored.rowHeight);
2961
+ if (restored.displayMode) table.options.meta?.onDisplayModeChange?.(restored.displayMode);
2962
+ if (restored.pivotFilterRule !== undefined) setPivotFilterRule(restored.pivotFilterRule ?? null);
2963
+ /*
2964
+ * Toolbar column filters are cleared via a `setTimeout(0)` on every view
2965
+ * switch (see the clear effect above). Re-apply the persisted filters on a
2966
+ * later macrotask so that reset doesn't wipe the restored overlay.
2967
+ */
2968
+ if (Array.isArray(restored.columnFilters)) {
2969
+ const filters = restored.columnFilters;
2970
+
2971
+ window.setTimeout(() => setColumnFilters(filters), 0);
2972
+ }
2973
+ }, [table]);
2974
+
2975
+ useParameterPersistence<DataGridPersistSnapshot>({
2976
+ enabled: persistEnabled,
2977
+ storage: persistStorage,
2978
+ storageKey: persistStorageKey,
2979
+ ready: persistReady,
2980
+ snapshot: persistSnapshot,
2981
+ onRestore: restorePersistedParams
2982
+ });
2983
+
2984
+ /*
2985
+ * Lazy-load list of all data sources so relation filters can resolve a
2986
+ * `relationDataSourceId` (UUID) → `{ appSlug, slug }` (REST path). Reads from
2987
+ * the shared, post-sign-in-warmed inventory cache (`listDataSources()`) — a
2988
+ * cache hit on the single `/v1/apps/data-sources?expand=views,forms,fields`
2989
+ * request the app already made at bootstrap, instead of a fresh
2990
+ * `/v1/apps/data-sources` fetch. Still lazy (`enabled: false`); resolved the
2991
+ * first time a filter menu touches a relation column. Without this, filtering
2992
+ * by a relation field would have no way to query the related data source's
2993
+ * items endpoint.
2994
+ */
2995
+ const dataSourcesLookupQuery = useQuery<Map<string, { appSlug: string; slug: string }>>({
2996
+ queryKey: ['kiva', 'kivaDataGridDataSources'],
2997
+ queryFn: async () => {
2998
+ const inventory = getSharedKivaInventory(viewSelectOptions.client);
2999
+ const list = await inventory.listDataSources();
3000
+ const map = new Map<string, { appSlug: string; slug: string }>();
3001
+
3002
+ for (const entry of list) {
3003
+ const record = entry as Record<string, unknown>;
3004
+ const id = typeof record.id === 'string' ? record.id : null;
3005
+ const slug = typeof record.slug === 'string' ? record.slug : null;
3006
+ const appSlugFromSnake = typeof record.app_slug === 'string' ? record.app_slug : null;
3007
+ const appSlugFromCamel = typeof record.appSlug === 'string' ? record.appSlug : null;
3008
+ const targetAppSlug = appSlugFromCamel ?? appSlugFromSnake;
3009
+
3010
+ if (id && slug && targetAppSlug) {
3011
+ map.set(id, { appSlug: targetAppSlug, slug });
3012
+ }
3013
+ }
3014
+
3015
+ return map;
3016
+ },
3017
+ enabled: false,
3018
+ staleTime: 5 * 60_000
3019
+ });
3020
+
3021
+ const ensureDataSourcesLookup = useCallback(async () => {
3022
+ if (dataSourcesLookupQuery.data) return dataSourcesLookupQuery.data;
3023
+ const result = await dataSourcesLookupQuery.refetch();
3024
+
3025
+ return result.data ?? new Map();
3026
+ }, [dataSourcesLookupQuery]);
3027
+
3028
+ /*
3029
+ * The tenant's users for user-field filters, when the host passes no
3030
+ * `users`. A filter's search fetches them on demand; a user filter already
3031
+ * set (e.g. restored with the view) fetches them for its chip's names.
3032
+ */
3033
+ const queryClient = useQueryClient();
3034
+ const userFieldSlugs = useMemo(
3035
+ () => new Set((dataSource?.fields ?? [])
3036
+ .filter(field => field.type === 'field-userSelect' || field.type === 'field-userMultiSelect')
3037
+ .map(field => field.slug)),
3038
+ [dataSource?.fields]
3039
+ );
3040
+ const hasUserFilter = columnFilters.some(filter => userFieldSlugs.has(filter.id));
3041
+ const usersDirectoryQuery = useQuery({
3042
+ ...usersDirectoryQueryOptions(viewSelectOptions.client),
3043
+ enabled: !(users && users.length > 0) && hasUserFilter
3044
+ });
3045
+ const usersDirectory = useMemo(() => usersDirectoryQuery.data?.map(toUserFilterOption), [usersDirectoryQuery.data]);
3046
+
3047
+ const getAsyncOptions = useCallback(
3048
+ (column: { columnDef: { meta?: { cell?: unknown } } }): AsyncOptionsConfig | undefined => {
3049
+ const cellMeta = column.columnDef.meta?.cell as
3050
+ | {
3051
+ variant?: string;
3052
+ dataSourceId?: string;
3053
+ relationAppSlug?: string;
3054
+ relationDataSourceSlug?: string;
3055
+ }
3056
+ | undefined;
3057
+ const variant = cellMeta?.variant;
3058
+
3059
+ if (variant === 'user' || variant === 'user-multi-select') {
3060
+ /*
3061
+ * `/v1/users` takes only `limit` / `offset`, so a search sent to it
3062
+ * comes back as the same first page whatever was typed, and a person
3063
+ * past that page could not be found. The search runs here instead:
3064
+ * over the hook's `users` prop when the host wires one up, otherwise
3065
+ * over all of the tenant's users, fetched once. It looks at the
3066
+ * name and the email, ignores case, accents and the Turkish dotted /
3067
+ * dotless i, and wants every typed word somewhere in them.
3068
+ */
3069
+ const fromProp: Array<UserFilterOption> | null = users && users.length > 0 ? users.map(user => ({
3070
+ value: user.value,
3071
+ label: user.label,
3072
+ ...(user.avatarUrl ? { imageUrl: user.avatarUrl } : {})
3073
+ })) : null;
3074
+
3075
+ return {
3076
+ load: async ({
3077
+ search, page, pageSize, signal
3078
+ }) => {
3079
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
3080
+
3081
+ const directory = fromProp ?? (await queryClient.fetchQuery(usersDirectoryQueryOptions(viewSelectOptions.client))).map(toUserFilterOption);
3082
+ const matching = filterUserOptions(directory, search);
3083
+ const start = page * pageSize;
3084
+
3085
+ return { items: matching.slice(start, start + pageSize).map(withUserIcon), hasMore: start + pageSize < matching.length };
3086
+ },
3087
+ resolve: (values) => {
3088
+ const directory: ReadonlyArray<UserFilterOption> = fromProp ?? usersDirectory ?? [];
3089
+
3090
+ return values
3091
+ .map(value => directory.find(option => option.value === value))
3092
+ .filter((option): option is UserFilterOption => option !== undefined)
3093
+ .map(withUserIcon);
3094
+ }
3095
+ };
3096
+ }
3097
+
3098
+ if (variant === 'relation') {
3099
+ const dataSourceId = cellMeta?.dataSourceId;
3100
+ const directAppSlug = cellMeta?.relationAppSlug;
3101
+ const directSlug = cellMeta?.relationDataSourceSlug;
3102
+
3103
+ if (!dataSourceId && !(directAppSlug && directSlug)) return undefined;
3104
+
3105
+ return {
3106
+ load: async ({
3107
+ search, page, pageSize, signal
3108
+ }) => {
3109
+ /*
3110
+ * Prefer the slug+appSlug captured directly from the field
3111
+ * metadata (`relation_data_source_app_slug` /
3112
+ * `relation_data_source_slug`) so we don't have to fan out a
3113
+ * `/v1/apps/data-sources` lookup just to translate the UUID. The
3114
+ * lookup query stays as a fallback for legacy field metadata
3115
+ * that only carries the UUID.
3116
+ */
3117
+ let target: { appSlug: string; slug: string } | undefined
3118
+ = directAppSlug && directSlug ? { appSlug: directAppSlug, slug: directSlug } : undefined;
3119
+
3120
+ if (!target) {
3121
+ const lookup = await ensureDataSourcesLookup();
3122
+
3123
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
3124
+
3125
+ target = dataSourceId ? lookup.get(dataSourceId) : undefined;
3126
+ }
3127
+
3128
+ if (!target) return { items: [], hasMore: false };
3129
+
3130
+ /*
3131
+ * `autonumber_id` gives us the secondary disambiguation label but
3132
+ * only resolves on SIMPLE/ADVANCED sources; SYSTEM data sources
3133
+ * have no such column and requesting it 500s. Try the richer
3134
+ * projection first, then retry once with just `id, name` on
3135
+ * failure so system relations still load.
3136
+ */
3137
+ const fetchItems = (columns: string) => viewSelectOptions.client.get<{ data?: Array<Record<string, unknown>>; meta?: { total?: number } } | Array<Record<string, unknown>>>(
3138
+ `/v1/apps/${target.appSlug}/data-sources/${target.slug}/items`,
3139
+ {
3140
+ columns,
3141
+ filterKeyword: search || undefined,
3142
+ limit: pageSize,
3143
+ offset: page * pageSize,
3144
+ fullCount: true
3145
+ } as Parameters<typeof viewSelectOptions.client.get>[1],
3146
+ { signal }
3147
+ );
3148
+
3149
+ let response;
3150
+
3151
+ try {
3152
+ response = await fetchItems('id, name, autonumber_id');
3153
+ } catch (err) {
3154
+ if (signal?.aborted) throw err;
3155
+ response = await fetchItems('id, name');
3156
+ }
3157
+ const items = Array.isArray(response) ? response : (response?.data ?? []);
3158
+ const total = !Array.isArray(response) ? response?.meta?.total : undefined;
3159
+ const mapped = items
3160
+ .map((record) => {
3161
+ const id = typeof record.id === 'string' ? record.id : null;
3162
+ const rawName = typeof record.name === 'string' ? record.name : null;
3163
+ const name = rawName ? decodeHtmlEntities(rawName) : null;
3164
+ const autoNumber = typeof record.autonumber_id === 'string' || typeof record.autonumber_id === 'number' ? String(record.autonumber_id) : null;
3165
+ const label = name ?? autoNumber ?? id;
3166
+
3167
+ if (!id || !label) return null;
3168
+
3169
+ /*
3170
+ * Surface `autonumber_id` as the secondary label so the
3171
+ * value editor can disambiguate same-named relation
3172
+ * records (e.g. two "Project K" records that the backend
3173
+ * returns from a relation lookup). Only attach it when a
3174
+ * proper `name` exists — otherwise the autonumber IS the
3175
+ * primary label and there's nothing to disambiguate.
3176
+ */
3177
+ const secondaryLabel = name && autoNumber ? `#${autoNumber}` : undefined;
3178
+
3179
+ return secondaryLabel ? { value: id, label, secondaryLabel } : { value: id, label };
3180
+ })
3181
+ .filter((option): option is { value: string; label: string; secondaryLabel?: string } => option !== null);
3182
+ const hasMore = typeof total === 'number' ? (page + 1) * pageSize < total : items.length === pageSize;
3183
+
3184
+ return { items: mapped, hasMore };
3185
+ }
3186
+ };
3187
+ }
3188
+
3189
+ return undefined;
3190
+ },
3191
+ [
3192
+ viewSelectOptions,
3193
+ ensureDataSourcesLookup,
3194
+ users,
3195
+ queryClient,
3196
+ usersDirectory
3197
+ ]
3198
+ );
3199
+
3200
+ /*
3201
+ * Server-side export wiring. The hook hands a query payload to
3202
+ * `POST /v1/edge/run/query-export` and lets the backend stream the result
3203
+ * as an xlsx attachment, so exports aren't bound by what's currently loaded
3204
+ * in the grid. Two scopes are surfaced through the toolbar menu:
3205
+ *
3206
+ * - `'visible'` — columns the active view exposes (minus the internal
3207
+ * metadata slugs and unexportable field types — same exclusions the
3208
+ * legacy Vue exporter applied).
3209
+ * - `'all'` — every field flagged exportable on the data source,
3210
+ * filtered by the same exclusions. Falls back to the entire field set
3211
+ * when the data source lacks an explicit `export` flag.
3212
+ */
3213
+ const { exportData: exportServerData, isExporting: isServerExporting } = useKivaDataExport({
3214
+ client: viewSelectOptions.client,
3215
+ defaultLimit: serverExportLimit
3216
+ });
3217
+
3218
+ const { t } = useUiTranslation();
3219
+
3220
+ /*
3221
+ * The operations the caller may run on this data source. Only the single
3222
+ * data source endpoint returns them (the inventory the schema comes from
3223
+ * does not), so they cost one small cached request. Until they arrive, or
3224
+ * when a server does not send them, the export actions stay; the export
3225
+ * endpoint checks the permission itself.
3226
+ */
3227
+ const allowedOperationsQuery = useQuery({
3228
+ queryKey: [
3229
+ 'kiva',
3230
+ 'kivaDataSourceAllowedOperations',
3231
+ viewSelectOptions.appSlug,
3232
+ viewSelectOptions.dataSourceSlug
3233
+ ] as const,
3234
+ queryFn: async () => {
3235
+ const response = await viewSelectOptions.client.get<unknown>(`/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}`);
3236
+ const record = (response as { data?: unknown } | null)?.data ?? response;
3237
+ const operations = (record as { allowedOperations?: unknown } | null)?.allowedOperations;
3238
+
3239
+ return Array.isArray(operations) ? operations.filter((operation): operation is string => typeof operation === 'string') : null;
3240
+ },
3241
+ enabled: (enableServerExportMenu || bulkActionSet.has('export')) && Boolean(viewSelectOptions.appSlug && viewSelectOptions.dataSourceSlug),
3242
+ staleTime: 5 * 60_000
3243
+ });
3244
+
3245
+ /** Exporting a list, as a server file or as selected rows, takes the bulk export permission. */
3246
+ const canExportRows = !allowedOperationsQuery.data || allowedOperationsQuery.data.includes('export_bulk');
3247
+
3248
+ const exportBooleanLabels = useMemo(
3249
+ () => ({
3250
+ true: t('ui.dataGrid.exportBooleanTrue', 'Yes'),
3251
+ false: t('ui.dataGrid.exportBooleanFalse', 'No')
3252
+ }),
3253
+ [t]
3254
+ );
3255
+
3256
+ const serverExportableFields = useMemo<Array<DataSourceField>>(() => {
3257
+ const fields = dataSource?.fields ?? [];
3258
+
3259
+ if (fields.length === 0) return [];
3260
+
3261
+ const excludedSlugs = new Set<string>(
3262
+ serverExportExcludedSlugs ?? DEFAULT_SERVER_EXPORT_EXCLUDED_SLUGS
3263
+ );
3264
+ const excludedTypes = new Set<string>(
3265
+ serverExportExcludedFieldTypes ?? DEFAULT_SERVER_EXPORT_EXCLUDED_TYPES
3266
+ );
3267
+
3268
+ return fields.filter((field) => {
3269
+ if (excludedSlugs.has(field.slug)) return false;
3270
+ if (typeof field.type === 'string' && excludedTypes.has(field.type)) return false;
3271
+
3272
+ const fieldRecord = field as Record<string, unknown>;
3273
+
3274
+ if (fieldRecord.export === false) return false;
3275
+
3276
+ return true;
3277
+ });
3278
+ }, [dataSource?.fields, serverExportExcludedSlugs, serverExportExcludedFieldTypes]);
3279
+
3280
+ /*
3281
+ * The ids of the columns on screen, in display order. Keyed by content: the
3282
+ * table instance never changes identity, so a memo on it would keep the
3283
+ * first render's columns.
3284
+ */
3285
+ const visibleColumnKey = table.getVisibleLeafColumns().map(column => column.id).join('\n');
3286
+ const visibleColumnIds = useMemo(
3287
+ () => (visibleColumnKey ? visibleColumnKey.split('\n') : []),
3288
+ [visibleColumnKey]
3289
+ );
3290
+
3291
+ /*
3292
+ * The visible scope follows the grid as it is on screen: visible columns in
3293
+ * display order, unsaved hides and reorders included. Grouping fields the
3294
+ * rows depend on are kept even when their column is hidden.
3295
+ */
3296
+ const serverExportVisibleSlugs = useMemo(() => {
3297
+ const exportable = new Set(serverExportableFields.map(field => field.slug));
3298
+ const slugs = visibleColumnIds.filter(id => exportable.has(id));
3299
+
3300
+ for (const slug of groupingRequiredSlugs) {
3301
+ if (exportable.has(slug) && !slugs.includes(slug)) slugs.push(slug);
3302
+ }
3303
+
3304
+ return slugs;
3305
+ }, [serverExportableFields, visibleColumnIds, groupingRequiredSlugs]);
3306
+
3307
+ const serverExportColumnSlugs = useCallback(
3308
+ (scope: 'visible' | 'all'): Array<string> => (scope === 'all' ? serverExportableFields.map(field => field.slug) : serverExportVisibleSlugs),
3309
+ [serverExportableFields, serverExportVisibleSlugs]
3310
+ );
3311
+
3312
+ /** Picker rows: the on-screen columns first, in display order, then the rest. */
3313
+ const serverExportFieldOptions = useMemo<Array<KivaDataExportFieldOption>>(() => {
3314
+ const rank = new Map(serverExportVisibleSlugs.map((slug, index) => [slug, index]));
3315
+
3316
+ return [...serverExportableFields]
3317
+ .sort((a, b) => (rank.get(a.slug) ?? rank.size) - (rank.get(b.slug) ?? rank.size))
3318
+ .map(field => ({
3319
+ slug: field.slug,
3320
+ name: typeof field.name === 'string' && field.name.length > 0 ? field.name : field.slug,
3321
+ type: typeof field.type === 'string' ? field.type : ''
3322
+ }));
3323
+ }, [serverExportableFields, serverExportVisibleSlugs]);
3324
+
3325
+ /*
3326
+ * Headers for the requested layout: the labels the grid shows, with the No
3327
+ * and the raw id of a relation, user or choice column told apart from its
3328
+ * label by a suffix.
3329
+ */
3330
+ const buildServerExportHeaders = useCallback(
3331
+ (entries: ReadonlyArray<KivaDataExportColumn>): Record<string, string> => {
3332
+ const columnsById = new Map(table.getAllLeafColumns().map(column => [column.id, column]));
3333
+ const fieldsBySlug = new Map((dataSource?.fields ?? []).map(field => [field.slug, field]));
3334
+ const headers: Record<string, string> = {};
3335
+
3336
+ for (const entry of entries) {
3337
+ const label = exportColumnLabel(columnsById.get(entry.slug)?.columnDef.meta?.label, fieldsBySlug.get(entry.slug)?.name, entry.slug);
3338
+
3339
+ for (const { key, variant } of kivaDataExportColumnKeys(entry)) {
3340
+ headers[key] = variant === 'id' ? `${label} (ID)` : variant === 'autonumber_id' ? `${label} (No)` : label;
3341
+ }
3342
+ }
3343
+
3344
+ return headers;
3345
+ },
3346
+ [table, dataSource?.fields]
3347
+ );
3348
+
3349
+ const handleServerExport = useCallback(
3350
+ async (selection: KivaDataExportSelection) => {
3351
+ const dataSourceId = typeof dataSource?.id === 'string' ? dataSource.id : null;
3352
+
3353
+ if (!dataSourceId) return;
3354
+
3355
+ const entries: ReadonlyArray<KivaDataExportColumn> = selection.scope === 'custom' ? selection.columns : serverExportColumnSlugs(selection.scope).map(slug => ({ slug }));
3356
+ const columns = entries.map(encodeKivaDataExportColumn);
3357
+ const payload: KivaDataExportPayload = {
3358
+ dataSourceId,
3359
+ columns: columns.length > 0 ? columns : '*',
3360
+ filters: resolvedListParams.filters as KivaDataExportPayload['filters'],
3361
+ filterKeyword: typeof resolvedListParams.filterKeyword === 'string' ? resolvedListParams.filterKeyword : undefined,
3362
+ orderBy: resolvedListParams.orderBy,
3363
+ limit: serverExportLimit,
3364
+ format: selection.format,
3365
+ ...(columns.length > 0 ? { layout: 'requested', headers: buildServerExportHeaders(entries), booleanLabels: exportBooleanLabels } : {})
3366
+ };
3367
+
3368
+ await exportServerData(payload);
3369
+ },
3370
+ [
3371
+ dataSource?.id,
3372
+ serverExportColumnSlugs,
3373
+ buildServerExportHeaders,
3374
+ exportBooleanLabels,
3375
+ resolvedListParams.filters,
3376
+ resolvedListParams.filterKeyword,
3377
+ resolvedListParams.orderBy,
3378
+ serverExportLimit,
3379
+ exportServerData
3380
+ ]
3381
+ );
3382
+
3383
+ /*
3384
+ * Columns for a file built in the browser, read from the table at click
3385
+ * time: the visible scope follows the grid as shown, headers are the column
3386
+ * labels, and cells holding ids or references are written as the label the
3387
+ * cell shows instead of a uuid or JSON.
3388
+ */
3389
+ const buildClientExportColumns = useCallback(
3390
+ (columnScope: 'visible' | 'all' = 'visible'): Array<DataExportColumn<TData>> => {
3391
+ const fields = dataSource?.fields ?? [];
3392
+ const fieldsBySlug = new Map(fields.map(field => [field.slug, field]));
3393
+ const columnsById = new Map(table.getAllLeafColumns().map(column => [column.id, column]));
3394
+
3395
+ const slugs = (() => {
3396
+ if (columnScope === 'all' || exportColumns === 'all') return fields.map(field => field.slug);
3397
+ if (Array.isArray(exportColumns)) return exportColumns;
3398
+
3399
+ return table.getVisibleLeafColumns().map(column => column.id);
3400
+ })();
3401
+
3402
+ return slugs.flatMap<DataExportColumn<TData>>((slug) => {
3403
+ const field = fieldsBySlug.get(slug);
3404
+
3405
+ if (!field) return [];
3406
+
3407
+ const meta = columnsById.get(slug)?.columnDef.meta;
3408
+ const header = exportColumnLabel(meta?.label, field.name, slug);
3409
+ const cell = meta?.cell;
3410
+
3411
+ if (!cell || !LABELLED_EXPORT_VARIANTS.has(cell.variant)) return [{ id: slug, header }];
3412
+
3413
+ return [{ id: slug, header, formatter: value => formatExportLabel(value, cell) }];
3414
+ });
3415
+ },
3416
+ [dataSource?.fields, exportColumns, table]
3417
+ );
3418
+
3419
+ const { exportData, isExporting: isClientExporting } = useDataExport<TData>({
3420
+ fileName: exportFileName ?? viewSelectOptions.dataSourceSlug ?? 'export'
3421
+ });
3422
+
3423
+ const exportRows = useCallback(
3424
+ (
3425
+ rows: Array<TData>,
3426
+ format: Parameters<typeof exportData>[1],
3427
+ columnScope: 'visible' | 'all'
3428
+ ) => exportData(rows, format, buildClientExportColumns(columnScope)),
3429
+ [exportData, buildClientExportColumns]
3430
+ );
3431
+
3432
+ const hasServerExport = enableServerExportMenu && Boolean(dataSource?.id);
3433
+ const canServerExport = hasServerExport && canExportRows;
3434
+ const canClientExport = enableClientExportMenu && !hasServerExport && canExportRows;
3435
+
3436
+ /*
3437
+ * Background refetch indicator. `isFetching` covers any in-flight request
3438
+ * including the toolbar reload button; we exclude `isLoading` so the
3439
+ * dedicated initial-mount skeleton/empty state isn't double-counted as a
3440
+ * reload. Drives the toolbar reload spinner + the grid body overlay.
3441
+ */
3442
+ const isReloading = providedData === undefined
3443
+ && itemsQuery.isFetching
3444
+ && !itemsQuery.isLoading;
3445
+
3446
+ /*
3447
+ * For `vertical-tabs`, the view picker lives in the side panel — keep it
3448
+ * out of the toolbar so the controls strip stays compact.
3449
+ */
3450
+ const renderViewSelectInToolbar = enableViewSelect && viewSelectVariant !== 'vertical-tabs';
3451
+ const renderViewSelectInSidePanel = enableViewSelect && viewSelectVariant === 'vertical-tabs';
3452
+
3453
+ /*
3454
+ * Aktif filtre varken filtre seridi (filtre dugmesi + chip'ler + Clear)
3455
+ * toolbar'in tam genislikli kendi satirina iner. Onceden serit, sag buton
3456
+ * grubundan artan dar sol sutuna sikisiyor ve chip alt satira kayiyordu.
3457
+ */
3458
+ const hasToolbarFilterChips = columnFilters.length > 0;
3459
+
3460
+ const controlsToolbar = useMemo<ReactNode>(() => (
3461
+ <div
3462
+ data-slot="kiva-data-grid-toolbar"
3463
+ className={cn('flex flex-wrap items-start gap-2 px-3 py-2', toolbarClassName)}>
3464
+ <div className="flex min-w-0 items-center gap-2 flex-wrap">
3465
+ {toolbarStartContent}
3466
+ {renderViewSelectInToolbar && (
3467
+ <DataGridViewSelect
3468
+ table={table}
3469
+ variant={viewSelectVariant}
3470
+ maxVisibleViews={viewSelectMaxVisible}
3471
+ editable
3472
+ {...gridViewSelectProps} />
3473
+ )}
3474
+ {enableSearchInput && (
3475
+ <div className="relative shrink-0">
3476
+ <Search className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
3477
+ <Input
3478
+ type="search"
3479
+ value={searchInput}
3480
+ onChange={event => setSearchInput(event.target.value)}
3481
+ placeholder={searchPlaceholder}
3482
+ className="h-8 w-56 pl-7" />
3483
+ </div>
3484
+ )}
3485
+ </div>
3486
+ {/*
3487
+ * The advanced filter sits next to the chips it is ANDed with, so the
3488
+ * toolbar reads left-to-right as one sentence.
3489
+ *
3490
+ * Gated on a server-driven grid: a `providedData` grid runs
3491
+ * `manualFiltering: false` and filters through TanStack, which cannot
3492
+ * evaluate a RuleGroupType — the control would silently do nothing.
3493
+ */}
3494
+ {enableFilterMenu && (
3495
+ <div
3496
+ className={cn(
3497
+ 'flex min-w-0 items-center gap-2',
3498
+ hasToolbarFilterChips ? 'order-last basis-full' : 'shrink-0'
3499
+ )}>
3500
+ <DataGridFilterMenu
3501
+ table={table}
3502
+ getAsyncOptions={getAsyncOptions}
3503
+ className="min-w-0" />
3504
+ {providedData === undefined && (
3505
+ <DataGridAdvancedFilter
3506
+ table={table}
3507
+ group={advancedFilterGroup}
3508
+ onChange={handleAdvancedFilterChange} />
3509
+ )}
3510
+ </div>
3511
+ )}
3512
+ <div className="ml-auto flex flex-none shrink-0 items-center gap-2">
3513
+ {enableGroupMenu && (
3514
+ <DataGridGroupMenu
3515
+ table={table}
3516
+ defaultRowGroupingColumn={defaultRowGroupingColumn} />
3517
+ )}
3518
+ {enableSortMenu && <DataGridSortMenu table={table} />}
3519
+ {enableRowHeightMenu && <DataGridRowHeightMenu table={table} />}
3520
+ {enableFieldsMenu && <DataGridFieldsMenu table={table} />}
3521
+ {enableDisplayMenu && <DataGridDisplayMenu table={table} />}
3522
+ {enableGalleryMenus && currentDisplayMode === 'gallery' && (
3523
+ <>
3524
+ <DataGalleryCardConfigMenu
3525
+ table={table}
3526
+ config={galleryCardConfig}
3527
+ onConfigChange={setGalleryCardConfig} />
3528
+ <DataGalleryDisplayMenu
3529
+ config={galleryDisplayConfig}
3530
+ onConfigChange={setGalleryDisplayConfig} />
3531
+ </>
3532
+ )}
3533
+ {canServerExport && (
3534
+ <KivaDataExportMenu
3535
+ onExport={handleServerExport}
3536
+ fields={serverExportFieldOptions}
3537
+ visibleSlugs={serverExportVisibleSlugs}
3538
+ isExporting={isServerExporting} />
3539
+ )}
3540
+ {canClientExport && (
3541
+ <DataGridExportMenu
3542
+ table={table}
3543
+ onExport={exportRows}
3544
+ isExporting={isClientExporting} />
3545
+ )}
3546
+ {enableReloadButton && (
3547
+ <Button
3548
+ variant="outline"
3549
+ size="icon-sm"
3550
+ aria-label={t('ui.dataGrid.reload', 'Reload')}
3551
+ title={t('ui.dataGrid.reload', 'Reload')}
3552
+ disabled={isReloading}
3553
+ onClick={reloadItems}>
3554
+ {isReloading ? (
3555
+ <Loader2 className="size-4 animate-spin" />
3556
+ ) : (
3557
+ <RotateCw className="size-4" />
3558
+ )}
3559
+ </Button>
3560
+ )}
3561
+ {toolbarEndContent}
3562
+ </div>
3563
+ </div>
3564
+ ), [
3565
+ table,
3566
+ gridViewSelectProps,
3567
+ searchInput,
3568
+ searchPlaceholder,
3569
+ toolbarClassName,
3570
+ toolbarStartContent,
3571
+ toolbarEndContent,
3572
+ renderViewSelectInToolbar,
3573
+ viewSelectVariant,
3574
+ viewSelectMaxVisible,
3575
+ enableSearchInput,
3576
+ enableFilterMenu,
3577
+ hasToolbarFilterChips,
3578
+ enableGroupMenu,
3579
+ enableSortMenu,
3580
+ enableRowHeightMenu,
3581
+ enableFieldsMenu,
3582
+ enableDisplayMenu,
3583
+ enableGalleryMenus,
3584
+ currentDisplayMode,
3585
+ galleryCardConfig,
3586
+ galleryDisplayConfig,
3587
+ enableReloadButton,
3588
+ reloadItems,
3589
+ defaultRowGroupingColumn,
3590
+ getAsyncOptions,
3591
+ canServerExport,
3592
+ handleServerExport,
3593
+ serverExportFieldOptions,
3594
+ serverExportVisibleSlugs,
3595
+ isServerExporting,
3596
+ canClientExport,
3597
+ exportRows,
3598
+ isClientExporting,
3599
+ isReloading,
3600
+ /*
3601
+ * The advanced filter trigger. `advancedFilterGroup` is what its summary
3602
+ * chip counts, so leaving it out would freeze the chip on the group that
3603
+ * was set when the toolbar was last rebuilt.
3604
+ */
3605
+ providedData,
3606
+ advancedFilterGroup,
3607
+ handleAdvancedFilterChange,
3608
+ t
3609
+ ]);
3610
+
3611
+ /*
3612
+ * Bulk-action wiring. The actual floating bar is rendered by `<DataGrid>`
3613
+ * via its built-in `actions` prop; this hook just produces the action
3614
+ * descriptors plus the dialogs they trigger.
3615
+ */
3616
+ const [bulkUpdateOpen, setBulkUpdateOpen] = useState(false);
3617
+ const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
3618
+ const [isBulkDeleting, setIsBulkDeleting] = useState(false);
3619
+ const [bulkUpdateRecords, setBulkUpdateRecords] = useState<ReadonlyArray<TData>>([]);
3620
+ const [bulkDeleteIds, setBulkDeleteIds] = useState<ReadonlyArray<string>>([]);
3621
+ const [bulkDeleteCount, setBulkDeleteCount] = useState(0);
3622
+ const [bulkEmailOpen, setBulkEmailOpen] = useState(false);
3623
+ const [bulkEmailRecipients, setBulkEmailRecipients] = useState<string[]>([]);
3624
+ const [bulkMessageOpen, setBulkMessageOpen] = useState(false);
3625
+ const [bulkMessageRecipients, setBulkMessageRecipients] = useState<string[]>([]);
3626
+
3627
+ const emailFieldSlugs = useMemo(
3628
+ () => collectFieldSlugsByType(dataSource?.fields, EMAIL_FIELD_TYPES),
3629
+ [dataSource?.fields]
3630
+ );
3631
+ const phoneFieldSlugs = useMemo(
3632
+ () => collectFieldSlugsByType(dataSource?.fields, PHONE_FIELD_TYPES),
3633
+ [dataSource?.fields]
3634
+ );
3635
+
3636
+ const clearSelection = useCallback(() => {
3637
+ table.toggleAllRowsSelected(false);
3638
+ }, [table]);
3639
+
3640
+ const bulkDeleteMutation = useMutation({
3641
+ mutationFn: async (recordIds: ReadonlyArray<string>) => {
3642
+ const body = { recordIds: [...recordIds] };
3643
+
3644
+ if (collection?.deleteMany) {
3645
+ await collection.deleteMany(body);
3646
+
3647
+ return;
3648
+ }
3649
+
3650
+ await viewSelectOptions.client.delete(
3651
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items`,
3652
+ body
3653
+ );
3654
+ }
3655
+ });
3656
+
3657
+ const onConfirmBulkDelete = useCallback(async () => {
3658
+ if (bulkDeleteIds.length === 0) return;
3659
+
3660
+ setIsBulkDeleting(true);
3661
+
3662
+ try {
3663
+ await bulkDeleteMutation.mutateAsync(bulkDeleteIds);
3664
+ setBulkDeleteOpen(false);
3665
+ clearSelection();
3666
+
3667
+ if (providedData === undefined) {
3668
+ void itemsRefetchRef.current?.();
3669
+ }
3670
+ } finally {
3671
+ setIsBulkDeleting(false);
3672
+ }
3673
+ }, [
3674
+ bulkDeleteIds,
3675
+ bulkDeleteMutation,
3676
+ clearSelection,
3677
+ providedData
3678
+ ]);
3679
+
3680
+ const onBulkUpdateSuccess = useCallback(() => {
3681
+ clearSelection();
3682
+
3683
+ if (providedData === undefined) {
3684
+ void itemsRefetchRef.current?.();
3685
+ }
3686
+ }, [clearSelection, providedData]);
3687
+
3688
+ const bulkActionDescriptors = useMemo<Array<DataGridAction<TData>>>(() => {
3689
+ if (bulkActionSet.size === 0 && (!extraBulkActions || extraBulkActions.length === 0)) return [];
3690
+
3691
+ const list: Array<DataGridAction<TData>> = [];
3692
+
3693
+ if (bulkActionSet.has('update')) {
3694
+ list.push({
3695
+ key: 'bulk-update',
3696
+ label: 'Update',
3697
+ icon: <Pencil className="size-4" />,
3698
+ onAction: (rows) => {
3699
+ if (rows.length === 0) return;
3700
+ setBulkUpdateRecords(rows);
3701
+ setBulkUpdateOpen(true);
3702
+ }
3703
+ });
3704
+ }
3705
+
3706
+ if (bulkActionSet.has('delete')) {
3707
+ list.push({
3708
+ key: 'bulk-delete',
3709
+ label: 'Delete',
3710
+ icon: <Trash2 className="size-4" />,
3711
+ variant: 'destructive',
3712
+ onAction: (rows) => {
3713
+ const ids = rows
3714
+ .map(row => (row as { id?: unknown }).id)
3715
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
3716
+
3717
+ if (ids.length === 0) return;
3718
+
3719
+ setBulkDeleteIds(ids);
3720
+ setBulkDeleteCount(rows.length);
3721
+ setBulkDeleteOpen(true);
3722
+ }
3723
+ });
3724
+ }
3725
+
3726
+ if (bulkActionSet.has('export') && canExportRows) {
3727
+ list.push({
3728
+ key: 'bulk-export',
3729
+ label: 'Export',
3730
+ render: rows => (
3731
+ <DropdownMenu>
3732
+ <DropdownMenuTrigger asChild>
3733
+ <Button variant="secondary" size="sm">
3734
+ <Download className="size-4" />
3735
+ Export
3736
+ </Button>
3737
+ </DropdownMenuTrigger>
3738
+ <DropdownMenuContent align="end">
3739
+ <DropdownMenuItem onClick={() => void exportData(rows, 'csv', buildClientExportColumns())}>
3740
+ CSV
3741
+ </DropdownMenuItem>
3742
+ <DropdownMenuItem onClick={() => void exportData(rows, 'xlsx', buildClientExportColumns())}>
3743
+ Excel (.xlsx)
3744
+ </DropdownMenuItem>
3745
+ <DropdownMenuItem onClick={() => void exportData(rows, 'json', buildClientExportColumns())}>
3746
+ JSON
3747
+ </DropdownMenuItem>
3748
+ <DropdownMenuItem onClick={() => void exportData(rows, 'markdown', buildClientExportColumns())}>
3749
+ Markdown
3750
+ </DropdownMenuItem>
3751
+ </DropdownMenuContent>
3752
+ </DropdownMenu>
3753
+ )
3754
+ });
3755
+ }
3756
+
3757
+ if (bulkActionSet.has('email') && emailFieldSlugs.length > 0) {
3758
+ list.push({
3759
+ key: 'bulk-email',
3760
+ label: 'Email',
3761
+ icon: <Mail className="size-4" />,
3762
+ onAction: (rows) => {
3763
+ const recipients = collectRecipientValues(rows, emailFieldSlugs);
3764
+
3765
+ if (recipients.length === 0) return;
3766
+
3767
+ setBulkEmailRecipients(recipients);
3768
+ setBulkEmailOpen(true);
3769
+ }
3770
+ });
3771
+ }
3772
+
3773
+ if (bulkActionSet.has('message') && phoneFieldSlugs.length > 0) {
3774
+ list.push({
3775
+ key: 'bulk-message',
3776
+ label: 'Message',
3777
+ icon: <MessageSquare className="size-4" />,
3778
+ onAction: (rows) => {
3779
+ const recipients = collectRecipientValues(rows, phoneFieldSlugs);
3780
+
3781
+ if (recipients.length === 0) return;
3782
+
3783
+ setBulkMessageRecipients(recipients);
3784
+ setBulkMessageOpen(true);
3785
+ }
3786
+ });
3787
+ }
3788
+
3789
+ if (extraBulkActions && extraBulkActions.length > 0) {
3790
+ list.push(...extraBulkActions);
3791
+ }
3792
+
3793
+ return list;
3794
+ }, [
3795
+ bulkActionSet,
3796
+ canExportRows,
3797
+ exportData,
3798
+ buildClientExportColumns,
3799
+ extraBulkActions,
3800
+ emailFieldSlugs,
3801
+ phoneFieldSlugs
3802
+ ]);
3803
+
3804
+ const bulkDialogs = bulkActionSet.size > 0 ? (
3805
+ <>
3806
+ {bulkActionSet.has('update') && (
3807
+ <BulkUpdateDialog
3808
+ open={bulkUpdateOpen}
3809
+ onOpenChange={(next) => {
3810
+ setBulkUpdateOpen(next);
3811
+ if (!next) setBulkUpdateRecords([]);
3812
+ }}
3813
+ client={viewSelectOptions.client}
3814
+ appSlug={viewSelectOptions.appSlug}
3815
+ dataSourceSlug={viewSelectOptions.dataSourceSlug}
3816
+ records={bulkUpdateRecords as ReadonlyArray<{ id: string }>}
3817
+ onSuccess={onBulkUpdateSuccess} />
3818
+ )}
3819
+ {bulkActionSet.has('delete') && (
3820
+ <RecordDeleteConfirmDialog
3821
+ open={bulkDeleteOpen}
3822
+ onOpenChange={(next) => {
3823
+ if (!next && !isBulkDeleting) {
3824
+ setBulkDeleteOpen(false);
3825
+ setBulkDeleteIds([]);
3826
+ setBulkDeleteCount(0);
3827
+ }
3828
+ }}
3829
+ recordCount={bulkDeleteCount}
3830
+ isPending={isBulkDeleting}
3831
+ onConfirm={onConfirmBulkDelete} />
3832
+ )}
3833
+ {bulkActionSet.has('email') && emailFieldSlugs.length > 0 && (
3834
+ <EmailComposeDialog
3835
+ client={viewSelectOptions.client}
3836
+ trigger={null}
3837
+ open={bulkEmailOpen}
3838
+ onOpenChange={(next) => {
3839
+ setBulkEmailOpen(next);
3840
+ if (!next) setBulkEmailRecipients([]);
3841
+ }}
3842
+ to={bulkEmailRecipients} />
3843
+ )}
3844
+ {bulkActionSet.has('message') && phoneFieldSlugs.length > 0 && (
3845
+ <InstantMessageComposeDialog
3846
+ client={viewSelectOptions.client}
3847
+ trigger={null}
3848
+ open={bulkMessageOpen}
3849
+ onOpenChange={(next) => {
3850
+ setBulkMessageOpen(next);
3851
+ if (!next) setBulkMessageRecipients([]);
3852
+ }}
3853
+ to={bulkMessageRecipients} />
3854
+ )}
3855
+ </>
3856
+ ) : null;
3857
+
3858
+ /*
3859
+ * Auto-stack pivot filter strips above the data-view controls when the
3860
+ * caller passes `pivotFilters`. `<KivaPivotFilterGroup>` owns the
3861
+ * per-strip query state, surfaces the AND-combined rule via
3862
+ * `onFilterRuleChange`, and cross-filters by seeing the grid's external
3863
+ * filter chain (saved view + toolbar + side) as `activeFilters`.
3864
+ */
3865
+ const pivotFiltersToolbar: ReactNode = pivotFilters && pivotFilters.length > 0 ? (
3866
+ <KivaPivotFilterGroup
3867
+ client={viewSelectOptions.client}
3868
+ appSlug={viewSelectOptions.appSlug}
3869
+ dataSourceSlug={viewSelectOptions.dataSourceSlug}
3870
+ fields={pivotFilters}
3871
+ activeFilters={externalFilterChain}
3872
+ onFilterRuleChange={setPivotFilterRule} />
3873
+ ) : null;
3874
+
3875
+ const toolbar = (
3876
+ <>
3877
+ {pivotFiltersToolbar}
3878
+ {controlsToolbar}
3879
+ {bulkDialogs}
3880
+ </>
3881
+ );
3882
+
3883
+ const sidePanel: ReactNode = renderViewSelectInSidePanel ? (
3884
+ <DataGridSidePanel>
3885
+ <DataGridViewSelect
3886
+ table={table}
3887
+ variant="vertical-tabs"
3888
+ editable
3889
+ {...gridViewSelectProps} />
3890
+ </DataGridSidePanel>
3891
+ ) : null;
3892
+
3893
+ const expandedSideFilterWidth = typeof sideFiltersWidth === 'number' ? `${sideFiltersWidth}px` : sideFiltersWidth;
3894
+ const sideFiltersNode: ReactNode = enableSideFilters && sideFiltersConfig ? (
3895
+ <DataTableSideFilters
3896
+ columns={sideFilterDtf.columns}
3897
+ filters={sideFilterDtf.filters}
3898
+ actions={sideFilterDtf.actions}
3899
+ strategy={sideFilterDtf.strategy}
3900
+ defaults={sideFilterDtf.defaults}
3901
+ sections={sideFilterDtf.sections}
3902
+ locale={sideFiltersConfig.locale}
3903
+ variant={sideFiltersConfig.variant}
3904
+ title={sideFiltersConfig.title}
3905
+ showActiveChips={sideFiltersConfig.showActiveChips}
3906
+ showClearAll={sideFiltersConfig.showClearAll}
3907
+ searchable={sideFiltersConfig.searchable}
3908
+ clearAllLabel={sideFiltersConfig.clearAllLabel}
3909
+ clearLabel={sideFiltersConfig.clearLabel}
3910
+ className={cn(
3911
+ 'h-full shrink-0 overflow-y-auto border-r p-3',
3912
+ sideFiltersConfig.className
3913
+ )}
3914
+ style={sideFiltersExpanded ? { width: expandedSideFilterWidth } : undefined}
3915
+ collapsible
3916
+ expanded={sideFiltersExpanded}
3917
+ onExpandedChange={setSideFiltersExpanded}
3918
+ collapsedWidth={sideFiltersConfig.collapsedWidth}
3919
+ collapseAriaLabel={sideFiltersConfig.collapseAriaLabel}
3920
+ expandAriaLabel={sideFiltersConfig.expandAriaLabel} />
3921
+ ) : null;
3922
+
3923
+ /*
3924
+ * Inject the bulk-action descriptors into the grid props the consumer
3925
+ * spreads onto `<DataGrid>` — that's the floating action bar already
3926
+ * implemented by `data-grid.tsx`. `actions` is a `<DataGrid>` prop (not
3927
+ * part of `useDataGrid`'s output), so we just attach it.
3928
+ */
3929
+ const isLoading = viewSelect.isLoading
3930
+ || (providedData === undefined && (itemsQuery.isLoading || !viewMetadataReady));
3931
+ const error = (viewSelect.error ?? (itemsQuery.error as Error | null)) ?? null;
3932
+
3933
+ const gridPropsWithActions = useMemo<UseKivaDataGridResult<TData>['gridProps']>(
3934
+ () => ({
3935
+ ...gridProps,
3936
+ ...(bulkActionDescriptors.length > 0 ? { actions: bulkActionDescriptors } : {}),
3937
+ galleryCardConfig: resolvedGalleryCardConfig,
3938
+ galleryDisplayConfig,
3939
+ onCardClick,
3940
+ onClearFilters: handleClearAllFilters,
3941
+ isReloading,
3942
+ onReload: reloadItems,
3943
+ paginationExtraSlots,
3944
+ isLoading
3945
+ }),
3946
+ [
3947
+ gridProps,
3948
+ bulkActionDescriptors,
3949
+ resolvedGalleryCardConfig,
3950
+ galleryDisplayConfig,
3951
+ onCardClick,
3952
+ handleClearAllFilters,
3953
+ isReloading,
3954
+ reloadItems,
3955
+ paginationExtraSlots,
3956
+ isLoading
3957
+ ]
3958
+ );
3959
+
3960
+ const pagingMode: 'standard' | 'virtual-scroll' | undefined = viewPagingMode;
3961
+
3962
+ return {
3963
+ table,
3964
+ selectedRows,
3965
+ selectedRowCount,
3966
+ gridProps: gridPropsWithActions,
3967
+ toolbar,
3968
+ sidePanel,
3969
+ sideFilters: sideFiltersNode,
3970
+ sideFiltersExpanded,
3971
+ setSideFiltersExpanded,
3972
+ sideFiltersQuery: sideFiltersActiveQuery,
3973
+ pivotFilterRule,
3974
+ items,
3975
+ resolvedListParams,
3976
+ pagingMode,
3977
+ reload,
3978
+ views: viewSelect.views,
3979
+ fields,
3980
+ forms: viewSelect.forms,
3981
+ activeViewFormId,
3982
+ activeViewForm,
3983
+ formViewProps,
3984
+ dataSource: viewSelect.dataSource,
3985
+ activeViewId: viewSelect.activeViewId,
3986
+ setActiveViewId: viewSelect.setActiveViewId,
3987
+ /*
3988
+ * Surfaced for downstream hooks (e.g. `useKivaDataGallery`) that
3989
+ * need to render their own view picker. The data-grid's built-in
3990
+ * toolbar still uses these internally — exposing them is additive.
3991
+ */
3992
+ gridViewSelectProps,
3993
+ /*
3994
+ * The interactive `<KivaPivotFilterGroup>` strip — same instance
3995
+ * the built-in toolbar renders. Exposed so downstream hooks can
3996
+ * compose their own toolbar layout (e.g. `useKivaDataGallery`
3997
+ * stacks it above the gallery toolbar) without duplicating the pivot
3998
+ * state management. `null` when no `pivotFilters` were configured.
3999
+ */
4000
+ pivotFiltersStrip: pivotFiltersToolbar,
4001
+ isLoading,
4002
+ error,
4003
+ refetch: reload,
4004
+ hasNoViews: viewSelect.hasNoViews
4005
+ };
4006
+ }
4007
+
4008
+ function unwrapItems<TData>(value: Array<TData> | { data: Array<TData> } | unknown): Array<TData> {
4009
+ if (Array.isArray(value)) return value;
4010
+ if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
4011
+ return (value as { data: Array<TData> }).data;
4012
+ }
4013
+
4014
+ return [];
4015
+ }
4016
+
4017
+ /*
4018
+ * Patterns the Kiva items endpoint uses when a requested column is in the
4019
+ * schema metadata but not physically materialized in the table. Two shapes
4020
+ * occur in the wild:
4021
+ * - NestJS validation: `Field 'contact_billed' not found in data source`
4022
+ * - Raw Postgres: `column t0.contact_billed does not exist`
4023
+ * Mirrors the single-record recovery already in `useKivaFormView`.
4024
+ */
4025
+ function extractMissingItemsColumn(error: unknown): string | null {
4026
+ if (!error || typeof error !== 'object') return null;
4027
+
4028
+ const record = error as Record<string, unknown>;
4029
+ const candidates: Array<unknown> = [record.error_description, record.message];
4030
+ const { response } = record;
4031
+
4032
+ if (response && typeof response === 'object') {
4033
+ const { data } = response as Record<string, unknown>;
4034
+
4035
+ if (data && typeof data === 'object') {
4036
+ candidates.push(
4037
+ (data as Record<string, unknown>).error_description,
4038
+ (data as Record<string, unknown>).message
4039
+ );
4040
+ }
4041
+ }
4042
+
4043
+ for (const candidate of candidates) {
4044
+ const name = extractUnservableColumnName(candidate);
4045
+
4046
+ if (name) return name;
4047
+ }
4048
+
4049
+ return null;
4050
+ }
4051
+
4052
+ /*
4053
+ * Apply a consumer-supplied label translator to a column's display label.
4054
+ * Translates the string `header` and `meta.label` (the two places the header
4055
+ * text surfaces across the grid, fields menu, filter menu, and export). A
4056
+ * non-string `header` (a custom render function / JSX) is left untouched.
4057
+ */
4058
+ function translateColumnHeader<TData>(
4059
+ column: ColumnDef<TData>,
4060
+ translate: (label: string) => string
4061
+ ): ColumnDef<TData> {
4062
+ const header = typeof column.header === 'string' ? translate(column.header) : column.header;
4063
+ const metaLabel = typeof column.meta?.label === 'string' ? translate(column.meta.label) : column.meta?.label;
4064
+
4065
+ const headerChanged = header !== column.header;
4066
+ const labelChanged = metaLabel !== column.meta?.label;
4067
+
4068
+ if (!headerChanged && !labelChanged) return column;
4069
+
4070
+ return {
4071
+ ...column,
4072
+ ...(headerChanged ? { header } : {}),
4073
+ ...(labelChanged ? { meta: { ...column.meta, label: metaLabel } } : {})
4074
+ } as ColumnDef<TData>;
4075
+ }
4076
+
4077
+ /*
4078
+ * Return a shallow clone of a data source field whose enum options have had
4079
+ * their display label (`name`) run through the consumer's translator. Matches
4080
+ * each raw `enums` entry to its normalized `EnumOption` by `id`, so `slug` /
4081
+ * `color` / `icon` and every other option property are preserved. Returns the
4082
+ * original field untouched when it has no enums or nothing changed.
4083
+ */
4084
+ function translateFieldEnumOptions(
4085
+ field: DataSourceField,
4086
+ translate: (option: EnumOption, field: IField) => string
4087
+ ): DataSourceField {
4088
+ const raw = field as unknown as Record<string, unknown>;
4089
+
4090
+ if (!Array.isArray(raw.enums) || raw.enums.length === 0) return field;
4091
+
4092
+ const iField = toIField(field);
4093
+ const options = extractEnumOptions(field);
4094
+
4095
+ if (options.length === 0) return field;
4096
+
4097
+ const nameById = new Map<string, string>();
4098
+
4099
+ for (const option of options) {
4100
+ const next = translate(option, iField);
4101
+
4102
+ if (typeof next === 'string' && next !== option.name) nameById.set(option.id, next);
4103
+ }
4104
+
4105
+ if (nameById.size === 0) return field;
4106
+
4107
+ const nextEnums = raw.enums.map((entry) => {
4108
+ if (!entry || typeof entry !== 'object') return entry;
4109
+
4110
+ const option = entry as Record<string, unknown>;
4111
+ const id = typeof option.id === 'string' ? option.id : undefined;
4112
+
4113
+ return id && nameById.has(id) ? { ...option, name: nameById.get(id) } : entry;
4114
+ });
4115
+
4116
+ return { ...raw, enums: nextEnums } as unknown as DataSourceField;
4117
+ }
4118
+
4119
+ /*
4120
+ * Remove a top-level column token from a comma-joined columns string, leaving
4121
+ * relation sub-columns (`task(id, name, …)`) intact. Splits on depth-0 commas
4122
+ * so a phantom scalar like `contact_billed` is dropped without corrupting the
4123
+ * parenthesised relation groups. Returns the original string when nothing
4124
+ * matched (so the caller can stop retrying).
4125
+ */
4126
+ function stripColumnFromColumnsParam(columns: string, slug: string): string {
4127
+ const tokens: Array<string> = [];
4128
+ let depth = 0;
4129
+ let current = '';
4130
+
4131
+ for (const char of columns) {
4132
+ if (char === '(') depth += 1;
4133
+ else if (char === ')') depth = Math.max(0, depth - 1);
4134
+
4135
+ if (char === ',' && depth === 0) {
4136
+ tokens.push(current);
4137
+ current = '';
4138
+ continue;
4139
+ }
4140
+
4141
+ current += char;
4142
+ }
4143
+
4144
+ if (current.length > 0) tokens.push(current);
4145
+
4146
+ /*
4147
+ * `matchesUnservableColumn` rather than a plain identifier comparison,
4148
+ * because the server names three different things: the token we sent, the
4149
+ * TABLE a borrowed filter path derived (`rel_matter` for
4150
+ * `rel_matter.project_lead`), or only the INNER field of a nested projection
4151
+ * (`project_lead` for `matter(id, name, project_lead)`). Without the last
4152
+ * one a paren token could not be stripped at all, and an inner field the
4153
+ * target data source no longer has is a hard error that empties the whole
4154
+ * response.
4155
+ */
4156
+ const kept = tokens.filter(token => !matchesUnservableColumn(token, slug));
4157
+
4158
+ if (kept.length === tokens.length) return columns;
4159
+
4160
+ return kept.map(token => token.trim()).filter(Boolean).join(', ');
4161
+ }
4162
+
4163
+ /*
4164
+ * Fetch items, recovering from "column does not exist" failures by stripping
4165
+ * the offending column and retrying. A data source can carry several phantom
4166
+ * companion columns (e.g. `*_billed`) and the backend reports them one at a
4167
+ * time, so we loop — bounded to avoid spinning on an unrelated error.
4168
+ */
4169
+ async function fetchItemsWithColumnRecovery(
4170
+ client: RestApiClient,
4171
+ url: string,
4172
+ params: KivaDataGridListParams
4173
+ ): Promise<unknown> {
4174
+ let activeParams = params;
4175
+
4176
+ for (let attempt = 0; attempt < 12; attempt += 1) {
4177
+ try {
4178
+ return await client.get(url, activeParams as Parameters<typeof client.get>[1]);
4179
+ } catch (error) {
4180
+ const missingColumn = extractMissingItemsColumn(error);
4181
+
4182
+ if (!missingColumn || typeof activeParams.columns !== 'string') throw error;
4183
+
4184
+ const nextColumns = stripColumnFromColumnsParam(activeParams.columns, missingColumn);
4185
+
4186
+ if (nextColumns === activeParams.columns) throw error;
4187
+
4188
+ activeParams = { ...activeParams, columns: nextColumns };
4189
+ }
4190
+ }
4191
+
4192
+ return client.get(url, activeParams as Parameters<typeof client.get>[1]);
4193
+ }
4194
+
4195
+ /**
4196
+ * Pull `meta.total` out of a response when present. The Kiva API only
4197
+ * populates this when the request asks for `fullCount: true` — we send
4198
+ * that automatically whenever standard paging is active so the grid can
4199
+ * compute total pages without having to load every row.
4200
+ */
4201
+ function unwrapTotal(value: unknown): number | undefined {
4202
+ if (!value || typeof value !== 'object') return undefined;
4203
+
4204
+ const { meta } = value as { meta?: unknown };
4205
+
4206
+ if (!meta || typeof meta !== 'object') return undefined;
4207
+
4208
+ const { total } = meta as { total?: unknown };
4209
+
4210
+ return typeof total === 'number' ? total : undefined;
4211
+ }
4212
+
4213
+ /*
4214
+ * ---------------------------------------------------------------------------
4215
+ * List params derivation — turns active view + search + overrides into the
4216
+ * `ZodSelectQueryPayload` shape consumed by the Kiva data-source items
4217
+ * endpoint. See `docs/guides/kiva-api-query-guide.md`.
4218
+ * ---------------------------------------------------------------------------
4219
+ */
4220
+
4221
+ interface BuildListParamsArgs {
4222
+ fields: Array<DataSourceField> | undefined;
4223
+ view: SavedDataGridView | undefined;
4224
+ filterKeyword?: string;
4225
+ defaultLimit: number;
4226
+ override: KivaDataGridListParams | undefined;
4227
+ /**
4228
+ * Slugs that must be present in the resolved column list regardless of the
4229
+ * view's visibility/order. Used to ensure the active row-grouping column
4230
+ * is always fetched even if the user excluded it from the view.
4231
+ */
4232
+ requiredSlugs?: Array<string>;
4233
+ /**
4234
+ * Active pagination state — when supplied, switches the request into
4235
+ * server-paged mode: `limit` / `offset` are derived from this and
4236
+ * `fullCount: true` is added so the response carries `meta.total`.
4237
+ * Undefined means "no remote paging" (virtual-scroll mode); the legacy
4238
+ * behavior of seeding `limit: defaultLimit, offset: 0` still applies.
4239
+ */
4240
+ pagination?: { pageIndex: number; pageSize: number };
4241
+ /**
4242
+ * Toolbar filter state from the DataTableFilter menu. ANDed onto the
4243
+ * saved view's `filterQuery` so server-paged grids refetch when the user
4244
+ * adds a transient filter from the toolbar.
4245
+ */
4246
+ toolbarFilters?: ColumnFiltersState;
4247
+ /**
4248
+ * Optional `RuleGroupType` emitted by the side-panel filter rail. ANDed
4249
+ * onto the saved view filter alongside `toolbarFilters`.
4250
+ */
4251
+ sideFilters?: RuleGroupType | undefined;
4252
+ /**
4253
+ * Filter rules emitted by the integrated pivot filter strips. ANDed onto
4254
+ * the saved view / toolbar / side filter chain so the items query reflects
4255
+ * every active pivot selection.
4256
+ */
4257
+ pivotRules?: Array<PivotFilterRule> | null;
4258
+ /**
4259
+ * Live table sorting (column-header dropdown + Sort menu). Takes precedence
4260
+ * over the saved view's preset sort so the items query's `orderBy` follows
4261
+ * the user's interactive sort on server-paged grids. Falls back to
4262
+ * `view.sorting` when empty.
4263
+ */
4264
+ liveSorting?: SortingState;
4265
+ /**
4266
+ * Per-relation icon source map (see `UseKivaDataGridOptions.relationIconFields`).
4267
+ * Threaded into `buildColumnsParam` so the projection expands from
4268
+ * `<slug>(id, name, autonumber_id)` to
4269
+ * `<slug>(id, name, autonumber_id, <iconFieldSlug>)` for configured relations.
4270
+ */
4271
+ relationIconFields?: Record<string, string>;
4272
+ /**
4273
+ * Borrowed column ids (`<relation>(<field>)`) the user has turned on. Each
4274
+ * one adds its field to that relation's projection group — see
4275
+ * `buildColumnsParam`.
4276
+ */
4277
+ relationColumnIds?: ReadonlyArray<string>;
4278
+ /** Column id → `rel_<relation>/<field>` wire path, from the live catalogue. */
4279
+ relationFilterFieldMap?: Record<string, RelationFilterFieldConfig>;
4280
+ /** Borrowed column ids the catalogue vouches for AND that may be filtered. */
4281
+ filterableRelationColumnIds?: ReadonlySet<string>;
4282
+ }
4283
+
4284
+ function buildListParams(args: BuildListParamsArgs): KivaDataGridListParams {
4285
+ const {
4286
+ fields,
4287
+ view,
4288
+ filterKeyword,
4289
+ defaultLimit,
4290
+ override,
4291
+ requiredSlugs,
4292
+ pagination,
4293
+ toolbarFilters,
4294
+ sideFilters,
4295
+ pivotRules,
4296
+ liveSorting,
4297
+ relationIconFields,
4298
+ relationColumnIds,
4299
+ relationFilterFieldMap,
4300
+ filterableRelationColumnIds
4301
+ } = args;
4302
+
4303
+ const params: KivaDataGridListParams = {};
4304
+
4305
+ const visibleSlugs = fields ? deriveVisibleSlugs(fields, view, requiredSlugs) : [];
4306
+ const columns = buildColumnsParam(fields, view, requiredSlugs, relationIconFields, relationColumnIds);
4307
+
4308
+ if (columns) params.columns = columns;
4309
+
4310
+ /*
4311
+ * Prefer the live table sort (column-header dropdown / Sort menu) over the
4312
+ * saved view's preset. On a server-paged grid the preset alone meant the
4313
+ * server kept returning the view's default order no matter what the user
4314
+ * clicked — only the currently-loaded page could be re-sorted client-side.
4315
+ * Falls back to the view preset when the user hasn't sorted interactively.
4316
+ */
4317
+ const orderBy = buildOrderByParam(
4318
+ liveSorting && liveSorting.length > 0 ? liveSorting : view?.sorting
4319
+ );
4320
+
4321
+ if (orderBy) params.orderBy = orderBy;
4322
+
4323
+ const filters = buildFiltersParam(
4324
+ view?.filterQuery,
4325
+ toolbarFilters,
4326
+ sideFilters,
4327
+ pivotRules,
4328
+ relationFilterFieldMap,
4329
+ filterableRelationColumnIds
4330
+ );
4331
+
4332
+ if (filters) params.filters = filters;
4333
+
4334
+ if (filterKeyword) params.filterKeyword = filterKeyword;
4335
+
4336
+ const expand = buildExpandParam(fields, visibleSlugs);
4337
+
4338
+ if (expand && expand.length > 0) params.expand = expand;
4339
+
4340
+ params.limit = defaultLimit;
4341
+ params.offset = 0;
4342
+
4343
+ if (override) {
4344
+ /*
4345
+ * `override.filters` is AND-merged into the filters built from the
4346
+ * saved view, toolbar, and side filters (instead of replacing them).
4347
+ * Without this merge, callers that inject a filter through
4348
+ * `listParams.filters` (e.g. pivot filters, custom widgets, route-level
4349
+ * scoping) would silently wipe out the user's own toolbar / saved-view
4350
+ * filtering — which was the source of the "pivot + column filter don't
4351
+ * combine" regression.
4352
+ *
4353
+ * Every other field on `override` still overrides as before.
4354
+ */
4355
+ const { filters: overrideFilters, ...overrideRest } = override;
4356
+
4357
+ Object.assign(params, overrideRest);
4358
+
4359
+ if (overrideFilters) {
4360
+ const overrideGroup = overrideFilters as RuleGroupType;
4361
+ const overrideHasRules = Array.isArray(overrideGroup.rules) && overrideGroup.rules.length > 0;
4362
+
4363
+ if (!overrideHasRules) {
4364
+ } else if (!params.filters) {
4365
+ params.filters = overrideFilters;
4366
+ } else {
4367
+ const existing = params.filters as RuleGroupType;
4368
+
4369
+ params.filters = {
4370
+ combinator: 'and',
4371
+ rules: [...(Array.isArray(existing.rules) ? existing.rules : []), ...overrideGroup.rules]
4372
+ } as RuleGroupType;
4373
+ }
4374
+ }
4375
+ }
4376
+
4377
+ /*
4378
+ * Pagination state wins over both `defaultLimit` and caller-supplied
4379
+ * `override.limit/offset` — once the user is on page N of a paginated
4380
+ * view, that's the source of truth for what the request should fetch.
4381
+ * `fullCount: true` instructs the API to populate `meta.total` so the
4382
+ * grid footer can show "X of N" and compute the page count without
4383
+ * having to load every record.
4384
+ */
4385
+ if (pagination) {
4386
+ params.limit = pagination.pageSize;
4387
+ params.offset = pagination.pageIndex * pagination.pageSize;
4388
+ params.fullCount = true;
4389
+ }
4390
+
4391
+ return params;
4392
+ }
4393
+
4394
+ function buildColumnsParam(
4395
+ fields: Array<DataSourceField> | undefined,
4396
+ view: SavedDataGridView | undefined,
4397
+ requiredSlugs: Array<string> | undefined,
4398
+ relationIconFields?: Record<string, string>,
4399
+ relationColumnIds?: ReadonlyArray<string>
4400
+ ): string | undefined {
4401
+ if (!fields || fields.length === 0) return undefined;
4402
+
4403
+ const visibleSlugs = deriveVisibleSlugs(fields, view, requiredSlugs);
4404
+
4405
+ if (visibleSlugs.length === 0) return undefined;
4406
+
4407
+ /*
4408
+ * Relation fields need an explicit projection so the API includes
4409
+ * `autonumber_id` alongside `{ id, name }`. Without it the default
4410
+ * `expand=<slug>` shape only returns `{ id, name }` and the cell can't
4411
+ * render the "Show autonumber" prefix even when the user enables the
4412
+ * toggle. The projection is always requested — autonumber is cheap and
4413
+ * keeps the toggle responsive (no refetch on each flip).
4414
+ *
4415
+ * When the caller wires `relationIconFields` for a given relation slug
4416
+ * (mapping that slug to an icon-/image-typed field slug on the **related**
4417
+ * data source), the projection grows to include that field too so
4418
+ * `RelationCell` can prefix the name with the related record's icon /
4419
+ * logo without a follow-up fetch.
4420
+ */
4421
+ const relationSlugs = new Set(
4422
+ fields
4423
+ .filter(field => field.type === 'field-relation')
4424
+ .map(field => field.slug)
4425
+ );
4426
+
4427
+ /*
4428
+ * Borrowed fields are folded INTO their relation's existing paren group, one
4429
+ * group per relation. MEASURED: naming a relation in two tokens returns HTTP
4430
+ * 200 with only the LAST token honoured, so `matter(id, name)` next to
4431
+ * `matter(matter_type)` silently drops `row.matter.{id,name}` and blanks the
4432
+ * Matter column while the borrowed one works.
4433
+ */
4434
+ const borrowedByRelation = new Map<string, Array<string>>();
4435
+
4436
+ for (const id of relationColumnIds ?? []) {
4437
+ const parsed = parseRelationColumnId(id);
4438
+
4439
+ if (!parsed || !relationSlugs.has(parsed.relationSlug)) continue;
4440
+
4441
+ const borrowed = borrowedByRelation.get(parsed.relationSlug) ?? [];
4442
+
4443
+ if (!borrowed.includes(parsed.fieldSlug)) borrowed.push(parsed.fieldSlug);
4444
+ borrowedByRelation.set(parsed.relationSlug, borrowed);
4445
+ }
4446
+
4447
+ const slugs = ['id', ...visibleSlugs.filter(slug => slug !== 'id')];
4448
+
4449
+ /*
4450
+ * A relation that is only reached through a borrowed column still has to be
4451
+ * projected in its own right. Without it the row carries `{ matter_type: … }`
4452
+ * with no identity — a shape no other row in the grid has — and the token
4453
+ * would not pick up the `id, name` every relation cell expects.
4454
+ */
4455
+ for (const relationSlug of borrowedByRelation.keys()) {
4456
+ if (!slugs.includes(relationSlug)) slugs.push(relationSlug);
4457
+ }
4458
+
4459
+ const projected = slugs.map((slug) => {
4460
+ if (!relationSlugs.has(slug)) return slug;
4461
+
4462
+ const iconFieldSlug = relationIconFields?.[slug];
4463
+ const extras: Array<string> = ['id', 'name', 'autonumber_id'];
4464
+
4465
+ if (typeof iconFieldSlug === 'string' && iconFieldSlug.length > 0 && !extras.includes(iconFieldSlug)) {
4466
+ extras.push(iconFieldSlug);
4467
+ }
4468
+
4469
+ for (const fieldSlug of borrowedByRelation.get(slug) ?? []) {
4470
+ if (!extras.includes(fieldSlug)) extras.push(fieldSlug);
4471
+ }
4472
+
4473
+ return `${slug}(${extras.join(', ')})`;
4474
+ });
4475
+
4476
+ return projected.join(', ');
4477
+ }
4478
+
4479
+ /**
4480
+ * Field types whose stored value is an ID reference — fetching the related
4481
+ * record (user, enum option, related row, …) requires explicitly expanding
4482
+ * the field. Any field of one of these types whose slug is visible in the
4483
+ * current request is added to `expand` so the API resolves the reference.
4484
+ */
4485
+ const EXPANDABLE_FIELD_TYPES = new Set<string>([
4486
+ 'field-userSelect',
4487
+ 'field-userMultiSelect',
4488
+ 'field-relation',
4489
+ 'field-relatedField',
4490
+ 'field-select',
4491
+ 'field-radioGroup',
4492
+ 'field-enum',
4493
+ 'field-systemEnum',
4494
+ 'field-multiSelect',
4495
+ 'field-tagSelect',
4496
+ 'field-status',
4497
+ 'field-approvalStatus'
4498
+ ]);
4499
+
4500
+ function buildExpandParam(
4501
+ fields: Array<DataSourceField> | undefined,
4502
+ visibleSlugs: Array<string>
4503
+ ): Array<string> | undefined {
4504
+ if (!fields || fields.length === 0 || visibleSlugs.length === 0) return undefined;
4505
+
4506
+ const visible = new Set(visibleSlugs);
4507
+
4508
+ return fields
4509
+ .filter(field => visible.has(field.slug) && EXPANDABLE_FIELD_TYPES.has(field.type))
4510
+ .map(field => field.slug);
4511
+ }
4512
+
4513
+ /**
4514
+ * Resolve the active view into the ordered list of field slugs that should be
4515
+ * fetched + rendered. Honors the explicit whitelist semantics used by saved
4516
+ * views: when `columnOrder` is non-empty, it acts as the whitelist (in order);
4517
+ * otherwise the visibility map's `true` entries are the whitelist. With no
4518
+ * explicit config, all fields are visible.
4519
+ *
4520
+ * `requiredSlugs` are appended (deduped) so the active row-grouping column
4521
+ * is always part of the resolved list — otherwise grouping by a column that
4522
+ * the user excluded from the view would silently fail.
4523
+ */
4524
+ function deriveVisibleSlugs(
4525
+ fields: Array<DataSourceField>,
4526
+ view: SavedDataGridView | undefined,
4527
+ requiredSlugs?: Array<string>
4528
+ ): Array<string> {
4529
+ const allSlugs = fields.map(field => field.slug);
4530
+ const fieldSlugSet = new Set(allSlugs);
4531
+ const required = (requiredSlugs ?? []).filter(slug => fieldSlugSet.has(slug));
4532
+
4533
+ let visible: Array<string>;
4534
+
4535
+ if (!view) {
4536
+ visible = allSlugs;
4537
+ } else {
4538
+ const visibility = view.columnVisibility ?? {};
4539
+ const order = view.columnOrder ?? [];
4540
+
4541
+ if (order.length > 0) {
4542
+ visible = order.filter(slug => fieldSlugSet.has(slug) && visibility[slug] !== false);
4543
+ } else if (Object.keys(visibility).length > 0) {
4544
+ visible = allSlugs.filter(slug => visibility[slug] === true);
4545
+ } else {
4546
+ visible = allSlugs;
4547
+ }
4548
+ }
4549
+
4550
+ if (required.length === 0) return visible;
4551
+
4552
+ const seen = new Set(visible);
4553
+ const result = [...visible];
4554
+
4555
+ for (const slug of required) {
4556
+ if (!seen.has(slug)) {
4557
+ seen.add(slug);
4558
+ result.push(slug);
4559
+ }
4560
+ }
4561
+
4562
+ return result;
4563
+ }
4564
+
4565
+ function buildEnhancedVisibility(
4566
+ fields: Array<DataSourceField>,
4567
+ view: SavedDataGridView,
4568
+ requiredSlugs?: Array<string>
4569
+ ): Record<string, boolean> {
4570
+ const visibleSet = new Set(deriveVisibleSlugs(fields, view, requiredSlugs));
4571
+ const map: Record<string, boolean> = {};
4572
+
4573
+ for (const field of fields) {
4574
+ map[field.slug] = visibleSet.has(field.slug);
4575
+ }
4576
+
4577
+ return map;
4578
+ }
4579
+
4580
+ /**
4581
+ * The request's `orderBy`.
4582
+ *
4583
+ * A borrowed column forces the STRING form. MEASURED: the backend parses a sort
4584
+ * direction from INSIDE the paren group and silently ignores one placed after
4585
+ * it, so `matter(project_lead) desc` sorts ascending forever while the header
4586
+ * still shows a descending arrow — and the `{ field, direction }` object form
4587
+ * has nowhere else to put it. Sorts with no borrowed column keep the object
4588
+ * form untouched.
4589
+ */
4590
+ function buildOrderByParam(
4591
+ sorting: Array<ColumnSort> | undefined
4592
+ ): Array<{ field: string; direction: 'asc' | 'desc' }> | string | undefined {
4593
+ if (!sorting || sorting.length === 0) return undefined;
4594
+
4595
+ if (!sorting.some(sort => parseRelationColumnId(sort.id) !== null)) {
4596
+ return sorting.map(sort => ({
4597
+ field: sort.id,
4598
+ direction: sort.desc ? 'desc' : 'asc'
4599
+ }));
4600
+ }
4601
+
4602
+ const tokens = sorting
4603
+ .map(sort => (parseRelationColumnId(sort.id) !== null ? buildRelationSortToken(sort.id, Boolean(sort.desc)) : `${sort.id} ${sort.desc ? 'desc' : 'asc'}`))
4604
+ .filter((token): token is string => Boolean(token));
4605
+
4606
+ return tokens.length > 0 ? tokens.join(', ') : undefined;
4607
+ }
4608
+
4609
+ /*
4610
+ * Query Builder stores filter rules with UI-only keys (`id`, `valueSource`)
4611
+ * and display operator labels ("is one of", "is none of") that the backend's
4612
+ * ZodQueryFilterRule schema rejects (strict object + FILTER_OPERATORS enum).
4613
+ * Map every QB display operator to its canonical backend token here.
4614
+ */
4615
+ /**
4616
+ * Strip QB-only fields recursively. Operator translation and the drop pass for
4617
+ * catalog operators the endpoint cannot express are NOT done here — callers run
4618
+ * `normalizeFilterOperators` first, so this is purely about the rule SHAPE.
4619
+ */
4620
+ function stripViewFilterGroupShape(group: RuleGroupType): RuleGroupType {
4621
+ const normalizedRules = (group.rules ?? []).map((rule) => {
4622
+ if ('rules' in rule && Array.isArray((rule as RuleGroupType).rules)) {
4623
+ return stripViewFilterGroupShape(rule as RuleGroupType);
4624
+ }
4625
+
4626
+ const r = rule as unknown as Record<string, unknown>;
4627
+
4628
+ const cleaned: Record<string, unknown> = { operator: r['operator'] };
4629
+
4630
+ for (const key of [
4631
+ 'field',
4632
+ 'value',
4633
+ 'valueField',
4634
+ 'filterType'
4635
+ ] as const) {
4636
+ if (key in r) cleaned[key] = r[key];
4637
+ }
4638
+
4639
+ return cleaned;
4640
+ });
4641
+
4642
+ const result: Record<string, unknown> = {
4643
+ combinator: group.combinator,
4644
+ rules: normalizedRules
4645
+ };
4646
+
4647
+ if ('not' in group) result['not'] = (group as unknown as Record<string, unknown>)['not'];
4648
+
4649
+ return result as unknown as RuleGroupType;
4650
+ }
4651
+
4652
+ /**
4653
+ * The request's `filters`: the saved view's own filter, the toolbar's column
4654
+ * filters, the side filters and the pivot rules, ANDed.
4655
+ *
4656
+ * The toolbar rules are where a filter on a BORROWED column becomes a wire
4657
+ * path, and two guards ride along:
4658
+ *
4659
+ * 1. `relationFilterFieldMap` rewrites the column id `matter(matter_type)`
4660
+ * into `rel_matter/matter_type`. Those are two different grammars — the
4661
+ * projection one and the filter one — and sending the wrong one is not a
4662
+ * quiet failure: the backend's identifier validation rejects the
4663
+ * parentheses and 400s the whole request, taking the base columns with it.
4664
+ * 2. `keepEmittableRelationFilters` drops a relation filter whose operator
4665
+ * could UNDER-REPORT, and one whose column the live catalogue no longer
4666
+ * vouches for. Both arrive without passing through the filter menu:
4667
+ * `columnFilters` is rehydrated from the saved view and from persisted
4668
+ * state, so an operator chosen before the whitelist existed, or a field
4669
+ * that exists on one tenant and not the next, is already in state.
4670
+ *
4671
+ * The saved view's own `filterQuery` keeps its FIELDS untouched, deliberately.
4672
+ * It may contain a relation path written by the legacy app (dot-spelled, and
4673
+ * possibly negated); rewriting or dropping part of a tenant's saved view would
4674
+ * change what that view has meant for years without anyone asking.
4675
+ */
4676
+ function buildFiltersParam(
4677
+ filterQuery: SavedDataGridView['filterQuery'],
4678
+ toolbarFilters?: ColumnFiltersState,
4679
+ sideFilters?: RuleGroupType | undefined,
4680
+ pivotRules?: Array<PivotFilterRule> | null,
4681
+ relationFilterFieldMap?: Record<string, RelationFilterFieldConfig>,
4682
+ filterableRelationColumnIds?: ReadonlySet<string>
4683
+ ): RuleGroupType | undefined {
4684
+ const rawViewFilter = filterQuery && 'rules' in filterQuery && Array.isArray(filterQuery.rules) && filterQuery.rules.length > 0 ? (filterQuery as RuleGroupType) : undefined;
4685
+ /*
4686
+ * The query-builder catalog offers operators the list endpoint has never
4687
+ * implemented, and a saved view is where they survive: `normalizeFilterOperators`
4688
+ * rewrites the ones with a server equivalent (`is one of` → `in`,
4689
+ * `contains` → `contains any`) and DROPS the ones without (`weekday_is`,
4690
+ * `time_is`, `json_key_*`, …). Passing one through 400s the ENTIRE request —
4691
+ * one bad leaf blanks the whole grid, valid rules included — so dropping it
4692
+ * (which only widens the result set) is the safer failure.
4693
+ *
4694
+ * Emptiness is re-tested AFTER the drop pass: a view whose only rules were
4695
+ * unsupported normalizes to an empty group, which must not reach the wire.
4696
+ */
4697
+ const normalizedViewFilter = rawViewFilter ? normalizeFilterOperators(rawViewFilter) : undefined;
4698
+ const viewFilter = normalizedViewFilter && normalizedViewFilter.rules.length > 0 ? stripViewFilterGroupShape(normalizedViewFilter) : undefined;
4699
+
4700
+ /*
4701
+ * The toolbar's advanced filter group. It rides in `toolbarFilters` under a
4702
+ * reserved id so it inherits view reset, session restore and the persisted
4703
+ * state diff for free, and is stripped here before the per-column rules are
4704
+ * built — it is a GROUP, not a per-column filter.
4705
+ */
4706
+ const emittableAdvancedFilter = readEmittableAdvancedFilterGroup(toolbarFilters);
4707
+ /*
4708
+ * Through the SAME normalizer the saved view's filter goes through, and for
4709
+ * the same reason: both are authored by the query builder, whose rules carry
4710
+ * RQB-only keys (`id`, `valueSource`) that the endpoint's strict rule schema
4711
+ * rejects — one such key 400s the whole request. `readEmittableAdvancedFilterGroup`
4712
+ * has already done the operator translation and the drop pass; this strips the
4713
+ * shape.
4714
+ */
4715
+ const advancedFilter = emittableAdvancedFilter ? stripViewFilterGroupShape(emittableAdvancedFilter) : undefined;
4716
+
4717
+ const toolbarRules = keepEmittableRelationFilters(
4718
+ withoutAdvancedFilter(toolbarFilters),
4719
+ filterableRelationColumnIds
4720
+ )
4721
+ .map(filter => toServerRule(filter, relationFilterFieldMap))
4722
+ .filter((rule): rule is { field: string; operator: string; value?: unknown } => Boolean(rule));
4723
+
4724
+ const sideRule = sideFilters && Array.isArray(sideFilters.rules) && sideFilters.rules.length > 0 ? sideFilters : undefined;
4725
+ const pivotRuleList = pivotRules ?? [];
4726
+
4727
+ const groupCount = (viewFilter ? 1 : 0) + (sideRule ? 1 : 0) + (advancedFilter ? 1 : 0);
4728
+ const flatRuleCount = toolbarRules.length + pivotRuleList.length;
4729
+
4730
+ if (groupCount === 0 && flatRuleCount === 0) return undefined;
4731
+ if (groupCount === 1 && flatRuleCount === 0) {
4732
+ return (viewFilter ?? sideRule ?? advancedFilter) as RuleGroupType;
4733
+ }
4734
+ if (groupCount === 0) {
4735
+ return {
4736
+ combinator: 'and',
4737
+ rules: [...toolbarRules, ...pivotRuleList]
4738
+ } as RuleGroupType;
4739
+ }
4740
+
4741
+ const rules: Array<RuleGroupType | { field: string; operator: string; value?: unknown }> = [];
4742
+
4743
+ if (viewFilter) rules.push(viewFilter);
4744
+ if (sideRule) rules.push(sideRule);
4745
+ if (advancedFilter) rules.push(advancedFilter);
4746
+ for (const r of toolbarRules) rules.push(r);
4747
+ for (const r of pivotRuleList) rules.push(r);
4748
+
4749
+ return { combinator: 'and', rules } as RuleGroupType;
4750
+ }