@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,759 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import {
6
+ useCallback,
7
+ useMemo,
8
+ useState
9
+ } from 'react';
10
+
11
+ import { type RestApiClient } from '@kivacore/api-client';
12
+ import { useQuery } from '@tanstack/react-query';
13
+
14
+ import {
15
+ type IPivotCalendarCellClick,
16
+ type IPivotCalendarGroup,
17
+ type IPivotCalendarMeasure,
18
+ type IPivotCalendarRemoteCell,
19
+ type PivotCalendarProps,
20
+ type TPivotCalendarAggregate,
21
+ type TPivotCalendarView
22
+ } from '@kivacore/ui-pro-shared/components/kiva/pivot-calendar';
23
+
24
+ import {
25
+ buildPersistKey,
26
+ resolvePersistConfig,
27
+ useParameterPersistence,
28
+ type PersistStateProp
29
+ } from './use-parameter-persistence';
30
+
31
+ /* ------------------------------------------------------------------------- */
32
+ /* Types */
33
+ /* ------------------------------------------------------------------------- */
34
+
35
+ export interface KivaPivotMeasure {
36
+ /** Stable id used to match cells back to the measure. */
37
+ id: string;
38
+ /** Visible label. */
39
+ label: string;
40
+ /** Compact label rendered in the header. Defaults to `label`. */
41
+ shortLabel?: string;
42
+ /** Field slug to aggregate over. Use `'id'` for `count`. */
43
+ field: string;
44
+ /** Aggregation function. */
45
+ func: TPivotCalendarAggregate;
46
+ /** Optional transform applied after the API returns the value (e.g. `seconds → hours`). */
47
+ transform?: (value: number) => number;
48
+ /** Format function used to render values inside cells. */
49
+ formatValue?: (value: number) => string;
50
+ /** Color accent used in headers/dots. */
51
+ color?: string;
52
+ /** Tooltip description. */
53
+ description?: string;
54
+ }
55
+
56
+ export interface KivaPivotGroupBy {
57
+ /** Field slug of the grouping relation/select. */
58
+ field: string;
59
+ /** Visible label rendered in the side panel and pivot row header. */
60
+ label: string;
61
+ /**
62
+ * Subfield expression used inside the matrix `columns` to label groups.
63
+ * Defaults to `'name'` (e.g. for user/relation fields). The hook joins it
64
+ * as `groupLabel:<labelField>`.
65
+ */
66
+ labelField?: string;
67
+ /**
68
+ * Subfield used to expose the relation's primary key in the matrix CTE.
69
+ * Defaults to `'id'`, but some relations (notably `record_owner` /
70
+ * users) require a different column — pass `'user_id'` for those.
71
+ * Aliasing the relation's actual join key (e.g. plain `id`) breaks the
72
+ * matrix CROSS JOIN, so this MUST be a non-join column on the related
73
+ * data source. The hook joins it as `groupId:<idField>` and uses the
74
+ * resolved value to filter the drilldown query directly via
75
+ * `<field> = <uuid>` instead of `rel_<field>/<labelField>`.
76
+ */
77
+ idField?: string;
78
+ /** Optional filters applied to the group dimension's CTE (e.g. only active users). */
79
+ filters?: unknown;
80
+ /**
81
+ * Optional override that returns the avatar/colour shown in the sidebar/row
82
+ * header for a group. Receives the row from the pivot result.
83
+ */
84
+ toGroup?: (row: PivotRow) => Partial<IPivotCalendarGroup>;
85
+ }
86
+
87
+ export type PivotRow = Record<string, unknown>;
88
+
89
+ export interface UseKivaPivotCalendarOptions {
90
+ client: RestApiClient;
91
+ appSlug: string;
92
+ dataSourceSlug: string;
93
+ /** Date field on the data source (e.g. `created_on`, `due_date`). */
94
+ dateField: string;
95
+ /** Measures to aggregate and display. Up to 2 are rendered per cell. */
96
+ measures: Array<KivaPivotMeasure>;
97
+ /** Optional grouping dimension. */
98
+ groupBy?: KivaPivotGroupBy;
99
+ /**
100
+ * Extra `columns` segment to merge into the request (e.g. `...record_owner(name)`).
101
+ * The hook always includes the group label spread when `groupBy` is set.
102
+ */
103
+ columns?: string;
104
+ /** Filters applied to the main query (the records being aggregated). */
105
+ filters?: unknown;
106
+ /** Initial view. Defaults to `'month-calendar'`. */
107
+ defaultView?: TPivotCalendarView;
108
+ /** Controlled view. */
109
+ view?: TPivotCalendarView;
110
+ /** Called when view changes. */
111
+ onViewChange?: (view: TPivotCalendarView) => void;
112
+ /** Initial reference date. Defaults to today. */
113
+ defaultDate?: Date;
114
+ /** Controlled reference date. */
115
+ date?: Date;
116
+ /** Called when reference date changes. */
117
+ onDateChange?: (date: Date) => void;
118
+ /** Pass-through for the resulting PivotCalendar. */
119
+ hideViewSwitcher?: boolean;
120
+ hideSidebar?: boolean;
121
+ visibleViews?: Array<TPivotCalendarView>;
122
+ /** TanStack Query knobs. */
123
+ enabled?: boolean;
124
+ staleTime?: number;
125
+ /** When `false`, send `pivot.hideEmptyRows: true`. Defaults to `false` (keep empty cells). */
126
+ showEmptyCells?: boolean;
127
+ /**
128
+ * Fires when the user clicks a stat tile or value cell. The `info` argument
129
+ * is the same `IPivotCalendarCellClick` emitted by `<PivotCalendar>`. Use
130
+ * `buildDrilldownQuery` from the hook's return value to convert it into
131
+ * Kiva query parameters (filters/columns/orderBy).
132
+ */
133
+ onCellClick?: (info: IPivotCalendarCellClick<PivotRow>) => void;
134
+ /**
135
+ * Persist the user's manually-selected view granularity + focused date to
136
+ * storage and restore them on the next mount. Only the uncontrolled pieces
137
+ * are persisted (controlled `view` / `date` props always win).
138
+ *
139
+ * `true` → session storage. Pass `{ storage: 'local' }` to survive restarts,
140
+ * or `{ key: '…' }` to override the data-source segment of the storage key.
141
+ */
142
+ persistState?: PersistStateProp;
143
+ }
144
+
145
+ /** Serializable snapshot of the pivot calendar's user-editable parameters. */
146
+ interface PivotCalendarPersistSnapshot {
147
+ view?: TPivotCalendarView;
148
+ /** Focused date as an ISO string. */
149
+ date?: string;
150
+ }
151
+
152
+ export interface KivaPivotFilterRule {
153
+ field: string;
154
+ operator: string;
155
+ value?: unknown;
156
+ }
157
+
158
+ export interface KivaPivotFilterGroup {
159
+ combinator: 'and' | 'or';
160
+ rules: Array<KivaPivotFilterRule | KivaPivotFilterGroup>;
161
+ }
162
+
163
+ export interface KivaPivotDrilldownQuery {
164
+ /** App slug — pass to `useKivaDataGrid`. */
165
+ appSlug: string;
166
+ /** Data source slug — pass to `useKivaDataGrid`. */
167
+ dataSourceSlug: string;
168
+ /** Date field that produced the bucket. */
169
+ dateField: string;
170
+ /** Group field slug, when `groupBy` is configured. */
171
+ groupField?: string;
172
+ /** The clicked group's display label (used as the filter value). */
173
+ groupLabel?: string | null;
174
+ /** Date range that the bucket represents. */
175
+ bucketStart: Date;
176
+ bucketEnd: Date;
177
+ /** ISO-formatted strings of the bucket range — handy for filter values. */
178
+ bucketStartIso: string;
179
+ bucketEndIso: string;
180
+ /** Field slug used for the clicked measure. */
181
+ measureField: string;
182
+ /** Aggregate function for the clicked measure. */
183
+ measureFunc: TPivotCalendarAggregate;
184
+ /** Measure descriptor (for label/format reuse in the dialog). */
185
+ measure: IPivotCalendarMeasure<PivotRow>;
186
+ /** Raw aggregated value before formatting. */
187
+ measureValue: number;
188
+ /** Pre-formatted value (e.g. `1.5h`). */
189
+ measureFormatted: string;
190
+ /**
191
+ * Filter group ready to send to `GET /v1/apps/.../items` (or to compose
192
+ * with caller-side filters in `useKivaDataGrid`).
193
+ */
194
+ filters: KivaPivotFilterGroup;
195
+ /** Suggested `columns` selection for the drilldown query. */
196
+ columns: string;
197
+ /** Suggested `orderBy` for the drilldown query (newest first by date). */
198
+ orderBy: string;
199
+ }
200
+
201
+ export interface UseKivaPivotCalendarResult<TData = PivotRow> {
202
+ /** Props ready to spread on `<PivotCalendar {...pivotCalendarProps} />`. */
203
+ pivotCalendarProps: PivotCalendarProps<TData>;
204
+ cells: Array<IPivotCalendarRemoteCell>;
205
+ groups: Array<IPivotCalendarGroup>;
206
+ measures: Array<IPivotCalendarMeasure<TData>>;
207
+ view: TPivotCalendarView;
208
+ setView: (view: TPivotCalendarView) => void;
209
+ selectedDate: Date;
210
+ setSelectedDate: (date: Date) => void;
211
+ isLoading: boolean;
212
+ error: Error | null;
213
+ refetch: () => void;
214
+ /**
215
+ * Converts a click event into the query parameters needed to fetch the
216
+ * underlying records (date range filter + group filter + caller filters).
217
+ * Use it inside `onCellClick` to drive a drilldown dialog.
218
+ */
219
+ buildDrilldownQuery: (info: IPivotCalendarCellClick<TData>) => KivaPivotDrilldownQuery;
220
+ }
221
+
222
+ /* ------------------------------------------------------------------------- */
223
+ /* Helpers */
224
+ /* ------------------------------------------------------------------------- */
225
+
226
+ function startOfDay(d: Date): Date {
227
+ const x = new Date(d);
228
+
229
+ x.setHours(0, 0, 0, 0);
230
+
231
+ return x;
232
+ }
233
+
234
+ function endOfDay(d: Date): Date {
235
+ const x = new Date(d);
236
+
237
+ x.setHours(23, 59, 59, 999);
238
+
239
+ return x;
240
+ }
241
+
242
+ function startOfMonth(d: Date): Date {
243
+ const x = new Date(d.getFullYear(), d.getMonth(), 1, 0, 0, 0, 0);
244
+
245
+ return x;
246
+ }
247
+
248
+ function endOfMonth(d: Date): Date {
249
+ const x = new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59, 999);
250
+
251
+ return x;
252
+ }
253
+
254
+ function startOfWeek(d: Date): Date {
255
+ const x = new Date(d);
256
+ const day = x.getDay();
257
+
258
+ x.setDate(x.getDate() - day);
259
+ x.setHours(0, 0, 0, 0);
260
+
261
+ return x;
262
+ }
263
+
264
+ function endOfWeek(d: Date): Date {
265
+ const x = startOfWeek(d);
266
+
267
+ x.setDate(x.getDate() + 6);
268
+ x.setHours(23, 59, 59, 999);
269
+
270
+ return x;
271
+ }
272
+
273
+ function startOfYear(d: Date): Date {
274
+ return new Date(d.getFullYear(), 0, 1, 0, 0, 0, 0);
275
+ }
276
+
277
+ function endOfYear(d: Date): Date {
278
+ return new Date(d.getFullYear(), 11, 31, 23, 59, 59, 999);
279
+ }
280
+
281
+ function getRangeForView(
282
+ reference: Date,
283
+ view: TPivotCalendarView
284
+ ): { start: Date; end: Date; interval: 'day' | 'month' } {
285
+ switch (view) {
286
+ case 'days-of-week':
287
+ return { start: startOfWeek(reference), end: endOfWeek(reference), interval: 'day' };
288
+
289
+ case 'months-of-year':
290
+ return { start: startOfYear(reference), end: endOfYear(reference), interval: 'month' };
291
+
292
+ case 'days-of-month':
293
+
294
+ case 'month-calendar':
295
+
296
+ default: {
297
+ /*
298
+ * For month-calendar we widen to the rendered grid so we cover prev/next month leak,
299
+ * but we still aggregate per day. Simpler: use month bounds.
300
+ */
301
+ const start = startOfMonth(reference);
302
+ const end = endOfMonth(reference);
303
+
304
+ return { start: startOfDay(start), end: endOfDay(end), interval: 'day' };
305
+ }
306
+ }
307
+ }
308
+
309
+ function bucketFormatToken(view: TPivotCalendarView): string {
310
+ return view === 'months-of-year' ? 'YYYY-MM' : 'YYYY-MM-DD';
311
+ }
312
+
313
+ /* ------------------------------------------------------------------------- */
314
+ /* Hook */
315
+ /* ------------------------------------------------------------------------- */
316
+
317
+ const DEFAULT_VIEW: TPivotCalendarView = 'month-calendar';
318
+
319
+ export function useKivaPivotCalendar<TData = PivotRow>(
320
+ options: UseKivaPivotCalendarOptions
321
+ ): UseKivaPivotCalendarResult<TData> {
322
+ const {
323
+ client,
324
+ appSlug,
325
+ dataSourceSlug,
326
+ dateField,
327
+ measures,
328
+ groupBy,
329
+ columns,
330
+ filters,
331
+ defaultView = DEFAULT_VIEW,
332
+ view: controlledView,
333
+ onViewChange,
334
+ defaultDate,
335
+ date: controlledDate,
336
+ onDateChange,
337
+ hideViewSwitcher,
338
+ hideSidebar,
339
+ visibleViews,
340
+ enabled = true,
341
+ staleTime = 30_000,
342
+ showEmptyCells = true,
343
+ onCellClick,
344
+ persistState
345
+ } = options;
346
+
347
+ const persistConfig = resolvePersistConfig(persistState);
348
+ const persistStorage = persistConfig?.storage ?? 'session';
349
+ const persistKeyOverride = persistConfig?.key ?? '';
350
+
351
+ /* ----- view + date state ----- */
352
+
353
+ const [internalView, setInternalView] = useState<TPivotCalendarView>(defaultView);
354
+ const view = controlledView ?? internalView;
355
+ const setView = useCallback((next: TPivotCalendarView) => {
356
+ if (controlledView === undefined) setInternalView(next);
357
+ onViewChange?.(next);
358
+ }, [controlledView, onViewChange]);
359
+
360
+ const [internalDate, setInternalDate] = useState<Date>(() => defaultDate ?? new Date());
361
+ const selectedDate = controlledDate ?? internalDate;
362
+ const setSelectedDate = useCallback((next: Date) => {
363
+ if (controlledDate === undefined) setInternalDate(next);
364
+ onDateChange?.(next);
365
+ }, [controlledDate, onDateChange]);
366
+
367
+ /*
368
+ * ── View-parameter persistence ────────────────────────────────────────
369
+ * Persist the uncontrolled view granularity + focused date. Controlled
370
+ * `view` / `date` props always win, so only the internal pieces persist.
371
+ */
372
+ const persistView = persistConfig !== null && controlledView === undefined;
373
+ const persistDate = persistConfig !== null && controlledDate === undefined;
374
+ const persistEnabled = persistView || persistDate;
375
+
376
+ const persistStorageKey = useMemo(() => {
377
+ if (!persistEnabled) return null;
378
+
379
+ const dataSourceSegment = persistKeyOverride || `${appSlug}:${dataSourceSlug}`;
380
+
381
+ return buildPersistKey([dataSourceSegment, 'pivot-calendar']);
382
+ }, [
383
+ persistEnabled,
384
+ persistKeyOverride,
385
+ appSlug,
386
+ dataSourceSlug
387
+ ]);
388
+
389
+ const persistSnapshot = useMemo<PivotCalendarPersistSnapshot>(() => ({
390
+ ...(persistView ? { view } : {}),
391
+ ...(persistDate ? { date: selectedDate.toISOString() } : {})
392
+ }), [
393
+ persistView,
394
+ persistDate,
395
+ view,
396
+ selectedDate
397
+ ]);
398
+
399
+ const restorePersistedParams = useCallback((restored: Partial<PivotCalendarPersistSnapshot>) => {
400
+ if (persistView && restored.view) setInternalView(restored.view);
401
+ if (persistDate && typeof restored.date === 'string') {
402
+ const parsed = new Date(restored.date);
403
+
404
+ if (!Number.isNaN(parsed.getTime())) setInternalDate(parsed);
405
+ }
406
+ }, [persistView, persistDate]);
407
+
408
+ useParameterPersistence<PivotCalendarPersistSnapshot>({
409
+ enabled: persistEnabled,
410
+ storage: persistStorage,
411
+ storageKey: persistStorageKey,
412
+ ready: persistEnabled,
413
+ snapshot: persistSnapshot,
414
+ onRestore: restorePersistedParams
415
+ });
416
+
417
+ /* ----- payload ----- */
418
+
419
+ const limitedMeasures = useMemo(() => measures.slice(0, 2), [measures]);
420
+
421
+ const payload = useMemo(() => {
422
+ const range = getRangeForView(selectedDate, view);
423
+ const labelField = groupBy?.labelField ?? 'name';
424
+ const idField = groupBy?.idField;
425
+ const formatToken = bucketFormatToken(view);
426
+
427
+ type MatrixEntry = {
428
+ using: string;
429
+ columns: string;
430
+ spread?: boolean;
431
+ filters?: unknown;
432
+ dateRange?: {
433
+ interval: 'day' | 'week' | 'month' | 'year';
434
+ min: string;
435
+ max: string;
436
+ };
437
+ };
438
+
439
+ const matrix: Array<MatrixEntry> = [
440
+ {
441
+ using: dateField,
442
+ columns: `bucket:to_char[${formatToken}]@${dateField}`,
443
+ spread: true,
444
+ dateRange: {
445
+ interval: range.interval,
446
+ min: range.start.toISOString(),
447
+ max: range.end.toISOString()
448
+ }
449
+ }
450
+ ];
451
+
452
+ if (groupBy) {
453
+ /*
454
+ * The relation matrix's primary-key column (the one that joins the
455
+ * CTE to the main query) is implicit — aliasing it breaks the SQL.
456
+ * When `idField` is supplied (e.g. `'user_id'` for users) we surface
457
+ * a different non-join column as the stable group identifier. When
458
+ * absent, the displayed label doubles as the group key.
459
+ */
460
+ const matrixColumns = idField ? `groupLabel:${labelField}, groupId:${idField}` : `groupLabel:${labelField}`;
461
+
462
+ matrix.push({
463
+ using: groupBy.field,
464
+ columns: matrixColumns,
465
+ spread: true,
466
+ ...(groupBy.filters ? { filters: groupBy.filters } : {})
467
+ });
468
+ }
469
+
470
+ const calculations = limitedMeasures.map(m => ({
471
+ field: m.field,
472
+ func: m.func,
473
+ name: m.id
474
+ }));
475
+
476
+ /*
477
+ * The API rejects empty `columns`. With pivot+calculations, plain main-
478
+ * query columns become extra GROUP BY keys (which breaks aggregation),
479
+ * so we send a relation spread when possible — it groups by the relation
480
+ * id without surfacing a per-record key. Falls back to a caller-provided
481
+ * `columns` if supplied.
482
+ */
483
+ const callerColumns = columns?.trim() ?? '';
484
+ const requestColumns = callerColumns.length > 0 ? callerColumns : (groupBy ? `...${groupBy.field}(${labelField})` : 'id');
485
+
486
+ return {
487
+ columns: requestColumns,
488
+ ...(filters ? { filters } : {}),
489
+ pivot: {
490
+ matrix,
491
+ ...(showEmptyCells ? {} : { hideEmptyRows: true })
492
+ },
493
+ calculations
494
+ } as Record<string, unknown>;
495
+ }, [
496
+ selectedDate,
497
+ view,
498
+ dateField,
499
+ groupBy,
500
+ columns,
501
+ filters,
502
+ limitedMeasures,
503
+ showEmptyCells
504
+ ]);
505
+
506
+ /* ----- query ----- */
507
+
508
+ const queryKey = useMemo(() => [
509
+ 'kiva',
510
+ 'pivot-calendar',
511
+ appSlug,
512
+ dataSourceSlug,
513
+ view,
514
+ selectedDate.toISOString(),
515
+ payload
516
+ ], [
517
+ appSlug,
518
+ dataSourceSlug,
519
+ view,
520
+ selectedDate,
521
+ payload
522
+ ]);
523
+
524
+ const query = useQuery<Array<PivotRow>>({
525
+ queryKey,
526
+ queryFn: async () => {
527
+ const response = await client.get<Array<PivotRow> | { data: Array<PivotRow> }>(
528
+ `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items`,
529
+ payload as Parameters<typeof client.get>[1]
530
+ );
531
+
532
+ if (Array.isArray(response)) return response;
533
+ if (response && typeof response === 'object' && Array.isArray((response as { data?: unknown }).data)) {
534
+ return (response as { data: Array<PivotRow> }).data;
535
+ }
536
+
537
+ return [];
538
+ },
539
+ enabled: enabled && Boolean(client) && Boolean(dataSourceSlug) && Boolean(appSlug),
540
+ staleTime
541
+ });
542
+
543
+ /* ----- map response → cells + groups ----- */
544
+
545
+ const { cells, groups } = useMemo(() => {
546
+ const rows = query.data ?? [];
547
+ const cellOut: Array<IPivotCalendarRemoteCell> = [];
548
+ const groupMap = new Map<string, IPivotCalendarGroup>();
549
+
550
+ for (const row of rows) {
551
+ const bucketRaw = row.bucket;
552
+
553
+ if (typeof bucketRaw !== 'string' || bucketRaw.length === 0) continue;
554
+
555
+ let groupId: string | null = null;
556
+
557
+ if (groupBy) {
558
+ const labelRaw = row.groupLabel;
559
+ const labelString = typeof labelRaw === 'string' && labelRaw.length > 0 ? labelRaw : null;
560
+ const idRaw = row.groupId;
561
+ const idString = idRaw == null ? null : typeof idRaw === 'string' && idRaw.length > 0 ? idRaw : String(idRaw);
562
+
563
+ /*
564
+ * Prefer the matrix's id column (when `idField` was supplied, e.g.
565
+ * `user_id`) so drilldown filters can use the stable UUID. Fall
566
+ * back to the display label when only `labelField` is exposed.
567
+ */
568
+ groupId = idString ?? labelString;
569
+
570
+ if (groupId) {
571
+ const existing = groupMap.get(groupId);
572
+ const overrides = groupBy.toGroup?.(row) ?? {};
573
+
574
+ if (!existing) {
575
+ groupMap.set(groupId, {
576
+ id: groupId,
577
+ label: labelString ?? groupId,
578
+ ...overrides
579
+ });
580
+ }
581
+ }
582
+ }
583
+
584
+ const values = limitedMeasures
585
+ .map((m) => {
586
+ const raw = row[m.id];
587
+
588
+ if (raw == null) return null;
589
+ const num = typeof raw === 'number' ? raw : Number(raw);
590
+
591
+ if (!Number.isFinite(num)) return null;
592
+ const final = m.transform ? m.transform(num) : num;
593
+
594
+ return { measureId: m.id, value: final };
595
+ })
596
+ .filter((v): v is { measureId: string; value: number } => v !== null);
597
+
598
+ if (values.length === 0) continue;
599
+
600
+ cellOut.push({
601
+ bucket: bucketRaw,
602
+ ...(groupBy ? { groupId } : {}),
603
+ values
604
+ });
605
+ }
606
+
607
+ const groupList = Array.from(groupMap.values()).sort((a, b) => a.label.localeCompare(b.label));
608
+
609
+ return { cells: cellOut, groups: groupList };
610
+ }, [query.data, groupBy, limitedMeasures]);
611
+
612
+ /* ----- measures for the component ----- */
613
+
614
+ const componentMeasures = useMemo<Array<IPivotCalendarMeasure<TData>>>(() => limitedMeasures.map(m => ({
615
+ id: m.id,
616
+ label: m.label,
617
+ shortLabel: m.shortLabel,
618
+ aggregate: m.func,
619
+ color: m.color,
620
+ description: m.description,
621
+ formatValue: m.formatValue
622
+ })), [limitedMeasures]);
623
+
624
+ /* ----- result ----- */
625
+
626
+ /* ----- drilldown query builder ----- */
627
+
628
+ const buildDrilldownQuery = useCallback(
629
+ (info: IPivotCalendarCellClick<TData>): KivaPivotDrilldownQuery => {
630
+ const labelField = groupBy?.labelField ?? 'name';
631
+ const idField = groupBy?.idField;
632
+ const callerFilters = filters as KivaPivotFilterGroup | undefined;
633
+
634
+ const rules: Array<KivaPivotFilterRule | KivaPivotFilterGroup> = [
635
+ {
636
+ field: dateField,
637
+ operator: 'between',
638
+ value: [info.bucketStart.toISOString(), info.bucketEnd.toISOString()]
639
+ }
640
+ ];
641
+
642
+ if (groupBy && info.groupId) {
643
+ /*
644
+ * When `idField` is set the matrix surfaces the relation's stable
645
+ * key (e.g. `user_id` for users), so we filter the main query by
646
+ * the relation field directly: `<groupBy.field> = <uuid>`. Without
647
+ * `idField`, fall back to the relation's display label via the
648
+ * Kiva `rel_<field>/<subfield>` syntax.
649
+ */
650
+ rules.push(idField ? {
651
+ field: groupBy.field,
652
+ operator: '=',
653
+ value: info.groupId
654
+ } : {
655
+ field: `rel_${groupBy.field}/${labelField}`,
656
+ operator: '=',
657
+ value: info.groupId
658
+ });
659
+ }
660
+
661
+ const merged: KivaPivotFilterGroup = callerFilters ? { combinator: 'and', rules: [callerFilters, ...rules] } : { combinator: 'and', rules };
662
+
663
+ const measureSource = limitedMeasures.find(m => m.id === info.measure.id);
664
+ const measureField = measureSource?.field ?? info.measure.id;
665
+ const measureFunc = measureSource?.func ?? info.measure.aggregate;
666
+
667
+ const drillColumns = columns?.trim().length ? columns.trim() : groupBy ? `id, ${dateField}, ${measureField}, ...${groupBy.field}(${labelField})` : `id, ${dateField}, ${measureField}`;
668
+
669
+ return {
670
+ appSlug,
671
+ dataSourceSlug,
672
+ dateField,
673
+ groupField: groupBy?.field,
674
+ groupLabel: info.group?.label ?? info.groupId ?? null,
675
+ bucketStart: info.bucketStart,
676
+ bucketEnd: info.bucketEnd,
677
+ bucketStartIso: info.bucketStart.toISOString(),
678
+ bucketEndIso: info.bucketEnd.toISOString(),
679
+ measureField,
680
+ measureFunc,
681
+ measure: info.measure as IPivotCalendarMeasure<PivotRow>,
682
+ measureValue: info.value,
683
+ measureFormatted: info.formattedValue,
684
+ filters: merged,
685
+ columns: drillColumns,
686
+ orderBy: `${dateField} DESC`
687
+ };
688
+ },
689
+ [
690
+ appSlug,
691
+ dataSourceSlug,
692
+ dateField,
693
+ groupBy,
694
+ filters,
695
+ columns,
696
+ limitedMeasures
697
+ ]
698
+ );
699
+
700
+ /* ----- onCellClick adapter (PivotRow → TData passthrough) ----- */
701
+
702
+ const handleCellClick = useMemo<((info: IPivotCalendarCellClick<TData>) => void) | undefined>(() => {
703
+ if (!onCellClick) return undefined;
704
+
705
+ return info => onCellClick(info as IPivotCalendarCellClick<PivotRow>);
706
+ }, [onCellClick]);
707
+
708
+ const pivotCalendarProps: PivotCalendarProps<TData> = useMemo(() => ({
709
+ mode: 'remote',
710
+ cells,
711
+ groups,
712
+ measures: componentMeasures,
713
+ ...(groupBy ? {
714
+ groupBy: {
715
+ id: groupBy.field,
716
+ label: groupBy.label,
717
+ getId: () => null
718
+ }
719
+ } : {}),
720
+ view,
721
+ onViewChange: setView,
722
+ date: selectedDate,
723
+ onDateChange: setSelectedDate,
724
+ hideViewSwitcher,
725
+ hideSidebar,
726
+ visibleViews,
727
+ onCellClick: handleCellClick
728
+ }), [
729
+ cells,
730
+ groups,
731
+ componentMeasures,
732
+ groupBy,
733
+ view,
734
+ setView,
735
+ selectedDate,
736
+ setSelectedDate,
737
+ hideViewSwitcher,
738
+ hideSidebar,
739
+ visibleViews,
740
+ handleCellClick
741
+ ]);
742
+
743
+ return {
744
+ pivotCalendarProps,
745
+ cells,
746
+ groups,
747
+ measures: componentMeasures,
748
+ view,
749
+ setView,
750
+ selectedDate,
751
+ setSelectedDate,
752
+ isLoading: query.isLoading,
753
+ error: (query.error as Error | null) ?? null,
754
+ refetch: () => {
755
+ query.refetch();
756
+ },
757
+ buildDrilldownQuery
758
+ };
759
+ }