@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,543 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import { useMemo } from 'react';
6
+
7
+ import { type RestApiClient } from '@kivacore/api-client';
8
+ import { useQuery } from '@tanstack/react-query';
9
+
10
+ import {
11
+ usePivotGrid
12
+ } from '@kivacore/ui-pro-shared/components/kiva/pivot-grid/hooks/use-pivot-grid';
13
+ import {
14
+ type PivotGridAggregate,
15
+ type PivotGridCellColorRule,
16
+ type PivotGridController,
17
+ type PivotGridDimension,
18
+ type PivotGridDrilldown,
19
+ type PivotGridMeasure,
20
+ type PivotGridState
21
+ } from '@kivacore/ui-pro-shared/components/kiva/pivot-grid/types';
22
+
23
+ /* ------------------------------------------------------------------------- */
24
+ /* Public types */
25
+ /* ------------------------------------------------------------------------- */
26
+
27
+ export type { PivotGridAggregate };
28
+
29
+ export type PivotRow = Record<string, unknown>;
30
+
31
+ /**
32
+ * Aggregation mode.
33
+ *
34
+ * - `'client'` (default) — fetches raw records and aggregates in the browser
35
+ * via `usePivotGrid`. Simple to set up; not suitable for large datasets.
36
+ *
37
+ * - `'server'` — sends a `pivot.matrix` + `calculations` payload to the
38
+ * Kiva items endpoint so the database does the aggregation. Returns one
39
+ * row per dimension combination; scales to any dataset size.
40
+ */
41
+ export type KivaPivotGridMode = 'client' | 'server';
42
+
43
+ /**
44
+ * Thin descriptor for a pivot dimension backed by a Kiva field.
45
+ */
46
+ export interface KivaPivotGridDimension<TData = PivotRow> {
47
+ /** Unique id used internally by usePivotGrid. */
48
+ id: string;
49
+ /** Visible label rendered in headers. */
50
+ label: string;
51
+ /**
52
+ * Field slug on the data source (e.g. `'record_owner'`, `'date'`).
53
+ */
54
+ field: string;
55
+ /**
56
+ * Sub-field for relation fields (e.g. `'name'` for `record_owner.name`).
57
+ * In client mode: used to resolve nested/flattened API keys.
58
+ * In server mode: used to build the matrix columns expression.
59
+ */
60
+ subField?: string;
61
+ /**
62
+ * Date format string for server mode (Postgres `to_char` token).
63
+ * Set this when the field is a date and you want server-side bucketing.
64
+ * E.g. `'YYYY-MM'` for monthly, `'YYYY'` for yearly.
65
+ * When set the matrix entry uses `to_char[format]@field` syntax.
66
+ */
67
+ dateFormat?: string;
68
+ /**
69
+ * Required when `dateFormat` is set (server mode).
70
+ * Passed verbatim to the pivot matrix `dateRange` — the backend uses
71
+ * `generate_series(min, max, interval)` to build the date axis.
72
+ * `interval` examples: `'day'`, `'week'`, `'month'`, `'year'`.
73
+ */
74
+ dateRange?: {
75
+ interval: string;
76
+ increment?: number;
77
+ min: string;
78
+ max: string;
79
+ };
80
+ /**
81
+ * Custom value extractor. Takes precedence over automatic derivation.
82
+ * In server mode the hook generates a simple identity accessor from the
83
+ * server alias — only set this when you need custom transformation logic.
84
+ */
85
+ getValue?: (row: TData) => unknown;
86
+ formatValue?: (value: unknown) => string;
87
+ sort?: (a: unknown, b: unknown) => number;
88
+ emptyLabel?: string;
89
+ }
90
+
91
+ /** Measure backed by a Kiva field. */
92
+ export interface KivaPivotGridMeasure<TData = PivotRow> {
93
+ /** Unique id — also used as the server-side calculation alias. */
94
+ id: string;
95
+ /** Visible label. */
96
+ label: string;
97
+ /**
98
+ * Field slug to aggregate over. Use `'id'` for `count`.
99
+ */
100
+ field: string;
101
+ /** Aggregation function. */
102
+ aggregate: PivotGridAggregate;
103
+ /** Optional transform applied after reading the value (e.g. seconds → hours). */
104
+ transform?: (value: number) => number;
105
+ /** Custom value extractor — takes precedence over `field` accessor. */
106
+ getValue?: (row: TData) => number | null | undefined;
107
+ formatValue?: (value: number) => string;
108
+ }
109
+
110
+ export interface UseKivaPivotGridOptions<TData = PivotRow> {
111
+ client: RestApiClient;
112
+ appSlug: string;
113
+ dataSourceSlug: string;
114
+
115
+ /**
116
+ * Aggregation mode. Defaults to `'client'`.
117
+ *
118
+ * Use `'server'` for large datasets — the database aggregates and only
119
+ * summary rows are transferred over the wire.
120
+ */
121
+ mode?: KivaPivotGridMode;
122
+
123
+ /** Row grouping dimensions (outermost → innermost). */
124
+ rowDimensions: Array<KivaPivotGridDimension<TData>>;
125
+ /** Column grouping dimensions (outermost → innermost). */
126
+ columnDimensions: Array<KivaPivotGridDimension<TData>>;
127
+ /** Measures to aggregate and display in each pivot cell. */
128
+ measures: Array<KivaPivotGridMeasure<TData>>;
129
+
130
+ /**
131
+ * `columns` expression forwarded to the items endpoint.
132
+ *
133
+ * - `'client'` mode: fetched as-is (auto-derived when omitted).
134
+ * - `'server'` mode: used as the main-query columns alongside the pivot
135
+ * payload (auto-derived from relation dimensions when omitted).
136
+ */
137
+ columns?: string;
138
+ /** Server-side filters forwarded verbatim to the items endpoint. */
139
+ filters?: unknown;
140
+ /** `orderBy` expression (client mode only — server mode ignores this). */
141
+ orderBy?: string;
142
+ /** Maximum records to fetch. Client mode only. Defaults to 5000. */
143
+ limit?: number;
144
+
145
+ /** Stable row identifier extractor passed to usePivotGrid. */
146
+ getRowId?: (row: TData, index: number) => string;
147
+ /** Initial expand/pin/size state forwarded to usePivotGrid. */
148
+ initialState?: Partial<PivotGridState>;
149
+ /** Formula-based cell colour rules forwarded to usePivotGrid. */
150
+ cellColorRules?: Array<PivotGridCellColorRule>;
151
+ /** Drilldown configuration forwarded to usePivotGrid. */
152
+ drilldown?: PivotGridDrilldown<TData>;
153
+ /** Grid height in pixels or `'auto'`. Defaults to 600. */
154
+ height?: number | 'auto';
155
+ className?: string;
156
+
157
+ /** Enable/disable the query. Defaults to `true`. */
158
+ enabled?: boolean;
159
+ /** TanStack Query staleTime in ms. Defaults to 30 s. */
160
+ staleTime?: number;
161
+ }
162
+
163
+ export interface UseKivaPivotGridResult<TData = PivotRow> {
164
+ /** Pass to `<PivotGridView controller={controller} />`. */
165
+ controller: PivotGridController<TData>;
166
+ /** Items returned by the API (raw records in client mode, aggregated rows in server mode). */
167
+ items: Array<TData>;
168
+ isLoading: boolean;
169
+ isFetching: boolean;
170
+ error: Error | null;
171
+ refetch: () => void;
172
+ }
173
+
174
+ /* ------------------------------------------------------------------------- */
175
+ /* Client-mode helpers */
176
+ /* ------------------------------------------------------------------------- */
177
+
178
+ function buildClientColumns<TData>(
179
+ rowDimensions: Array<KivaPivotGridDimension<TData>>,
180
+ columnDimensions: Array<KivaPivotGridDimension<TData>>,
181
+ measures: Array<KivaPivotGridMeasure<TData>>
182
+ ): string {
183
+ const parts: Array<string> = ['id'];
184
+
185
+ for (const dim of [...rowDimensions, ...columnDimensions]) {
186
+ if (dim.subField) {
187
+ parts.push(`...${dim.field}(${dim.subField})`);
188
+ } else {
189
+ parts.push(dim.field);
190
+ }
191
+ }
192
+
193
+ for (const m of measures) {
194
+ if (m.field !== 'id') parts.push(m.field);
195
+ }
196
+
197
+ return [...new Set(parts)].join(', ');
198
+ }
199
+
200
+ function resolveValue<TData>(
201
+ row: TData,
202
+ field: string,
203
+ subField?: string
204
+ ): unknown {
205
+ const record = row as Record<string, unknown>;
206
+
207
+ if (subField) {
208
+ const dotKey = `${field}.${subField}`;
209
+
210
+ if (dotKey in record) return record[dotKey];
211
+
212
+ const nested = record[field];
213
+
214
+ if (nested != null && typeof nested === 'object') {
215
+ return (nested as Record<string, unknown>)[subField];
216
+ }
217
+
218
+ return null;
219
+ }
220
+
221
+ return record[field] ?? null;
222
+ }
223
+
224
+ function toPivotGridDimension<TData>(
225
+ dim: KivaPivotGridDimension<TData>,
226
+ serverAlias?: string
227
+ ): PivotGridDimension<TData> {
228
+ const alias = serverAlias ?? dim.id;
229
+
230
+ return {
231
+ id: dim.id,
232
+ label: dim.label,
233
+ getValue: dim.getValue
234
+ ?? (serverAlias ? (row: TData) => (row as Record<string, unknown>)[alias] ?? null : (row: TData) => resolveValue(row, dim.field, dim.subField)),
235
+ formatValue: dim.formatValue,
236
+ sort: dim.sort,
237
+ emptyLabel: dim.emptyLabel
238
+ };
239
+ }
240
+
241
+ function toPivotGridMeasure<TData>(
242
+ m: KivaPivotGridMeasure<TData>,
243
+ serverAlias?: string
244
+ ): PivotGridMeasure<TData> {
245
+ const { transform } = m;
246
+
247
+ const baseGetValue: (row: TData) => number | null | undefined = serverAlias ? (row: TData) => {
248
+ const raw = (row as Record<string, unknown>)[serverAlias];
249
+
250
+ if (raw == null) return null;
251
+ const num = typeof raw === 'number' ? raw : Number(raw);
252
+
253
+ return Number.isFinite(num) ? num : null;
254
+ } : (row: TData) => {
255
+ const raw = resolveValue(row, m.field);
256
+
257
+ if (raw == null) return null;
258
+ const num = typeof raw === 'number' ? raw : Number(raw);
259
+
260
+ return Number.isFinite(num) ? num : null;
261
+ };
262
+
263
+ function withTransform(row: TData): number | null | undefined {
264
+ if (!transform) return baseGetValue(row);
265
+ const v = baseGetValue(row);
266
+
267
+ return v == null ? null : transform(v);
268
+ }
269
+
270
+ const getValue: (row: TData) => number | null | undefined = m.getValue ?? withTransform;
271
+
272
+ return {
273
+ id: m.id,
274
+ label: m.label,
275
+ aggregate: m.aggregate,
276
+ getValue,
277
+ formatValue: m.formatValue
278
+ };
279
+ }
280
+
281
+ /* ------------------------------------------------------------------------- */
282
+ /* Server-mode helpers */
283
+ /* ------------------------------------------------------------------------- */
284
+
285
+ interface MatrixEntry {
286
+ using: string;
287
+ columns: string;
288
+ spread: boolean;
289
+ dateRange?: {
290
+ interval: string;
291
+ increment?: number;
292
+ min: string;
293
+ max: string;
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Derives a stable server alias for a dimension.
299
+ * Uses the dimension's `id` prefixed with `dim_` to avoid collisions with
300
+ * measure aliases or reserved API keys.
301
+ */
302
+ type DimBase = {
303
+ id: string;
304
+ field: string;
305
+ subField?: string;
306
+ dateFormat?: string;
307
+ dateRange?: {
308
+ interval: string;
309
+ increment?: number;
310
+ min: string;
311
+ max: string;
312
+ };
313
+ };
314
+
315
+ function dimAlias(dim: DimBase): string {
316
+ return `dim_${dim.id}`;
317
+ }
318
+
319
+ function buildMatrixEntry(dim: DimBase): MatrixEntry {
320
+ const alias = dimAlias(dim);
321
+
322
+ if (dim.dateFormat) {
323
+ return {
324
+ using: dim.field,
325
+ columns: `${alias}:to_char[${dim.dateFormat}]@${dim.field}`,
326
+ spread: true,
327
+ ...(dim.dateRange ? { dateRange: dim.dateRange } : {})
328
+ };
329
+ }
330
+
331
+ if (dim.subField) {
332
+ return {
333
+ using: dim.field,
334
+ columns: `${alias}:${dim.subField}`,
335
+ spread: true
336
+ };
337
+ }
338
+
339
+ return {
340
+ using: dim.field,
341
+ columns: `${alias}:${dim.field}`,
342
+ spread: true
343
+ };
344
+ }
345
+
346
+ function buildServerPayload<TData>(
347
+ rowDimensions: Array<KivaPivotGridDimension<TData>>,
348
+ columnDimensions: Array<KivaPivotGridDimension<TData>>,
349
+ measures: Array<KivaPivotGridMeasure<TData>>,
350
+ columns: string | undefined,
351
+ filters: unknown
352
+ ): Record<string, unknown> {
353
+ const allDimensions = [...rowDimensions, ...columnDimensions];
354
+ const matrix = allDimensions.map(buildMatrixEntry);
355
+
356
+ const calculations = measures.map(m => ({
357
+ field: m.field,
358
+ func: m.aggregate,
359
+ name: m.id
360
+ }));
361
+
362
+ const autoColumns = 'id';
363
+
364
+ return {
365
+ columns: columns?.trim() || autoColumns,
366
+ ...(filters ? { filters } : {}),
367
+ pivot: { matrix },
368
+ calculations
369
+ };
370
+ }
371
+
372
+ /* ------------------------------------------------------------------------- */
373
+ /* Hook */
374
+ /* ------------------------------------------------------------------------- */
375
+
376
+ export function useKivaPivotGrid<TData = PivotRow>(
377
+ options: UseKivaPivotGridOptions<TData>
378
+ ): UseKivaPivotGridResult<TData> {
379
+ const {
380
+ client,
381
+ appSlug,
382
+ dataSourceSlug,
383
+ mode = 'client',
384
+ rowDimensions,
385
+ columnDimensions,
386
+ measures,
387
+ columns,
388
+ filters,
389
+ orderBy,
390
+ limit = 5000,
391
+ getRowId,
392
+ initialState,
393
+ cellColorRules,
394
+ drilldown,
395
+ height = 600,
396
+ className,
397
+ enabled = true,
398
+ staleTime = 30_000
399
+ } = options;
400
+
401
+ /* ----- build query payload (differs by mode) ----- */
402
+
403
+ const clientColumnsExpression = useMemo(
404
+ () => columns?.trim() || buildClientColumns(rowDimensions, columnDimensions, measures),
405
+ [
406
+ columns,
407
+ rowDimensions,
408
+ columnDimensions,
409
+ measures
410
+ ]
411
+ );
412
+
413
+ const clientPayload = useMemo(() => ({
414
+ columns: clientColumnsExpression,
415
+ ...(filters ? { filters } : {}),
416
+ ...(orderBy ? { orderBy } : {}),
417
+ limit
418
+ }), [
419
+ clientColumnsExpression,
420
+ filters,
421
+ orderBy,
422
+ limit
423
+ ]);
424
+
425
+ const serverPayload = useMemo(
426
+ () => buildServerPayload(rowDimensions, columnDimensions, measures, columns, filters),
427
+ [
428
+ rowDimensions,
429
+ columnDimensions,
430
+ measures,
431
+ columns,
432
+ filters
433
+ ]
434
+ );
435
+
436
+ const payload = mode === 'server' ? serverPayload : clientPayload;
437
+
438
+ /* ----- fetch ----- */
439
+
440
+ const queryKey = useMemo(
441
+ () => [
442
+ 'kiva',
443
+ 'pivot-grid',
444
+ mode,
445
+ appSlug,
446
+ dataSourceSlug,
447
+ payload
448
+ ],
449
+ [
450
+ mode,
451
+ appSlug,
452
+ dataSourceSlug,
453
+ payload
454
+ ]
455
+ );
456
+
457
+ const query = useQuery<Array<TData>>({
458
+ queryKey,
459
+ queryFn: async () => {
460
+ const response = await client.get<Array<TData> | { data: Array<TData> }>(
461
+ `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items`,
462
+ payload as unknown as Parameters<typeof client.get>[1]
463
+ );
464
+
465
+ if (Array.isArray(response)) return response;
466
+
467
+ if (
468
+ response != null
469
+ && typeof response === 'object'
470
+ && Array.isArray((response as { data?: unknown }).data)
471
+ ) {
472
+ return (response as { data: Array<TData> }).data;
473
+ }
474
+
475
+ return [];
476
+ },
477
+ enabled: enabled && Boolean(client) && Boolean(appSlug) && Boolean(dataSourceSlug),
478
+ staleTime
479
+ });
480
+
481
+ /* ----- map descriptors to usePivotGrid format ----- */
482
+
483
+ const pivotRowDimensions = useMemo(
484
+ () => rowDimensions.map(dim => toPivotGridDimension<TData>(
485
+ dim,
486
+ mode === 'server' ? dimAlias(dim) : undefined
487
+ )),
488
+ [rowDimensions, mode]
489
+ );
490
+
491
+ const pivotColumnDimensions = useMemo(
492
+ () => columnDimensions.map(dim => toPivotGridDimension<TData>(
493
+ dim,
494
+ mode === 'server' ? dimAlias(dim) : undefined
495
+ )),
496
+ [columnDimensions, mode]
497
+ );
498
+
499
+ const pivotMeasures = useMemo(
500
+ () => measures.map(m => toPivotGridMeasure<TData>(
501
+ m,
502
+ mode === 'server' ? m.id : undefined
503
+ )),
504
+ [measures, mode]
505
+ );
506
+
507
+ const items = useMemo(() => query.data ?? [], [query.data]);
508
+
509
+ /* ----- build the pivot controller ----- */
510
+
511
+ const controller = usePivotGrid<TData>({
512
+ data: items,
513
+ rowDimensions: pivotRowDimensions,
514
+ columnDimensions: pivotColumnDimensions,
515
+ measures: pivotMeasures,
516
+ getRowId,
517
+ initialState,
518
+ cellColorRules,
519
+ drilldown,
520
+ height,
521
+ className
522
+ });
523
+
524
+ const {
525
+ isLoading, isFetching, error: queryError, refetch: queryRefetch
526
+ } = query;
527
+
528
+ return useMemo(() => ({
529
+ controller,
530
+ items,
531
+ isLoading,
532
+ isFetching,
533
+ error: (queryError as Error | null) ?? null,
534
+ refetch: () => { queryRefetch(); }
535
+ }), [
536
+ controller,
537
+ items,
538
+ isLoading,
539
+ isFetching,
540
+ queryError,
541
+ queryRefetch
542
+ ]);
543
+ }