@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,1750 @@
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 DataSourceField } from '@kivacore/app-utils';
15
+ import { type UniqueIdentifier } from '@dnd-kit/core';
16
+ import {
17
+ keepPreviousData,
18
+ useMutation,
19
+ useQuery,
20
+ useQueryClient
21
+ } from '@tanstack/react-query';
22
+ import {
23
+ Loader2,
24
+ RotateCw,
25
+ Search
26
+ } from 'lucide-react';
27
+ import { type RuleGroupType } from 'react-querybuilder';
28
+
29
+ import {
30
+ KanbanBoard,
31
+ KanbanColumn,
32
+ KanbanFinalColumn,
33
+ KanbanFinalZone,
34
+ KanbanItem,
35
+ KanbanOverlay
36
+ } from '@kivacore/ui-pro-shared/components/kiva/kanban';
37
+ import {
38
+ RecordDeleteConfirmDialog
39
+ } from '@kivacore/ui-pro-shared/components/kiva/record-delete-confirm-dialog';
40
+ import { Button } from '@kivacore/ui-pro-shared/components/button';
41
+
42
+ import { Input } from '@kivacore/ui-pro-shared/components/input';
43
+ import { Label } from '@kivacore/ui-pro-shared/components/label';
44
+ import {
45
+ Select,
46
+ SelectContent,
47
+ SelectItem,
48
+ SelectTrigger,
49
+ SelectValue
50
+ } from '@kivacore/ui-pro-shared/components/select';
51
+ import { Switch } from '@kivacore/ui-pro-shared/components/switch';
52
+ import {
53
+ TooltipProvider
54
+ } from '@kivacore/ui-pro-shared/components/tooltip';
55
+ import { cn } from '@kivacore/ui-pro-shared/lib/utils';
56
+
57
+ import {
58
+ KanbanCard,
59
+ KanbanColumnAccent,
60
+ KanbanColumnHeader,
61
+ KanbanEmpty,
62
+ KanbanRootGeneric
63
+ } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-kiva-kanban-cards';
64
+
65
+ import {
66
+ useKivaDataViewSelect,
67
+ type UseKivaDataViewSelectOptions,
68
+ type UseKivaDataViewSelectResult
69
+ } from './use-kiva-data-view-select';
70
+ import {
71
+ buildPersistKey,
72
+ resolvePersistConfig,
73
+ useParameterPersistence,
74
+ type PersistStateProp
75
+ } from './use-parameter-persistence';
76
+ /*
77
+ * Renderer components live in `_internal/` so they're not picked up by
78
+ * the registry's `library/hooks/` scanner as standalone hooks. Aliased
79
+ * path is required so the `detectInternalFiles` BFS bundles them when a
80
+ * user installs this hook — relative imports inside `library/hooks/` are
81
+ * not followed by the resolver.
82
+ */
83
+
84
+ /* ------------------------------------------------------------------------- */
85
+ /* Types */
86
+ /* ------------------------------------------------------------------------- */
87
+
88
+ const ENUM_GROUP_FIELD_TYPES = new Set<string>(['field-select', 'field-radioGroup', 'field-status']);
89
+
90
+ const DATE_GROUP_FIELD_TYPES = new Set<string>(['field-date', 'field-dateTime']);
91
+
92
+ /*
93
+ * Query-builder filter groups carry QB-only fields (`id`, `valueSource`) and
94
+ * display-operator labels ("is one of", "is none of") that the backend's
95
+ * strict `ZodQueryFilterRule` schema rejects. The data-grid hook normalizes
96
+ * saved-view filters before sending; the kanban must do the same or the
97
+ * backend silently rejects / ignores the view's filtering. Kept module-local
98
+ * (mirrors the data-grid) because the registry generator does not bundle
99
+ * transitive files for hooks.
100
+ */
101
+ const QB_OPERATOR_TO_BACKEND: Record<string, string> = {
102
+ 'is one of': 'in',
103
+ 'is none of': 'not in',
104
+ /*
105
+ * The FOLLOWER group offers a bare `contains`, which the endpoint does not
106
+ * know at all. For a follower / multi-user column `contains any` asks the
107
+ * same question ("does this hold at least one of these?").
108
+ */
109
+ contains: 'contains any'
110
+ };
111
+
112
+ /*
113
+ * Server operators whose value must be an array. A display operator that
114
+ * rewrites into one of these already carried array semantics in the picker, but
115
+ * a rule seeded elsewhere (a legacy view, smart search) can hold a bare scalar
116
+ * and the endpoint rejects that.
117
+ */
118
+ const ARRAY_VALUED_BACKEND_OPERATORS: ReadonlySet<string> = new Set([
119
+ 'in',
120
+ 'not in',
121
+ 'contains any',
122
+ 'contains all',
123
+ 'not contains'
124
+ ]);
125
+
126
+ /*
127
+ * Catalog operators with no server equivalent at all. A rule carrying one is
128
+ * DROPPED rather than sent: the endpoint answers `Invalid input` for the ENTIRE
129
+ * request, so one unsupported leaf in a saved view empties the whole page,
130
+ * valid rules included. Dropping only widens the result set.
131
+ *
132
+ * `is_other_field` / `is_not_other_field` are here for a different reason than
133
+ * the rest: the server does support column-to-column comparison, but as a rule
134
+ * SHAPE (`{ operator: '=', valueField: '<slug>' }`), not as an operator.
135
+ *
136
+ * Mirrors `UNSUPPORTED_DISPLAY_OPERATORS` in
137
+ * `data-grid/lib/filter-operator-normalize.ts` — kept module-local for the same
138
+ * reason as the map above.
139
+ */
140
+ const UNSUPPORTED_BACKEND_OPERATORS: ReadonlySet<string> = new Set([
141
+ 'is_other_field',
142
+ 'is_not_other_field',
143
+ 'weekday_is',
144
+ 'monthday_is',
145
+ 'weekdays',
146
+ 'time_is',
147
+ 'time_greater',
148
+ 'time_greater_or_equals',
149
+ 'time_lower',
150
+ 'time_lower_or_equals',
151
+ 'json_key_is',
152
+ 'json_key_is_not',
153
+ 'json_key_is_empty',
154
+ 'json_key_is_not_empty'
155
+ ]);
156
+
157
+ function normalizeViewFilterGroup(group: RuleGroupType): RuleGroupType {
158
+ const normalizedRules = (group.rules ?? []).map((rule) => {
159
+ if ('rules' in rule && Array.isArray((rule as RuleGroupType).rules)) {
160
+ return normalizeViewFilterGroup(rule as RuleGroupType);
161
+ }
162
+
163
+ const r = rule as unknown as Record<string, unknown>;
164
+ const rawOperator = r['operator'];
165
+
166
+ if (typeof rawOperator === 'string' && UNSUPPORTED_BACKEND_OPERATORS.has(rawOperator)) {
167
+ return null;
168
+ }
169
+
170
+ const operator = typeof rawOperator === 'string' ? (QB_OPERATOR_TO_BACKEND[rawOperator] ?? rawOperator) : rawOperator;
171
+ const cleaned: Record<string, unknown> = { operator };
172
+
173
+ for (const key of [
174
+ 'field',
175
+ 'value',
176
+ 'valueField',
177
+ 'filterType'
178
+ ] as const) {
179
+ if (key in r) cleaned[key] = r[key];
180
+ }
181
+
182
+ if (
183
+ typeof operator === 'string'
184
+ && ARRAY_VALUED_BACKEND_OPERATORS.has(operator)
185
+ && 'value' in cleaned
186
+ && cleaned['value'] !== undefined
187
+ && cleaned['value'] !== null
188
+ && !Array.isArray(cleaned['value'])
189
+ ) {
190
+ cleaned['value'] = [cleaned['value']];
191
+ }
192
+
193
+ return cleaned;
194
+ }).filter((rule): rule is Record<string, unknown> => rule !== null);
195
+
196
+ const result: Record<string, unknown> = {
197
+ combinator: group.combinator,
198
+ rules: normalizedRules
199
+ };
200
+
201
+ if ('not' in group) result['not'] = (group as unknown as Record<string, unknown>)['not'];
202
+
203
+ return result as unknown as RuleGroupType;
204
+ }
205
+
206
+ /** Shape of a TanStack DB collection compatible with the kanban hook. */
207
+ export interface KivaKanbanCollection<TData> {
208
+ list: (params?: Record<string, unknown>) => Promise<Array<TData> | { data: Array<TData> }>;
209
+ /** PATCH `/items/:id` — used when a card is dropped into a different column. */
210
+ update?: (id: string, body: Record<string, unknown>) => Promise<unknown>;
211
+ /** DELETE `/items/:id` — used by the default "Delete" action menu item. */
212
+ remove?: (id: string) => Promise<unknown>;
213
+ }
214
+
215
+ export interface KivaKanbanListParams {
216
+ columns?: string;
217
+ filters?: RuleGroupType | Record<string, unknown>;
218
+ filterKeyword?: string;
219
+ orderBy?: string | { field: string; direction?: 'asc' | 'desc' } | Array<{ field: string; direction?: 'asc' | 'desc' }>;
220
+ limit?: number;
221
+ offset?: number;
222
+ fullCount?: boolean;
223
+ expand?: Array<string>;
224
+ expandTypes?: Array<'user' | 'enum' | 'relation'>;
225
+ [key: string]: unknown;
226
+ }
227
+
228
+ /** Resolved metadata for a single kanban column. */
229
+ export interface KivaKanbanColumnMeta {
230
+ /** Stable column id (enum option id/slug, user/team id, or bucketed date key). */
231
+ id: string;
232
+ /** Display label rendered in the column header. */
233
+ label: string;
234
+ /** Color forwarded from enum options or computed; rendered as the column accent. */
235
+ color?: string | null;
236
+ /** Icon identifier forwarded from enum options. */
237
+ icon?: string | null;
238
+ /** Avatar image (e.g. user photo) — used for user/team grouping. */
239
+ imageUrl?: string | null;
240
+ /** Marks enum options where `is_final_option` / `isFinalOption` is `true`. */
241
+ isFinal?: boolean;
242
+ /** Pre-computed count of items in the column. */
243
+ count: number;
244
+ }
245
+
246
+ /** Built-in card menu actions surfaced by the default `cardMenuItems`. */
247
+ export type KivaKanbanCardAction = 'open' | 'edit' | 'delete';
248
+
249
+ export interface KivaKanbanCardMenuItem<TData> {
250
+ key: string;
251
+ label: ReactNode;
252
+ icon?: ReactNode;
253
+ destructive?: boolean;
254
+ /** Disable the item; called with the row before `onAction` runs. */
255
+ disabled?: boolean | ((row: TData) => boolean);
256
+ onAction?: (row: TData) => void;
257
+ }
258
+
259
+ export interface KivaKanbanCardContext<TData> {
260
+ row: TData;
261
+ column: KivaKanbanColumnMeta;
262
+ }
263
+
264
+ /** Serializable snapshot of the kanban's user-editable parameters. */
265
+ interface KanbanPersistSnapshot {
266
+ searchInput?: string;
267
+ dateGroupBy?: KivaKanbanDateGroupBy;
268
+ userGroupBy?: KivaKanbanUserGroupBy;
269
+ showAllColumns?: boolean;
270
+ }
271
+
272
+ export interface UseKivaKanbanOptions<TData> extends UseKivaDataViewSelectOptions {
273
+ /** Slug of the field whose values become kanban columns. */
274
+ groupByFieldSlug: string;
275
+ /** Pre-resolved rows. When provided, the hook skips its internal items query. */
276
+ data?: Array<TData>;
277
+ /** TanStack DB collection (e.g., `useBaseOrganizationCollection()`). */
278
+ collection?: KivaKanbanCollection<TData>;
279
+ /** Extra query params merged on top of the view-derived payload. */
280
+ listParams?: KivaKanbanListParams;
281
+ /** Default page size when no `limit` is supplied via `listParams`. Default `200`. */
282
+ defaultLimit?: number;
283
+ /** Disable the internal items query. Default `true` when no `data` is provided. */
284
+ enableItemsQuery?: boolean;
285
+ /**
286
+ * Granularity used when grouping by a `field-date` / `field-dateTime` field.
287
+ * Time portion is always ignored. Default `'day'`.
288
+ */
289
+ dateGroupBy?: KivaKanbanDateGroupBy;
290
+ /**
291
+ * Grouping mode used when the group-by field is `field-userSelect`.
292
+ * `'user'` groups one column per user; `'team'` groups by `team_id` /
293
+ * `team` on the user payload. Default `'user'`.
294
+ */
295
+ userGroupBy?: KivaKanbanUserGroupBy;
296
+ /**
297
+ * For enum-backed fields (`field-select`, `field-radioGroup`, `field-status`),
298
+ * controls whether columns are rendered for every enum option or only those
299
+ * with at least one item. Default `true` (show all).
300
+ */
301
+ showAllColumns?: boolean;
302
+
303
+ /* ----------------------------- Card contract ------------------------- */
304
+
305
+ /** Field slug whose `icon`/`color`/`image` value seeds the card avatar. */
306
+ avatarColumn?: string;
307
+ /** Field slug used for the card title (top, large, single-line truncated). */
308
+ titleColumn?: string;
309
+ /** Field slug used for the card description (under the title). */
310
+ descriptionColumn?: string;
311
+ /** Field slug whose user value appears in the card footer (left). */
312
+ userColumn?: string;
313
+ /**
314
+ * Free-form card content rendered between the header and the footer.
315
+ * Receives the raw row + active column metadata.
316
+ */
317
+ cardContent?: (ctx: KivaKanbanCardContext<TData>) => ReactNode;
318
+ /**
319
+ * Override the card action menu (top-right vertical-three-dots). Default
320
+ * surfaces Open, Edit, and Delete entries — wire callbacks via
321
+ * `onCardOpen`, `onCardEdit`, `onCardDelete` to keep the defaults.
322
+ */
323
+ cardMenuItems?:
324
+ | Array<KivaKanbanCardMenuItem<TData>>
325
+ | ((row: TData, defaults: Array<KivaKanbanCardMenuItem<TData>>) => Array<KivaKanbanCardMenuItem<TData>>);
326
+ /** Whitelist of default actions to keep. Default `['open', 'edit', 'delete']`. */
327
+ cardActions?: ReadonlyArray<KivaKanbanCardAction>;
328
+ onCardOpen?: (row: TData) => void;
329
+ onCardEdit?: (row: TData) => void;
330
+ /**
331
+ * Custom delete handler. If omitted, the hook uses
332
+ * `collection.remove(id)` or `DELETE /v1/apps/.../items/:id` after a
333
+ * confirmation dialog.
334
+ */
335
+ onCardDelete?: (row: TData) => Promise<void> | void;
336
+ /** Click handler fired when the user clicks the card body. */
337
+ onCardClick?: (row: TData) => void;
338
+
339
+ /* --------------------------- Toolbar feature toggles ------------------ */
340
+
341
+ enableViewSelect?: boolean;
342
+ enableSearchInput?: boolean;
343
+ /** Show the date grouping picker when grouping by date/dateTime. Default `true`. */
344
+ enableDateGroupMenu?: boolean;
345
+ /** Show the user/team grouping picker when grouping by user. Default `true`. */
346
+ enableUserGroupMenu?: boolean;
347
+ /** Show the "Show all columns" switch when grouping by enum. Default `true`. */
348
+ enableShowAllColumnsSwitch?: boolean;
349
+ enableReloadButton?: boolean;
350
+
351
+ /** Fired after the toolbar reload + internal `refetch`. */
352
+ onReload?: () => void;
353
+ searchPlaceholder?: string;
354
+ searchDebounceMs?: number;
355
+ toolbarClassName?: string;
356
+ toolbarStartContent?: ReactNode;
357
+ toolbarEndContent?: ReactNode;
358
+
359
+ /**
360
+ * Fired when a card is dropped into a different column. The hook still
361
+ * issues its built-in PATCH; use this callback to mirror the change in
362
+ * local state, fire analytics, etc.
363
+ */
364
+ onItemMove?: (params: {
365
+ row: TData;
366
+ fromColumnId: string | null;
367
+ toColumnId: string;
368
+ column: KivaKanbanColumnMeta;
369
+ }) => void;
370
+ /**
371
+ * Custom item-move handler. When provided the hook skips its built-in
372
+ * PATCH so callers fully own persistence (optimistic updates, validation,
373
+ * undo, etc.). Throw to abort the move — the UI rolls back.
374
+ */
375
+ onItemMoveCommit?: (params: {
376
+ row: TData;
377
+ fromColumnId: string | null;
378
+ toColumnId: string;
379
+ column: KivaKanbanColumnMeta;
380
+ payload: Record<string, unknown>;
381
+ }) => Promise<void> | void;
382
+ /**
383
+ * Persist the user's manually-edited kanban parameters (search keyword, date
384
+ * / user grouping mode, "show all columns") to storage and restore them on
385
+ * the next mount. Keyed per active saved view.
386
+ *
387
+ * `true` → session storage. Pass `{ storage: 'local' }` to survive restarts,
388
+ * or `{ key: '…' }` to override the data-source segment of the storage key.
389
+ */
390
+ persistState?: PersistStateProp;
391
+ }
392
+
393
+ export interface UseKivaKanbanResult<TData>
394
+ extends Omit<UseKivaDataViewSelectResult, 'gridViewSelectProps'> {
395
+ /** Pre-wired toolbar element ready to render above the board. */
396
+ toolbar: ReactNode;
397
+ /**
398
+ * Pre-wired kanban board element. Render it directly — the underlying
399
+ * `<Kanban>` is fully wired to the hook's items, columns, drag handlers
400
+ * and final-zone integration.
401
+ */
402
+ board: ReactNode;
403
+ /** Resolved rows passed to the board. */
404
+ items: Array<TData>;
405
+ /** The list params actually sent to the backend. */
406
+ resolvedListParams: KivaKanbanListParams;
407
+ /** Group-by field metadata. */
408
+ groupByField: DataSourceField | undefined;
409
+ /** Ordered metadata for every rendered column. */
410
+ columns: Array<KivaKanbanColumnMeta>;
411
+ /** Items grouped by `column.id` — same shape passed into `<Kanban value>`. */
412
+ columnsItems: Record<string, Array<TData>>;
413
+ /** Active date grouping (only meaningful when grouping by date). */
414
+ dateGroupBy: KivaKanbanDateGroupBy;
415
+ setDateGroupBy: (value: KivaKanbanDateGroupBy) => void;
416
+ /** Active user grouping (only meaningful when grouping by user). */
417
+ userGroupBy: KivaKanbanUserGroupBy;
418
+ setUserGroupBy: (value: KivaKanbanUserGroupBy) => void;
419
+ /** Active "show all columns" switch state (enum grouping only). */
420
+ showAllColumns: boolean;
421
+ setShowAllColumns: (value: boolean) => void;
422
+ reload: () => void;
423
+ }
424
+
425
+ /* ------------------------------------------------------------------------- */
426
+ /* Hook */
427
+ /* ------------------------------------------------------------------------- */
428
+
429
+ export function useKivaKanban<TData extends Record<string, unknown>>(
430
+ options: UseKivaKanbanOptions<TData>
431
+ ): UseKivaKanbanResult<TData> {
432
+ const {
433
+ groupByFieldSlug,
434
+ data: providedData,
435
+ collection,
436
+ listParams,
437
+ defaultLimit = 200,
438
+ enableItemsQuery = providedData === undefined,
439
+ dateGroupBy: dateGroupByProp = 'day',
440
+ userGroupBy: userGroupByProp = 'user',
441
+ showAllColumns: showAllColumnsProp = true,
442
+ avatarColumn,
443
+ titleColumn,
444
+ descriptionColumn,
445
+ userColumn,
446
+ cardContent,
447
+ cardMenuItems,
448
+ cardActions = ['open', 'edit', 'delete'],
449
+ onCardOpen,
450
+ onCardEdit,
451
+ onCardDelete,
452
+ onCardClick,
453
+ enableViewSelect = true,
454
+ enableSearchInput = true,
455
+ enableDateGroupMenu = true,
456
+ enableUserGroupMenu = true,
457
+ enableShowAllColumnsSwitch = true,
458
+ enableReloadButton = true,
459
+ onReload,
460
+ searchPlaceholder = 'Search…',
461
+ searchDebounceMs = 300,
462
+ toolbarClassName,
463
+ toolbarStartContent,
464
+ toolbarEndContent,
465
+ onItemMove,
466
+ onItemMoveCommit,
467
+ persistState,
468
+ ...viewSelectOptions
469
+ } = options;
470
+
471
+ const persistConfig = resolvePersistConfig(persistState);
472
+ const persistEnabled = persistConfig !== null;
473
+ const persistStorage = persistConfig?.storage ?? 'session';
474
+ const persistKeyOverride = persistConfig?.key ?? '';
475
+
476
+ const queryClient = useQueryClient();
477
+
478
+ /*
479
+ * When `persistState` is on, the active-view id follows the same storage
480
+ * backend (session/local) and the same `docyrus:view-params` namespace as
481
+ * the persisted view parameters — under the reserved `__active-view__`
482
+ * segment so it can't collide with a per-view params entry. The fallback
483
+ * segment includes `appId` (mirroring the legacy key) because saved-view
484
+ * lists are appId-scoped — without it, two surfaces on the same data
485
+ * source distinguished only by `appId` would clobber each other's entry.
486
+ * Explicit `activeViewStorage` / `persistKey` options still win. Without
487
+ * `persistState` the view-select keeps its historical default (always-on
488
+ * localStorage under `docyrus:data-grid-view:…`). Mirrors
489
+ * `useKivaDataGrid` — keep the two in sync.
490
+ */
491
+ const viewSelect = useKivaDataViewSelect(persistEnabled ? {
492
+ ...viewSelectOptions,
493
+ activeViewStorage: viewSelectOptions.activeViewStorage ?? persistStorage,
494
+ persistKey: viewSelectOptions.persistKey ?? buildPersistKey([persistKeyOverride || [viewSelectOptions.appSlug, viewSelectOptions.dataSourceSlug, viewSelectOptions.appId].filter(Boolean).join(':'), '__active-view__'])
495
+ } : viewSelectOptions);
496
+ const {
497
+ dataSource, refetch: refetchViewSelect, views, activeViewId, setActiveViewId
498
+ } = viewSelect;
499
+
500
+ const groupByField = useMemo(
501
+ () => dataSource?.fields?.find(field => field.slug === groupByFieldSlug),
502
+ [dataSource?.fields, groupByFieldSlug]
503
+ );
504
+
505
+ const groupByKind = useMemo<'enum' | 'user' | 'date' | 'unsupported'>(() => {
506
+ if (!groupByField) return 'unsupported';
507
+ if (ENUM_GROUP_FIELD_TYPES.has(groupByField.type)) return 'enum';
508
+ if (groupByField.type === 'field-userSelect') return 'user';
509
+ if (DATE_GROUP_FIELD_TYPES.has(groupByField.type)) return 'date';
510
+
511
+ return 'unsupported';
512
+ }, [groupByField]);
513
+
514
+ const [dateGroupBy, setDateGroupBy] = useState<KivaKanbanDateGroupBy>(dateGroupByProp);
515
+ const [userGroupBy, setUserGroupBy] = useState<KivaKanbanUserGroupBy>(userGroupByProp);
516
+ const [showAllColumns, setShowAllColumns] = useState<boolean>(showAllColumnsProp);
517
+
518
+ /* --------------------------- search / filters ------------------------- */
519
+
520
+ const [searchInput, setSearchInput] = useState('');
521
+ const [debouncedSearch, setDebouncedSearch] = useState('');
522
+
523
+ useEffect(() => {
524
+ const timeout = window.setTimeout(() => setDebouncedSearch(searchInput), searchDebounceMs);
525
+
526
+ return () => window.clearTimeout(timeout);
527
+ }, [searchInput, searchDebounceMs]);
528
+
529
+ const activeView = useMemo(
530
+ () => views.find(view => view.id === activeViewId),
531
+ [views, activeViewId]
532
+ );
533
+
534
+ /*
535
+ * ── View-parameter persistence ────────────────────────────────────────
536
+ * Persist the kanban-specific knobs (search, date / user grouping mode,
537
+ * show-all-columns) per active saved view.
538
+ */
539
+ const persistStorageKey = useMemo(() => {
540
+ if (!persistEnabled) return null;
541
+
542
+ const dataSourceSegment = persistKeyOverride
543
+ || `${viewSelectOptions.appSlug}:${viewSelectOptions.dataSourceSlug}`;
544
+
545
+ return buildPersistKey([dataSourceSegment, activeViewId ?? 'default', 'kanban']);
546
+ }, [
547
+ persistEnabled,
548
+ persistKeyOverride,
549
+ viewSelectOptions.appSlug,
550
+ viewSelectOptions.dataSourceSlug,
551
+ activeViewId
552
+ ]);
553
+
554
+ const persistReady = persistEnabled && !!dataSource?.fields && dataSource.fields.length > 0;
555
+
556
+ const persistSnapshot = useMemo<KanbanPersistSnapshot>(() => ({
557
+ searchInput,
558
+ dateGroupBy,
559
+ userGroupBy,
560
+ showAllColumns
561
+ }), [
562
+ searchInput,
563
+ dateGroupBy,
564
+ userGroupBy,
565
+ showAllColumns
566
+ ]);
567
+
568
+ const restorePersistedParams = useCallback((restored: Partial<KanbanPersistSnapshot>) => {
569
+ if (typeof restored.searchInput === 'string') setSearchInput(restored.searchInput);
570
+ if (restored.dateGroupBy) setDateGroupBy(restored.dateGroupBy);
571
+ if (restored.userGroupBy) setUserGroupBy(restored.userGroupBy);
572
+ if (typeof restored.showAllColumns === 'boolean') setShowAllColumns(restored.showAllColumns);
573
+ }, []);
574
+
575
+ useParameterPersistence<KanbanPersistSnapshot>({
576
+ enabled: persistEnabled,
577
+ storage: persistStorage,
578
+ storageKey: persistStorageKey,
579
+ ready: persistReady,
580
+ snapshot: persistSnapshot,
581
+ onRestore: restorePersistedParams
582
+ });
583
+
584
+ const cardSlugs = useMemo(() => {
585
+ const set = new Set<string>([groupByFieldSlug]);
586
+
587
+ if (avatarColumn) set.add(avatarColumn);
588
+ if (titleColumn) set.add(titleColumn);
589
+ if (descriptionColumn) set.add(descriptionColumn);
590
+ if (userColumn) set.add(userColumn);
591
+
592
+ return Array.from(set);
593
+ }, [
594
+ groupByFieldSlug,
595
+ avatarColumn,
596
+ titleColumn,
597
+ descriptionColumn,
598
+ userColumn
599
+ ]);
600
+
601
+ const resolvedListParams = useMemo<KivaKanbanListParams>(() => {
602
+ const params: KivaKanbanListParams = {};
603
+
604
+ /*
605
+ * Always request the columns we need to render the card + group rows by
606
+ * the chosen field. The Kiva query API honors `columns` only when it
607
+ * is non-empty, otherwise everything is returned (which is fine on the
608
+ * card-tested data sources but we'd rather be explicit).
609
+ */
610
+ const fields = dataSource?.fields ?? [];
611
+ const fieldSlugs = new Set(fields.map(field => field.slug));
612
+ const required = cardSlugs.filter(slug => fieldSlugs.has(slug));
613
+
614
+ if (required.length > 0) {
615
+ const set = new Set<string>(['id', ...required]);
616
+
617
+ [
618
+ 'created_on',
619
+ 'last_modified_on',
620
+ 'created_by',
621
+ 'last_modified_by'
622
+ ].forEach(slug => set.add(slug));
623
+
624
+ params.columns = Array.from(set).join(', ');
625
+ }
626
+
627
+ /*
628
+ * `expand` for select/status/radioGroup fields so we get color + icon on
629
+ * the enum option, and for user fields so we get the photo + name +
630
+ * (optionally) team payload.
631
+ */
632
+ const expand = new Set<string>();
633
+
634
+ if (groupByField && (ENUM_GROUP_FIELD_TYPES.has(groupByField.type) || groupByField.type === 'field-userSelect')) {
635
+ expand.add(groupByField.slug);
636
+ }
637
+
638
+ for (const slug of [avatarColumn, userColumn]) {
639
+ if (!slug) continue;
640
+
641
+ const field = fields.find(f => f.slug === slug);
642
+
643
+ if (!field) continue;
644
+
645
+ if (field.type === 'field-userSelect' || ENUM_GROUP_FIELD_TYPES.has(field.type)) {
646
+ expand.add(slug);
647
+ }
648
+ }
649
+
650
+ if (expand.size > 0) params.expand = Array.from(expand);
651
+
652
+ if (activeView?.filterQuery && 'rules' in activeView.filterQuery && Array.isArray((activeView.filterQuery as RuleGroupType).rules) && (activeView.filterQuery as RuleGroupType).rules.length > 0) {
653
+ /*
654
+ * Emptiness is re-tested AFTER normalization: a view whose only rules
655
+ * were unsupported catalog operators normalizes to an empty group, which
656
+ * must not reach the wire as a filter.
657
+ */
658
+ const normalized = normalizeViewFilterGroup(activeView.filterQuery as RuleGroupType);
659
+
660
+ if (normalized.rules.length > 0) params.filters = normalized;
661
+ }
662
+
663
+ if (activeView?.sorting && activeView.sorting.length > 0) {
664
+ params.orderBy = activeView.sorting.map(sort => ({
665
+ field: sort.id,
666
+ direction: sort.desc ? 'desc' as const : 'asc' as const
667
+ }));
668
+ }
669
+
670
+ const trimmed = debouncedSearch.trim();
671
+
672
+ if (trimmed.length > 0) params.filterKeyword = trimmed;
673
+
674
+ params.limit = defaultLimit;
675
+ params.offset = 0;
676
+
677
+ if (listParams) {
678
+ /*
679
+ * `listParams.filters` is AND-merged into the filter built from the
680
+ * saved view (instead of replacing it). Without this merge, callers
681
+ * that inject a filter through `listParams.filters` (pivot filters,
682
+ * route-level scoping, custom widgets) would silently wipe out the
683
+ * active saved-view filtering — the same regression already fixed in
684
+ * `useKivaDataGrid`. Every other field on `listParams` still
685
+ * overrides as before.
686
+ */
687
+ const { filters: overrideFilters, ...overrideRest } = listParams;
688
+
689
+ Object.assign(params, overrideRest);
690
+
691
+ if (overrideFilters) {
692
+ const overrideGroup = overrideFilters as RuleGroupType;
693
+ const overrideHasRules = Array.isArray(overrideGroup.rules) && overrideGroup.rules.length > 0;
694
+
695
+ if (!overrideHasRules) {
696
+ } else if (!params.filters) {
697
+ params.filters = overrideFilters;
698
+ } else {
699
+ const existing = params.filters as RuleGroupType;
700
+
701
+ params.filters = {
702
+ combinator: 'and',
703
+ rules: [...(Array.isArray(existing.rules) ? existing.rules : []), ...overrideGroup.rules]
704
+ } as RuleGroupType;
705
+ }
706
+ }
707
+ }
708
+
709
+ return params;
710
+ }, [
711
+ dataSource?.fields,
712
+ cardSlugs,
713
+ groupByField,
714
+ avatarColumn,
715
+ userColumn,
716
+ activeView,
717
+ debouncedSearch,
718
+ defaultLimit,
719
+ listParams
720
+ ]);
721
+
722
+ /* --------------------------- items query ------------------------------ */
723
+
724
+ const itemsKey = useMemo(
725
+ () => [
726
+ 'kiva',
727
+ 'kivaKanbanItems',
728
+ viewSelectOptions.appSlug,
729
+ viewSelectOptions.dataSourceSlug,
730
+ collection ? 'collection' : 'direct',
731
+ resolvedListParams
732
+ ] as const,
733
+ [
734
+ viewSelectOptions.appSlug,
735
+ viewSelectOptions.dataSourceSlug,
736
+ collection,
737
+ resolvedListParams
738
+ ]
739
+ );
740
+
741
+ const viewMetadataReady = !viewSelect.isLoading && (views.length === 0 || Boolean(activeViewId));
742
+
743
+ const itemsQuery = useQuery<Array<TData>>({
744
+ queryKey: itemsKey,
745
+ queryFn: async () => {
746
+ if (collection) return unwrapItems<TData>(await collection.list(resolvedListParams));
747
+
748
+ const response = await viewSelectOptions.client.get<Array<TData> | { data: Array<TData> }>(
749
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items`,
750
+ resolvedListParams as Parameters<typeof viewSelectOptions.client.get>[1]
751
+ );
752
+
753
+ return unwrapItems<TData>(response);
754
+ },
755
+ enabled: providedData === undefined
756
+ && enableItemsQuery
757
+ && Boolean(viewSelectOptions.appSlug)
758
+ && Boolean(viewSelectOptions.dataSourceSlug)
759
+ && Boolean(groupByField)
760
+ && viewMetadataReady,
761
+ staleTime: viewSelectOptions.staleTime ?? 30_000,
762
+ placeholderData: keepPreviousData
763
+ });
764
+
765
+ const itemsRefetchRef = useRef<(() => Promise<unknown>) | null>(null);
766
+
767
+ itemsRefetchRef.current = itemsQuery.refetch as () => Promise<unknown>;
768
+
769
+ const items = useMemo<Array<TData>>(
770
+ () => providedData ?? itemsQuery.data ?? [],
771
+ [providedData, itemsQuery.data]
772
+ );
773
+
774
+ /* --------------------------- column derivation ------------------------ */
775
+
776
+ const allColumnsMeta = useMemo<Array<KivaKanbanColumnMeta>>(() => {
777
+ if (!groupByField) return [];
778
+
779
+ if (groupByKind === 'enum') {
780
+ return extractEnumColumns(groupByField);
781
+ }
782
+
783
+ if (groupByKind === 'user') {
784
+ return collectUserColumns(items, groupByField.slug, userGroupBy);
785
+ }
786
+
787
+ if (groupByKind === 'date') {
788
+ return collectDateColumns(items, groupByField.slug, dateGroupBy);
789
+ }
790
+
791
+ return [];
792
+ }, [
793
+ groupByField,
794
+ groupByKind,
795
+ items,
796
+ userGroupBy,
797
+ dateGroupBy
798
+ ]);
799
+
800
+ const columnsItems = useMemo<Record<string, Array<TData>>>(() => {
801
+ const map: Record<string, Array<TData>> = {};
802
+
803
+ if (!groupByField) return map;
804
+
805
+ for (const col of allColumnsMeta) map[col.id] = [];
806
+
807
+ for (const item of items) {
808
+ const value = (item as Record<string, unknown>)[groupByField.slug];
809
+ const keys = resolveItemKeys(value, groupByKind, dateGroupBy, userGroupBy);
810
+
811
+ for (const key of keys) {
812
+ if (!map[key]) {
813
+ if (groupByKind !== 'enum') continue; // only enum has the "show all" notion
814
+ map[key] = [];
815
+ }
816
+
817
+ map[key]?.push(item);
818
+ }
819
+ }
820
+
821
+ return map;
822
+ }, [
823
+ items,
824
+ allColumnsMeta,
825
+ groupByField,
826
+ groupByKind,
827
+ dateGroupBy,
828
+ userGroupBy
829
+ ]);
830
+
831
+ const visibleColumnsMeta = useMemo<Array<KivaKanbanColumnMeta>>(() => {
832
+ const withCounts = allColumnsMeta.map(col => ({
833
+ ...col,
834
+ count: columnsItems[col.id]?.length ?? 0
835
+ }));
836
+
837
+ if (groupByKind === 'enum' && !showAllColumns) {
838
+ return withCounts.filter(col => col.count > 0);
839
+ }
840
+
841
+ return withCounts;
842
+ }, [
843
+ allColumnsMeta,
844
+ columnsItems,
845
+ groupByKind,
846
+ showAllColumns
847
+ ]);
848
+
849
+ const finalColumnIds = useMemo<Array<string>>(() => {
850
+ if (groupByKind !== 'enum') return [];
851
+
852
+ return visibleColumnsMeta.filter(col => col.isFinal).map(col => col.id);
853
+ }, [groupByKind, visibleColumnsMeta]);
854
+
855
+ /*
856
+ * Items map fed into <Kanban>. We intentionally drop the entries that map
857
+ * to "final" columns from `value` (so they show up only inside the final
858
+ * zone) and we strip out columns the user hid via the show-all switch.
859
+ */
860
+ const kanbanValue = useMemo<Record<UniqueIdentifier, Array<TData>>>(() => {
861
+ const visibleIds = new Set(visibleColumnsMeta.map(col => col.id));
862
+ const finalIdSet = new Set(finalColumnIds);
863
+ const out: Record<UniqueIdentifier, Array<TData>> = {};
864
+
865
+ for (const col of visibleColumnsMeta) {
866
+ if (finalIdSet.has(col.id)) continue;
867
+ out[col.id] = columnsItems[col.id] ?? [];
868
+ }
869
+
870
+ /*
871
+ * Items whose group key isn't in the visible set get parked under "uncategorized"
872
+ * so they don't disappear from the board entirely.
873
+ */
874
+ const uncategorized: Array<TData> = [];
875
+
876
+ for (const [key, list] of Object.entries(columnsItems)) {
877
+ if (visibleIds.has(key)) continue;
878
+ uncategorized.push(...list);
879
+ }
880
+
881
+ if (uncategorized.length > 0) {
882
+ out['__uncategorized__'] = uncategorized;
883
+ }
884
+
885
+ return out;
886
+ }, [visibleColumnsMeta, columnsItems, finalColumnIds]);
887
+
888
+ const columnsForRender = useMemo<Array<KivaKanbanColumnMeta>>(() => {
889
+ const finalIdSet = new Set(finalColumnIds);
890
+ const list = visibleColumnsMeta.filter(col => !finalIdSet.has(col.id));
891
+
892
+ if (kanbanValue['__uncategorized__']) {
893
+ list.push({
894
+ id: '__uncategorized__',
895
+ label: 'Uncategorized',
896
+ count: kanbanValue['__uncategorized__'].length
897
+ });
898
+ }
899
+
900
+ return list;
901
+ }, [visibleColumnsMeta, finalColumnIds, kanbanValue]);
902
+
903
+ /* --------------------------- mutations / DnD -------------------------- */
904
+
905
+ const updateMutation = useMutation({
906
+ mutationFn: async (vars: { id: string; payload: Record<string, unknown> }) => {
907
+ if (collection?.update) {
908
+ await collection.update(vars.id, vars.payload);
909
+
910
+ return;
911
+ }
912
+
913
+ await viewSelectOptions.client.patch(
914
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items/${vars.id}`,
915
+ vars.payload
916
+ );
917
+ },
918
+ onSuccess: () => {
919
+ void queryClient.invalidateQueries({ queryKey: itemsKey });
920
+ }
921
+ });
922
+
923
+ const deleteMutation = useMutation({
924
+ mutationFn: async (id: string) => {
925
+ if (collection?.remove) {
926
+ await collection.remove(id);
927
+
928
+ return;
929
+ }
930
+
931
+ await viewSelectOptions.client.delete(
932
+ `/v1/apps/${viewSelectOptions.appSlug}/data-sources/${viewSelectOptions.dataSourceSlug}/items/${id}`
933
+ );
934
+ },
935
+ onSuccess: () => {
936
+ void queryClient.invalidateQueries({ queryKey: itemsKey });
937
+ }
938
+ });
939
+
940
+ const buildMovePayload = useCallback(
941
+ (toColumnId: string): Record<string, unknown> | null => {
942
+ if (!groupByField) return null;
943
+ if (toColumnId === '__uncategorized__') return { [groupByField.slug]: null };
944
+
945
+ if (groupByKind === 'enum') {
946
+ return { [groupByField.slug]: toColumnId };
947
+ }
948
+
949
+ if (groupByKind === 'user') {
950
+ if (userGroupBy === 'team') return null;
951
+
952
+ return { [groupByField.slug]: toColumnId };
953
+ }
954
+
955
+ return null;
956
+ },
957
+ [groupByField, groupByKind, userGroupBy]
958
+ );
959
+
960
+ /*
961
+ * Local mirror of the kanban distribution. The Kanban component fires
962
+ * `onValueChange` continuously during a drag (every `onDragOver`), so we
963
+ * keep a state copy that updates immediately for visual feedback and
964
+ * defer the actual PATCH to the drag-end handler. Reseed the mirror any
965
+ * time the source data (`kanbanValue`) changes — typically because a
966
+ * refetch landed.
967
+ */
968
+ const [liveValue, setLiveValue] = useState<Record<UniqueIdentifier, Array<TData>>>(kanbanValue);
969
+
970
+ useEffect(() => {
971
+ queueMicrotask(() => setLiveValue(kanbanValue));
972
+ }, [kanbanValue]);
973
+
974
+ const liveValueRef = useRef(liveValue);
975
+
976
+ liveValueRef.current = liveValue;
977
+
978
+ const handleValueChange = useCallback(
979
+ (next: Record<UniqueIdentifier, Array<TData>>) => {
980
+ setLiveValue(next);
981
+ },
982
+ []
983
+ );
984
+
985
+ const dragStateRef = useRef<{ id: string; originalColumnId: string } | null>(null);
986
+
987
+ const findColumnIdFor = useCallback(
988
+ (rowId: string, value: Record<UniqueIdentifier, Array<TData>>): string | null => {
989
+ for (const [columnId, list] of Object.entries(value)) {
990
+ const found = list.some((row) => {
991
+ const { id } = row as Record<string, unknown>;
992
+
993
+ return typeof id === 'string' && id === rowId;
994
+ });
995
+
996
+ if (found) return columnId;
997
+ }
998
+
999
+ return null;
1000
+ },
1001
+ []
1002
+ );
1003
+
1004
+ const handleDragStart = useCallback(
1005
+ (event: { active: { id: UniqueIdentifier } }) => {
1006
+ const id = String(event.active.id);
1007
+ const originalColumnId = findColumnIdFor(id, liveValueRef.current);
1008
+
1009
+ dragStateRef.current = originalColumnId ? { id, originalColumnId } : null;
1010
+ },
1011
+ [findColumnIdFor]
1012
+ );
1013
+
1014
+ const handleDragCancel = useCallback(() => {
1015
+ dragStateRef.current = null;
1016
+ }, []);
1017
+
1018
+ const commitMove = useCallback(
1019
+ (rowId: string, fromColumnId: string | null, toColumnId: string) => {
1020
+ if (!groupByField) return;
1021
+ if (fromColumnId === toColumnId) return;
1022
+
1023
+ const meta = columnsForRender.find(col => col.id === toColumnId);
1024
+
1025
+ if (!meta) return;
1026
+
1027
+ const payload = buildMovePayload(toColumnId);
1028
+
1029
+ if (!payload) return;
1030
+
1031
+ const list = liveValueRef.current[toColumnId] ?? [];
1032
+ const row = list.find((entry) => {
1033
+ const { id } = entry as Record<string, unknown>;
1034
+
1035
+ return typeof id === 'string' && id === rowId;
1036
+ });
1037
+
1038
+ if (!row) return;
1039
+
1040
+ const ctx = {
1041
+ row,
1042
+ fromColumnId,
1043
+ toColumnId,
1044
+ column: meta
1045
+ };
1046
+
1047
+ onItemMove?.(ctx);
1048
+
1049
+ if (onItemMoveCommit) {
1050
+ void Promise.resolve(onItemMoveCommit({ ...ctx, payload }));
1051
+ } else {
1052
+ updateMutation.mutate({ id: rowId, payload });
1053
+ }
1054
+ },
1055
+ [
1056
+ groupByField,
1057
+ columnsForRender,
1058
+ buildMovePayload,
1059
+ onItemMove,
1060
+ onItemMoveCommit,
1061
+ updateMutation
1062
+ ]
1063
+ );
1064
+
1065
+ const handleDragEnd = useCallback(
1066
+ () => {
1067
+ const drag = dragStateRef.current;
1068
+
1069
+ dragStateRef.current = null;
1070
+ if (!drag) return;
1071
+
1072
+ /*
1073
+ * Defer until the kanban component flushes its `onValueChange` call
1074
+ * for the drop. `onDragEnd` props fire BEFORE the internal state
1075
+ * update, so reading `liveValueRef.current` synchronously gives
1076
+ * pre-drop data.
1077
+ */
1078
+ queueMicrotask(() => {
1079
+ const newColumnId = findColumnIdFor(drag.id, liveValueRef.current);
1080
+
1081
+ /*
1082
+ * Final-zone drops remove the row from `value`, surfacing through
1083
+ * `handleFinalDrop` instead — bail out here.
1084
+ */
1085
+ if (!newColumnId) return;
1086
+
1087
+ commitMove(drag.id, drag.originalColumnId, newColumnId);
1088
+ });
1089
+ },
1090
+ [findColumnIdFor, commitMove]
1091
+ );
1092
+
1093
+ const handleFinalDrop = useCallback(
1094
+ (item: TData, finalColumnId: UniqueIdentifier) => {
1095
+ if (!groupByField) return;
1096
+ const { id } = item as Record<string, unknown>;
1097
+
1098
+ if (typeof id !== 'string' || id.length === 0) return;
1099
+ const meta = visibleColumnsMeta.find(col => col.id === finalColumnId);
1100
+
1101
+ if (!meta) return;
1102
+ const payload = { [groupByField.slug]: String(finalColumnId) };
1103
+
1104
+ onItemMove?.({
1105
+ row: item,
1106
+ fromColumnId: null,
1107
+ toColumnId: String(finalColumnId),
1108
+ column: meta
1109
+ });
1110
+
1111
+ if (onItemMoveCommit) {
1112
+ void Promise.resolve(onItemMoveCommit({
1113
+ row: item,
1114
+ fromColumnId: null,
1115
+ toColumnId: String(finalColumnId),
1116
+ column: meta,
1117
+ payload
1118
+ }));
1119
+ } else {
1120
+ updateMutation.mutate({ id, payload });
1121
+ }
1122
+ },
1123
+ [
1124
+ groupByField,
1125
+ visibleColumnsMeta,
1126
+ onItemMove,
1127
+ onItemMoveCommit,
1128
+ updateMutation
1129
+ ]
1130
+ );
1131
+
1132
+ /* --------------------------- delete dialog ---------------------------- */
1133
+
1134
+ const [deleteRow, setDeleteRow] = useState<TData | null>(null);
1135
+ const [isDeleting, setIsDeleting] = useState(false);
1136
+
1137
+ const onConfirmDelete = useCallback(async () => {
1138
+ if (!deleteRow) return;
1139
+ const { id } = deleteRow as Record<string, unknown>;
1140
+
1141
+ if (typeof id !== 'string' || id.length === 0) return;
1142
+
1143
+ setIsDeleting(true);
1144
+
1145
+ try {
1146
+ if (onCardDelete) {
1147
+ await Promise.resolve(onCardDelete(deleteRow));
1148
+ } else {
1149
+ await deleteMutation.mutateAsync(id);
1150
+ }
1151
+
1152
+ setDeleteRow(null);
1153
+ } finally {
1154
+ setIsDeleting(false);
1155
+ }
1156
+ }, [deleteRow, onCardDelete, deleteMutation]);
1157
+
1158
+ /* --------------------------- toolbar ---------------------------------- */
1159
+
1160
+ const reload = useCallback(() => {
1161
+ refetchViewSelect();
1162
+ if (providedData === undefined) void itemsQuery.refetch();
1163
+ onReload?.();
1164
+ }, [
1165
+ refetchViewSelect,
1166
+ itemsQuery,
1167
+ providedData,
1168
+ onReload
1169
+ ]);
1170
+
1171
+ const reloadItems = useCallback(() => {
1172
+ if (providedData === undefined) void itemsQuery.refetch();
1173
+ onReload?.();
1174
+ }, [itemsQuery, providedData, onReload]);
1175
+
1176
+ const isReloading = providedData === undefined && itemsQuery.isFetching && !itemsQuery.isLoading;
1177
+
1178
+ const showViewSelect = enableViewSelect && views.length > 0;
1179
+
1180
+ const showDateMenu = enableDateGroupMenu && groupByKind === 'date';
1181
+ const showUserMenu = enableUserGroupMenu && groupByKind === 'user';
1182
+ const showAllSwitch = enableShowAllColumnsSwitch && groupByKind === 'enum';
1183
+
1184
+ const toolbar = (
1185
+ <div
1186
+ data-slot="kiva-kanban-toolbar"
1187
+ className={cn('flex items-start gap-2 px-3 py-2', toolbarClassName)}>
1188
+ <div className="flex min-w-0 flex-1 items-center gap-2 flex-wrap">
1189
+ {toolbarStartContent}
1190
+ {showViewSelect && (
1191
+ <Select value={activeViewId} onValueChange={setActiveViewId}>
1192
+ <SelectTrigger className="h-8 min-w-[10rem]">
1193
+ <SelectValue placeholder="View" />
1194
+ </SelectTrigger>
1195
+ <SelectContent>
1196
+ {views.map(view => (
1197
+ <SelectItem key={view.id} value={view.id}>
1198
+ {view.name}
1199
+ </SelectItem>
1200
+ ))}
1201
+ </SelectContent>
1202
+ </Select>
1203
+ )}
1204
+ {enableSearchInput && (
1205
+ <div className="relative shrink-0">
1206
+ <Search className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
1207
+ <Input
1208
+ type="search"
1209
+ value={searchInput}
1210
+ onChange={event => setSearchInput(event.target.value)}
1211
+ placeholder={searchPlaceholder}
1212
+ className="h-8 w-56 pl-7" />
1213
+ </div>
1214
+ )}
1215
+ </div>
1216
+ <div className="flex flex-none shrink-0 items-center gap-2">
1217
+ {showDateMenu && (
1218
+ <div className="flex items-center gap-2">
1219
+ <Label className="text-xs text-muted-foreground">Group by</Label>
1220
+ <Select value={dateGroupBy} onValueChange={value => setDateGroupBy(value as KivaKanbanDateGroupBy)}>
1221
+ <SelectTrigger className="h-8 w-[7.5rem]">
1222
+ <SelectValue />
1223
+ </SelectTrigger>
1224
+ <SelectContent>
1225
+ <SelectItem value="day">Day</SelectItem>
1226
+ <SelectItem value="week">Week</SelectItem>
1227
+ <SelectItem value="month">Month</SelectItem>
1228
+ </SelectContent>
1229
+ </Select>
1230
+ </div>
1231
+ )}
1232
+ {showUserMenu && (
1233
+ <div className="flex items-center gap-2">
1234
+ <Label className="text-xs text-muted-foreground">Group by</Label>
1235
+ <Select value={userGroupBy} onValueChange={value => setUserGroupBy(value as KivaKanbanUserGroupBy)}>
1236
+ <SelectTrigger className="h-8 w-[7rem]">
1237
+ <SelectValue />
1238
+ </SelectTrigger>
1239
+ <SelectContent>
1240
+ <SelectItem value="user">User</SelectItem>
1241
+ <SelectItem value="team">Team</SelectItem>
1242
+ </SelectContent>
1243
+ </Select>
1244
+ </div>
1245
+ )}
1246
+ {showAllSwitch && (
1247
+ <div className="flex items-center gap-2">
1248
+ <Switch
1249
+ id="kiva-kanban-show-all"
1250
+ checked={showAllColumns}
1251
+ onCheckedChange={setShowAllColumns} />
1252
+ <Label htmlFor="kiva-kanban-show-all" className="text-xs text-muted-foreground">
1253
+ Show all
1254
+ </Label>
1255
+ </div>
1256
+ )}
1257
+ {enableReloadButton && (
1258
+ <Button
1259
+ variant="outline"
1260
+ size="icon-sm"
1261
+ aria-label="Reload"
1262
+ disabled={isReloading}
1263
+ onClick={reloadItems}>
1264
+ {isReloading ? <Loader2 className="size-4 animate-spin" /> : <RotateCw className="size-4" />}
1265
+ </Button>
1266
+ )}
1267
+ {toolbarEndContent}
1268
+ </div>
1269
+ </div>
1270
+ );
1271
+
1272
+ /* --------------------------- card rendering --------------------------- */
1273
+
1274
+ const buildDefaultMenu = useCallback(
1275
+ (): Array<KivaKanbanCardMenuItem<TData>> => {
1276
+ const list: Array<KivaKanbanCardMenuItem<TData>> = [];
1277
+
1278
+ if (cardActions.includes('open')) {
1279
+ list.push({
1280
+ key: 'open',
1281
+ label: 'Open',
1282
+ onAction: r => onCardOpen?.(r)
1283
+ });
1284
+ }
1285
+
1286
+ if (cardActions.includes('edit')) {
1287
+ list.push({
1288
+ key: 'edit',
1289
+ label: 'Edit',
1290
+ onAction: r => onCardEdit?.(r)
1291
+ });
1292
+ }
1293
+
1294
+ if (cardActions.includes('delete')) {
1295
+ list.push({
1296
+ key: 'delete',
1297
+ label: 'Delete',
1298
+ destructive: true,
1299
+ onAction: r => setDeleteRow(r)
1300
+ });
1301
+ }
1302
+
1303
+ return list;
1304
+ },
1305
+ [cardActions, onCardOpen, onCardEdit]
1306
+ );
1307
+
1308
+ const resolveMenu = useCallback(
1309
+ (row: TData): Array<KivaKanbanCardMenuItem<TData>> => {
1310
+ const defaults = buildDefaultMenu();
1311
+
1312
+ if (!cardMenuItems) return defaults;
1313
+ if (typeof cardMenuItems === 'function') return cardMenuItems(row, defaults);
1314
+
1315
+ return cardMenuItems;
1316
+ },
1317
+ [buildDefaultMenu, cardMenuItems]
1318
+ );
1319
+
1320
+ const renderCard = useCallback(
1321
+ (row: TData, column: KivaKanbanColumnMeta) => (
1322
+ <KanbanCard
1323
+ row={row}
1324
+ column={column}
1325
+ avatarColumn={avatarColumn}
1326
+ titleColumn={titleColumn}
1327
+ descriptionColumn={descriptionColumn}
1328
+ userColumn={userColumn}
1329
+ cardContent={cardContent}
1330
+ menu={resolveMenu(row)}
1331
+ onClick={onCardClick ?? onCardOpen} />
1332
+ ),
1333
+ [
1334
+ avatarColumn,
1335
+ titleColumn,
1336
+ descriptionColumn,
1337
+ userColumn,
1338
+ cardContent,
1339
+ resolveMenu,
1340
+ onCardClick,
1341
+ onCardOpen
1342
+ ]
1343
+ );
1344
+
1345
+ /* --------------------------- board ------------------------------------ */
1346
+
1347
+ const finalColumns = visibleColumnsMeta.filter(col => col.isFinal);
1348
+
1349
+ const board: ReactNode = viewSelect.isLoading ? null : !groupByField ? (
1350
+ <KanbanEmpty>
1351
+ Configure a group-by field that points to a `field-select`, `field-radioGroup`, `field-status`, `field-userSelect`, `field-date`, or `field-dateTime` field.
1352
+ </KanbanEmpty>
1353
+ ) : groupByKind === 'unsupported' ? (
1354
+ <KanbanEmpty>
1355
+ Field <code>{groupByField.slug}</code> is not supported as a kanban group column.
1356
+ </KanbanEmpty>
1357
+ ) : (
1358
+ /*
1359
+ * Cast through `unknown` because `KanbanRoot` uses a distributive
1360
+ * conditional (`T extends object ? … : Partial<…>`) that TS cannot
1361
+ * simplify against an unresolved generic. The props we pass are
1362
+ * always sound — TData is constrained to `Record<string, unknown>`.
1363
+ */
1364
+ <KanbanRootGeneric<TData>
1365
+ value={liveValue}
1366
+ onValueChange={handleValueChange}
1367
+ onDragStart={handleDragStart}
1368
+ onDragEnd={handleDragEnd}
1369
+ onDragCancel={handleDragCancel}
1370
+ onFinalDrop={handleFinalDrop}
1371
+ finalColumns={finalColumns.map(col => col.id)}
1372
+ getItemValue={(item: TData) => item.id as UniqueIdentifier}>
1373
+ {/*
1374
+ * Kanban root is a `<DndContext>` (no DOM wrapper), and `<KanbanBoard>`
1375
+ * defaults to `size-full`. Wrap board + final zone in a flex column so
1376
+ * the board flexes to fill available space and the final zone stays
1377
+ * pinned at the bottom — without this, the final zone ends up below
1378
+ * the viewport whenever the host page uses `flex-1 overflow-hidden`.
1379
+ */}
1380
+ <div className="flex h-full w-full flex-col gap-3">
1381
+ <KanbanBoard className="!h-auto min-h-0 flex-1 gap-3 overflow-x-auto overflow-y-hidden px-3 pb-2">
1382
+ {columnsForRender.map((col) => {
1383
+ const items = liveValue[col.id] ?? [];
1384
+
1385
+ return (
1386
+ <KanbanColumn
1387
+ key={col.id}
1388
+ value={col.id}
1389
+ className="flex h-full w-72 min-w-72 shrink-0 flex-col gap-0 overflow-hidden rounded-xl border bg-card p-0">
1390
+ <KanbanColumnHeader column={{ ...col, count: items.length }} />
1391
+ <div className="flex flex-1 flex-col gap-2 overflow-y-auto p-2">
1392
+ {items.map((row) => {
1393
+ const { id } = row as Record<string, unknown>;
1394
+
1395
+ if (typeof id !== 'string') return null;
1396
+
1397
+ return (
1398
+ <KanbanItem key={id} value={id} asHandle asChild>
1399
+ <div>
1400
+ {renderCard(row, col)}
1401
+ </div>
1402
+ </KanbanItem>
1403
+ );
1404
+ })}
1405
+ {items.length === 0 ? (
1406
+ <p className="py-8 text-center text-xs text-muted-foreground">
1407
+ No items
1408
+ </p>
1409
+ ) : null}
1410
+ </div>
1411
+ </KanbanColumn>
1412
+ );
1413
+ })}
1414
+ </KanbanBoard>
1415
+ {finalColumns.length > 0 && (
1416
+ <KanbanFinalZone className="shrink-0 px-3 pb-3">
1417
+ {finalColumns.map((col) => {
1418
+ return (
1419
+ <KanbanFinalColumn
1420
+ key={col.id}
1421
+ value={col.id}
1422
+ className="group rounded-xl border-2 border-dashed border-muted-foreground/25 bg-muted/40 transition-all duration-300 ease-in-out data-over:border-muted-foreground/60 data-over:bg-muted/60 data-over:scale-[1.02]">
1423
+ <KanbanColumnAccent color={col.color} icon={col.icon} />
1424
+ <span className="text-xs font-semibold transition-all duration-300 ease-in-out group-data-dragging:text-sm">
1425
+ {col.label}
1426
+ </span>
1427
+ <span className="grid grid-rows-[0fr] transition-[grid-template-rows] duration-300 ease-in-out group-data-dragging:grid-rows-[1fr]">
1428
+ <span className="overflow-hidden text-xs opacity-70">
1429
+ Drop to mark final
1430
+ </span>
1431
+ </span>
1432
+ </KanbanFinalColumn>
1433
+ );
1434
+ })}
1435
+ </KanbanFinalZone>
1436
+ )}
1437
+ </div>
1438
+ <KanbanOverlay>
1439
+ {({ value: activeId, variant }) => {
1440
+ if (variant === 'column') {
1441
+ return <div className="h-full w-72 rounded-xl border bg-primary/5" />;
1442
+ }
1443
+
1444
+ const idStr = String(activeId);
1445
+
1446
+ for (const col of columnsForRender) {
1447
+ const row = (liveValue[col.id] ?? []).find((r) => {
1448
+ const { id } = r as Record<string, unknown>;
1449
+
1450
+ return typeof id === 'string' && id === idStr;
1451
+ });
1452
+
1453
+ if (row) {
1454
+ return (
1455
+ <div className="w-72 cursor-grabbing">
1456
+ {renderCard(row, col)}
1457
+ </div>
1458
+ );
1459
+ }
1460
+ }
1461
+
1462
+ return <div className="size-full rounded-lg bg-primary/10" />;
1463
+ }}
1464
+ </KanbanOverlay>
1465
+ </KanbanRootGeneric>
1466
+ );
1467
+
1468
+ /* --------------------------- result ----------------------------------- */
1469
+
1470
+ const isLoading = viewSelect.isLoading
1471
+ || (providedData === undefined && (itemsQuery.isLoading || !viewMetadataReady));
1472
+ const error = (viewSelect.error ?? (itemsQuery.error as Error | null)) ?? null;
1473
+
1474
+ return {
1475
+ toolbar: (
1476
+ <>
1477
+ {toolbar}
1478
+ <RecordDeleteConfirmDialog
1479
+ open={deleteRow !== null}
1480
+ onOpenChange={(next) => {
1481
+ if (!next && !isDeleting) setDeleteRow(null);
1482
+ }}
1483
+ recordCount={1}
1484
+ isPending={isDeleting}
1485
+ onConfirm={onConfirmDelete} />
1486
+ </>
1487
+ ),
1488
+ board: <TooltipProvider>{board}</TooltipProvider>,
1489
+ items,
1490
+ resolvedListParams,
1491
+ groupByField,
1492
+ columns: visibleColumnsMeta,
1493
+ columnsItems,
1494
+ dateGroupBy,
1495
+ setDateGroupBy,
1496
+ userGroupBy,
1497
+ setUserGroupBy,
1498
+ showAllColumns,
1499
+ setShowAllColumns,
1500
+ reload,
1501
+ views: viewSelect.views,
1502
+ fields: viewSelect.fields,
1503
+ forms: viewSelect.forms,
1504
+ dataSource: viewSelect.dataSource,
1505
+ activeViewId: viewSelect.activeViewId,
1506
+ setActiveViewId: viewSelect.setActiveViewId,
1507
+ isLoading,
1508
+ error,
1509
+ refetch: reload,
1510
+ hasNoViews: viewSelect.hasNoViews
1511
+ };
1512
+ }
1513
+
1514
+ /* ------------------------------------------------------------------------- */
1515
+ /* Sub-components — moved to `_internal/use-kiva-kanban-cards` so this */
1516
+ /* file's exports stay non-component-only and Vite Fast Refresh works. */
1517
+ /* ------------------------------------------------------------------------- */
1518
+
1519
+ /* ------------------------------------------------------------------------- */
1520
+ /* Helpers */
1521
+ /* ------------------------------------------------------------------------- */
1522
+
1523
+ function unwrapItems<TData>(value: Array<TData> | { data: Array<TData> } | unknown): Array<TData> {
1524
+ if (Array.isArray(value)) return value;
1525
+ if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
1526
+ return (value as { data: Array<TData> }).data;
1527
+ }
1528
+
1529
+ return [];
1530
+ }
1531
+
1532
+ function extractEnumColumns(field: DataSourceField): Array<KivaKanbanColumnMeta> {
1533
+ const raw = field as Record<string, unknown>;
1534
+ const enums = Array.isArray(raw.enums) ? raw.enums : Array.isArray(raw.options) ? raw.options : [];
1535
+
1536
+ const result: Array<KivaKanbanColumnMeta> = [];
1537
+
1538
+ for (const entry of enums) {
1539
+ if (!entry || typeof entry !== 'object') continue;
1540
+
1541
+ const option = entry as Record<string, unknown>;
1542
+ const id = typeof option.id === 'string' ? option.id : typeof option.slug === 'string' ? option.slug : typeof option.value === 'string' ? option.value : null;
1543
+
1544
+ if (!id) continue;
1545
+
1546
+ const label = typeof option.name === 'string' ? option.name : typeof option.label === 'string' ? option.label : id;
1547
+ const color = typeof option.color === 'string' ? option.color : null;
1548
+ const icon = typeof option.icon === 'string' ? option.icon : null;
1549
+ const isFinal = option.is_final_option === true || option.isFinalOption === true;
1550
+
1551
+ result.push({
1552
+ id,
1553
+ label,
1554
+ color,
1555
+ icon,
1556
+ isFinal,
1557
+ count: 0
1558
+ });
1559
+ }
1560
+
1561
+ result.sort((a, b) => {
1562
+ const aRaw = enums.find((e: unknown) => (e as Record<string, unknown>).id === a.id || (e as Record<string, unknown>).slug === a.id);
1563
+ const bRaw = enums.find((e: unknown) => (e as Record<string, unknown>).id === b.id || (e as Record<string, unknown>).slug === b.id);
1564
+ const aOrder = typeof (aRaw as Record<string, unknown>)?.sort_order === 'number' ? (aRaw as { sort_order: number }).sort_order : Number.POSITIVE_INFINITY;
1565
+ const bOrder = typeof (bRaw as Record<string, unknown>)?.sort_order === 'number' ? (bRaw as { sort_order: number }).sort_order : Number.POSITIVE_INFINITY;
1566
+
1567
+ return aOrder - bOrder;
1568
+ });
1569
+
1570
+ return result;
1571
+ }
1572
+
1573
+ function collectUserColumns<TData>(
1574
+ items: Array<TData>,
1575
+ slug: string,
1576
+ mode: KivaKanbanUserGroupBy
1577
+ ): Array<KivaKanbanColumnMeta> {
1578
+ const map = new Map<string, KivaKanbanColumnMeta>();
1579
+
1580
+ for (const item of items) {
1581
+ const value = (item as Record<string, unknown>)[slug];
1582
+ const meta = readUserMeta(value, mode);
1583
+
1584
+ if (!meta) continue;
1585
+
1586
+ if (!map.has(meta.id)) {
1587
+ map.set(meta.id, {
1588
+ id: meta.id,
1589
+ label: meta.label,
1590
+ imageUrl: meta.imageUrl,
1591
+ count: 0
1592
+ });
1593
+ }
1594
+ }
1595
+
1596
+ return Array.from(map.values()).sort((a, b) => a.label.localeCompare(b.label));
1597
+ }
1598
+
1599
+ function collectDateColumns<TData>(
1600
+ items: Array<TData>,
1601
+ slug: string,
1602
+ mode: KivaKanbanDateGroupBy
1603
+ ): Array<KivaKanbanColumnMeta> {
1604
+ const map = new Map<string, { id: string; label: string; sortKey: number }>();
1605
+
1606
+ for (const item of items) {
1607
+ const value = (item as Record<string, unknown>)[slug];
1608
+ const bucket = bucketDate(value, mode);
1609
+
1610
+ if (!bucket) continue;
1611
+ if (!map.has(bucket.key)) {
1612
+ map.set(bucket.key, { id: bucket.key, label: bucket.label, sortKey: bucket.sortKey });
1613
+ }
1614
+ }
1615
+
1616
+ return Array.from(map.values())
1617
+ .sort((a, b) => a.sortKey - b.sortKey)
1618
+ .map(entry => ({ id: entry.id, label: entry.label, count: 0 }));
1619
+ }
1620
+
1621
+ function bucketDate(
1622
+ value: unknown,
1623
+ mode: KivaKanbanDateGroupBy
1624
+ ): { key: string; label: string; sortKey: number } | null {
1625
+ if (!value) return null;
1626
+ const date = value instanceof Date ? value : typeof value === 'string' || typeof value === 'number' ? new Date(value) : null;
1627
+
1628
+ if (!date || Number.isNaN(date.getTime())) return null;
1629
+
1630
+ const utc = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
1631
+
1632
+ if (mode === 'month') {
1633
+ const key = `${utc.getUTCFullYear()}-${String(utc.getUTCMonth() + 1).padStart(2, '0')}`;
1634
+ const label = utc.toLocaleDateString(undefined, { year: 'numeric', month: 'long', timeZone: 'UTC' });
1635
+
1636
+ return { key, label, sortKey: utc.getTime() };
1637
+ }
1638
+
1639
+ if (mode === 'week') {
1640
+ const day = utc.getUTCDay() || 7; // Sunday -> 7
1641
+ const monday = new Date(utc);
1642
+
1643
+ monday.setUTCDate(utc.getUTCDate() - (day - 1));
1644
+ const key = `${monday.getUTCFullYear()}-W${String(getISOWeek(monday)).padStart(2, '0')}`;
1645
+ const label = `Week of ${monday.toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' })}`;
1646
+
1647
+ return { key, label, sortKey: monday.getTime() };
1648
+ }
1649
+
1650
+ const key = utc.toISOString().slice(0, 10);
1651
+ const label = utc.toLocaleDateString(undefined, {
1652
+ year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC'
1653
+ });
1654
+
1655
+ return { key, label, sortKey: utc.getTime() };
1656
+ }
1657
+
1658
+ function getISOWeek(date: Date): number {
1659
+ const target = new Date(date);
1660
+
1661
+ target.setUTCDate(target.getUTCDate() + 4 - (target.getUTCDay() || 7));
1662
+ const yearStart = new Date(Date.UTC(target.getUTCFullYear(), 0, 1));
1663
+
1664
+ return Math.ceil(((target.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
1665
+ }
1666
+
1667
+ function resolveItemKeys(
1668
+ value: unknown,
1669
+ kind: 'enum' | 'user' | 'date' | 'unsupported',
1670
+ dateMode: KivaKanbanDateGroupBy,
1671
+ userMode: KivaKanbanUserGroupBy
1672
+ ): Array<string> {
1673
+ if (kind === 'enum') {
1674
+ if (!value) return [];
1675
+ if (typeof value === 'string') return [value];
1676
+
1677
+ if (typeof value === 'object') {
1678
+ const obj = value as Record<string, unknown>;
1679
+ const id = typeof obj.id === 'string' ? obj.id : typeof obj.slug === 'string' ? obj.slug : typeof obj.value === 'string' ? obj.value : null;
1680
+
1681
+ return id ? [id] : [];
1682
+ }
1683
+
1684
+ return [];
1685
+ }
1686
+
1687
+ if (kind === 'user') {
1688
+ const meta = readUserMeta(value, userMode);
1689
+
1690
+ return meta ? [meta.id] : [];
1691
+ }
1692
+
1693
+ if (kind === 'date') {
1694
+ const bucket = bucketDate(value, dateMode);
1695
+
1696
+ return bucket ? [bucket.key] : [];
1697
+ }
1698
+
1699
+ return [];
1700
+ }
1701
+
1702
+ export const KIVA_KANBAN_SUPPORTED_FIELD_TYPES = new Set<string>([
1703
+ 'field-select',
1704
+ 'field-radioGroup',
1705
+ 'field-status',
1706
+ 'field-userSelect',
1707
+ 'field-date',
1708
+ 'field-dateTime'
1709
+ ]);
1710
+
1711
+ /*
1712
+ * Exported so the renderer components in
1713
+ * `_internal/use-kiva-kanban-cards` can reuse the same user-shape
1714
+ * normalization the hook applies when bucketing rows into columns.
1715
+ */
1716
+ export function readUserMeta(
1717
+ value: unknown,
1718
+ mode: KivaKanbanUserGroupBy
1719
+ ): { id: string; label: string; imageUrl?: string | null } | null {
1720
+ if (!value || typeof value !== 'object') return null;
1721
+ const obj = value as Record<string, unknown>;
1722
+
1723
+ if (mode === 'team') {
1724
+ const teamId = typeof obj.team_id === 'string' ? obj.team_id : typeof obj.teamId === 'string' ? obj.teamId : null;
1725
+ const teamObj = (obj.team && typeof obj.team === 'object') ? (obj.team as Record<string, unknown>) : null;
1726
+ const id = teamId ?? (teamObj && typeof teamObj.id === 'string' ? teamObj.id : null);
1727
+
1728
+ if (!id) return null;
1729
+
1730
+ const label = teamObj && typeof teamObj.name === 'string' ? teamObj.name : typeof obj.team_name === 'string' ? obj.team_name : id;
1731
+
1732
+ return { id, label };
1733
+ }
1734
+
1735
+ const id = typeof obj.id === 'string' ? obj.id : typeof obj.user_id === 'string' ? obj.user_id : null;
1736
+
1737
+ if (!id) return null;
1738
+
1739
+ const firstName = typeof obj.firstname === 'string' ? obj.firstname : typeof obj.first_name === 'string' ? obj.first_name : null;
1740
+ const lastName = typeof obj.lastname === 'string' ? obj.lastname : typeof obj.last_name === 'string' ? obj.last_name : null;
1741
+ const fullName = firstName ? lastName ? `${firstName} ${lastName}` : firstName : lastName;
1742
+ const email = typeof obj.email === 'string' ? obj.email : null;
1743
+ const label = fullName ?? email ?? id;
1744
+ const imageUrl = typeof obj.photo === 'string' ? obj.photo : typeof obj.avatar_url === 'string' ? obj.avatar_url : typeof obj.profile_image_url === 'string' ? obj.profile_image_url : null;
1745
+
1746
+ return { id, label, imageUrl };
1747
+ }
1748
+
1749
+ export type KivaKanbanDateGroupBy = 'day' | 'week' | 'month';
1750
+ export type KivaKanbanUserGroupBy = 'user' | 'team';