@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,891 @@
1
+ 'use client';
2
+
3
+ // @ts-nocheck
4
+ /* eslint-disable */
5
+ import {
6
+ useCallback,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ type ReactNode
11
+ } from 'react';
12
+
13
+ import {
14
+ ChevronsUpDown,
15
+ GripVertical,
16
+ Loader2,
17
+ MoreHorizontal,
18
+ Plus,
19
+ RotateCcw,
20
+ SearchIcon,
21
+ Trash2,
22
+ X
23
+ } from 'lucide-react';
24
+
25
+ import { KivaIcon } from '@kivacore/ui-pro-shared/components/kiva/kiva-icon';
26
+ import { getEnumBadgeColors } from '@kivacore/ui-pro-shared/components/kiva/form-fields/lib/utils';
27
+ import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
28
+ import {
29
+ allIcons,
30
+ featuredHugeIcons,
31
+ featuredIcons,
32
+ hugeIcons
33
+ } from '@kivacore/ui-pro-shared/lib/kiva/icon-libraries';
34
+ import { TAILWIND_COLOR_FAMILIES, resolveColorHex } from '@kivacore/ui-pro-shared/lib/kiva/tailwind-colors';
35
+ import { cn } from '@kivacore/ui-pro-shared/lib/utils';
36
+ import { Alert, AlertDescription } from '@kivacore/ui-pro-shared/components/alert';
37
+ import { Badge } from '@kivacore/ui-pro-shared/components/badge';
38
+ import { Button } from '@kivacore/ui-pro-shared/components/button';
39
+ import {
40
+ Dialog,
41
+ DialogContent,
42
+ DialogDescription,
43
+ DialogHeader,
44
+ DialogTitle,
45
+ DialogTrigger
46
+ } from '@kivacore/ui-pro-shared/components/dialog';
47
+ import { Input } from '@kivacore/ui-pro-shared/components/input';
48
+ import { Label } from '@kivacore/ui-pro-shared/components/label';
49
+ import {
50
+ Popover,
51
+ PopoverContent,
52
+ PopoverTrigger
53
+ } from '@kivacore/ui-pro-shared/components/popover';
54
+ import { ScrollArea } from '@kivacore/ui-pro-shared/components/scroll-area';
55
+ import { Separator } from '@kivacore/ui-pro-shared/components/separator';
56
+ import {
57
+ Sortable,
58
+ SortableContent,
59
+ SortableItem,
60
+ SortableItemHandle,
61
+ SortableOverlay,
62
+ type SortableProps
63
+ } from '@kivacore/ui-pro-shared/components/sortable';
64
+ import { Switch } from '@kivacore/ui-pro-shared/components/switch';
65
+
66
+ import {
67
+ type EnumEditorOption,
68
+ type EnumOptionEditorDialogProps,
69
+ type EnumOptionEditorProps,
70
+ type EnumOptionInput
71
+ } from './types';
72
+
73
+ const TOKEN_RE = /^[a-z]+-\d+$/i;
74
+
75
+ /** Resolve an enum color string (Tailwind token or raw hex/rgb) to a CSS color. */
76
+ function resolveSwatch(color: string | undefined): string | undefined {
77
+ if (!color) return undefined;
78
+ const isToken = TOKEN_RE.test(color) || TAILWIND_COLOR_FAMILIES.includes(color as never);
79
+
80
+ return isToken ? resolveColorHex(color) : color;
81
+ }
82
+
83
+ /** Sort by `sort_order` (nulls last), then name. */
84
+ function sortOptions(options: EnumEditorOption[]): EnumEditorOption[] {
85
+ return [...options].sort((a, b) => {
86
+ const ao = a.sort_order ?? Number.POSITIVE_INFINITY;
87
+ const bo = b.sort_order ?? Number.POSITIVE_INFINITY;
88
+
89
+ if (ao !== bo) return ao - bo;
90
+
91
+ return (a.name ?? '').localeCompare(b.name ?? '');
92
+ });
93
+ }
94
+
95
+ /** Stable signature of the incoming options so we only reseed when they truly change. */
96
+ function optionsSignature(options: EnumEditorOption[]): string {
97
+ return options
98
+ .map(o => `${o.id}:${o.name}:${o.color ?? ''}:${o.icon ?? ''}:${o.sort_order ?? ''}:${o.active ?? ''}:${o.is_final_option ?? ''}:${o.isCustomized ?? ''}`)
99
+ .join('|');
100
+ }
101
+
102
+ const COLOR_TONES = [500];
103
+
104
+ interface OptionColorPickerProps {
105
+ value: string | undefined;
106
+ disabled?: boolean;
107
+ onChange: (value: string | undefined) => void;
108
+ }
109
+
110
+ function OptionColorPicker({ value, disabled, onChange }: OptionColorPickerProps) {
111
+ const { t } = useUiTranslation();
112
+ const [open, setOpen] = useState(false);
113
+ const swatch = resolveSwatch(value);
114
+
115
+ return (
116
+ <Popover open={open} onOpenChange={setOpen}>
117
+ <PopoverTrigger asChild disabled={disabled}>
118
+ <button
119
+ type="button"
120
+ aria-label={t('ui.enumEditor.color', 'Color')}
121
+ className={cn(
122
+ 'flex size-8 shrink-0 items-center justify-center rounded-md border border-input bg-background transition-colors hover:bg-accent/50',
123
+ disabled && 'pointer-events-none opacity-50'
124
+ )}>
125
+ <span
126
+ className={cn('size-4 rounded-sm border border-border', !swatch && 'bg-muted')}
127
+ style={swatch ? { backgroundColor: swatch } : undefined} />
128
+ </button>
129
+ </PopoverTrigger>
130
+ <PopoverContent align="start" className="w-64 p-3">
131
+ <div className="flex flex-wrap gap-1.5">
132
+ {TAILWIND_COLOR_FAMILIES.map((family) => {
133
+ const key = `${family}-${COLOR_TONES[0]}`;
134
+ const isSelected = value === key;
135
+
136
+ return (
137
+ <button
138
+ key={key}
139
+ type="button"
140
+ aria-label={key}
141
+ title={key}
142
+ className={cn(
143
+ 'size-6 shrink-0 rounded-sm transition-transform',
144
+ isSelected ? 'scale-110 ring-2 ring-primary ring-offset-1 ring-offset-background' : 'hover:scale-105'
145
+ )}
146
+ style={{ backgroundColor: resolveColorHex(key) }}
147
+ onClick={() => {
148
+ onChange(key);
149
+ setOpen(false);
150
+ }} />
151
+ );
152
+ })}
153
+ </div>
154
+ <Separator className="my-3" />
155
+ <div className="flex items-center gap-2">
156
+ <input
157
+ type="color"
158
+ value={value && value.startsWith('#') ? value : '#000000'}
159
+ onChange={e => onChange(e.target.value)}
160
+ className="h-8 w-10 shrink-0 cursor-pointer rounded-md border border-input p-1" />
161
+ <Input
162
+ value={value ?? ''}
163
+ onChange={e => onChange(e.target.value || undefined)}
164
+ placeholder={t('ui.enumEditor.colorPlaceholder', 'blue-500 or #2563eb')}
165
+ className="h-8 flex-1 text-xs" />
166
+ {value && (
167
+ <Button
168
+ type="button"
169
+ variant="ghost"
170
+ size="icon-sm"
171
+ aria-label={t('ui.enumEditor.clearColor', 'Clear color')}
172
+ onClick={() => onChange(undefined)}>
173
+ <X className="size-4" />
174
+ </Button>
175
+ )}
176
+ </div>
177
+ </PopoverContent>
178
+ </Popover>
179
+ );
180
+ }
181
+
182
+ type IconLibrary = 'fontawesome' | 'hugeicons';
183
+
184
+ interface OptionIconPickerProps {
185
+ value: string | undefined;
186
+ disabled?: boolean;
187
+ onChange: (value: string | undefined) => void;
188
+ }
189
+
190
+ function OptionIconPicker({ value, disabled, onChange }: OptionIconPickerProps) {
191
+ const { t } = useUiTranslation();
192
+ const [open, setOpen] = useState(false);
193
+ const [search, setSearch] = useState('');
194
+ const [library, setLibrary] = useState<IconLibrary>(() => (value?.startsWith('huge ') ? 'hugeicons' : 'fontawesome'));
195
+
196
+ const sourceIcons = library === 'hugeicons' ? hugeIcons : allIcons;
197
+ const featuredSource = library === 'hugeicons' ? featuredHugeIcons : featuredIcons;
198
+
199
+ const visibleIcons = useMemo(() => {
200
+ const query = search.trim().toLowerCase();
201
+
202
+ if (!query) return featuredSource;
203
+
204
+ return sourceIcons.filter(i => i.toLowerCase().includes(query)).slice(0, 90);
205
+ }, [featuredSource, search, sourceIcons]);
206
+
207
+ return (
208
+ <Popover open={open} onOpenChange={setOpen}>
209
+ <PopoverTrigger asChild disabled={disabled}>
210
+ <button
211
+ type="button"
212
+ aria-label={t('ui.enumEditor.icon', 'Icon')}
213
+ style={{ stroke: 'currentColor' }}
214
+ className={cn(
215
+ 'flex size-8 shrink-0 items-center justify-center rounded-md border border-input bg-background text-muted-foreground transition-colors hover:bg-accent/50',
216
+ disabled && 'pointer-events-none opacity-50'
217
+ )}>
218
+ {value ? <KivaIcon icon={value} className="size-4" /> : <Plus className="size-3.5 opacity-60" />}
219
+ </button>
220
+ </PopoverTrigger>
221
+ <PopoverContent align="start" className="w-72 p-3">
222
+ <div className="space-y-3">
223
+ <div className="flex items-center gap-1.5">
224
+ <Button
225
+ type="button"
226
+ variant={library === 'fontawesome' ? 'default' : 'outline'}
227
+ size="sm"
228
+ className="h-7 text-xs"
229
+ onClick={() => {
230
+ setLibrary('fontawesome');
231
+ setSearch('');
232
+ }}>
233
+ {t('ui.enumEditor.iconFontAwesome', 'Font Awesome')}
234
+ </Button>
235
+ <Button
236
+ type="button"
237
+ variant={library === 'hugeicons' ? 'default' : 'outline'}
238
+ size="sm"
239
+ className="h-7 text-xs"
240
+ onClick={() => {
241
+ setLibrary('hugeicons');
242
+ setSearch('');
243
+ }}>
244
+ {t('ui.enumEditor.iconHugeIcons', 'Huge Icons')}
245
+ </Button>
246
+ {value && (
247
+ <Button
248
+ type="button"
249
+ variant="ghost"
250
+ size="sm"
251
+ className="ml-auto h-7 text-xs text-muted-foreground"
252
+ onClick={() => {
253
+ onChange(undefined);
254
+ setOpen(false);
255
+ }}>
256
+ {t('ui.enumEditor.clear', 'Clear')}
257
+ </Button>
258
+ )}
259
+ </div>
260
+ <div className="relative">
261
+ <SearchIcon className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
262
+ <Input
263
+ value={search}
264
+ onChange={e => setSearch(e.target.value)}
265
+ placeholder={t('ui.enumEditor.iconSearch', 'Search icon...')}
266
+ className="h-8 pl-8 text-xs" />
267
+ </div>
268
+ <div className="max-h-52 overflow-y-auto p-0.5">
269
+ <div className="grid grid-cols-6 gap-1">
270
+ {visibleIcons.map((icon) => {
271
+ const isSelected = value === icon;
272
+
273
+ return (
274
+ <button
275
+ key={icon}
276
+ type="button"
277
+ title={icon}
278
+ className={cn(
279
+ 'flex h-9 w-full items-center justify-center rounded-md text-foreground transition-colors',
280
+ isSelected ? 'bg-primary/10 text-primary' : 'hover:bg-accent/60'
281
+ )}
282
+ style={{ stroke: 'currentColor' }}
283
+ onClick={() => {
284
+ onChange(icon);
285
+ setOpen(false);
286
+ }}>
287
+ <KivaIcon icon={icon} className="size-5" />
288
+ </button>
289
+ );
290
+ })}
291
+ </div>
292
+ {visibleIcons.length === 0 && (
293
+ <p className="py-4 text-center text-xs text-muted-foreground">
294
+ {t('ui.enumEditor.noIcons', 'No icons found.')}
295
+ </p>
296
+ )}
297
+ </div>
298
+ </div>
299
+ </PopoverContent>
300
+ </Popover>
301
+ );
302
+ }
303
+
304
+ interface AdvancedPopoverProps {
305
+ option: EnumEditorOption;
306
+ disabled?: boolean;
307
+ onPatch: (patch: Partial<EnumOptionInput>) => void;
308
+ }
309
+
310
+ function AdvancedPopover({ option, disabled, onPatch }: AdvancedPopoverProps) {
311
+ const { t } = useUiTranslation();
312
+ const [open, setOpen] = useState(false);
313
+ const [slug, setSlug] = useState(option.slug ?? '');
314
+ const [description, setDescription] = useState(option.description ?? '');
315
+
316
+ /*
317
+ * Reset the local inputs to the option's values each time the popover opens
318
+ * (React's "adjust state while rendering" pattern — no effect).
319
+ */
320
+ const wasOpenRef = useRef(open);
321
+
322
+ if (open !== wasOpenRef.current) {
323
+ wasOpenRef.current = open;
324
+
325
+ if (open) {
326
+ setSlug(option.slug ?? '');
327
+ setDescription(option.description ?? '');
328
+ }
329
+ }
330
+
331
+ const isInherited = option.origin === 'inherited';
332
+
333
+ return (
334
+ <Popover open={open} onOpenChange={setOpen}>
335
+ <PopoverTrigger asChild disabled={disabled}>
336
+ <Button
337
+ type="button"
338
+ variant="ghost"
339
+ size="icon-sm"
340
+ className="shrink-0 text-muted-foreground"
341
+ aria-label={t('ui.enumEditor.moreSettings', 'More settings')}>
342
+ <MoreHorizontal className="size-4" />
343
+ </Button>
344
+ </PopoverTrigger>
345
+ <PopoverContent align="end" className="w-72 space-y-3 p-3">
346
+ <div className="space-y-1.5">
347
+ <Label className="text-xs">{t('ui.enumEditor.slug', 'Slug')}</Label>
348
+ <Input
349
+ value={slug}
350
+ disabled={isInherited}
351
+ onChange={e => setSlug(e.target.value)}
352
+ onBlur={() => { if (slug !== (option.slug ?? '')) onPatch({ slug }); }}
353
+ placeholder={t('ui.enumEditor.slugAuto', 'Auto from name')}
354
+ className="h-8 text-xs" />
355
+ </div>
356
+ <div className="space-y-1.5">
357
+ <Label className="text-xs">{t('ui.enumEditor.description', 'Description')}</Label>
358
+ <Input
359
+ value={description}
360
+ onChange={e => setDescription(e.target.value)}
361
+ onBlur={() => { if (description !== (option.description ?? '')) onPatch({ description }); }}
362
+ className="h-8 text-xs" />
363
+ </div>
364
+ <Separator />
365
+ <ToggleRow
366
+ label={t('ui.enumEditor.active', 'Active')}
367
+ hint={t('ui.enumEditor.activeHint', 'Uncheck to retire without deleting')}
368
+ checked={option.active ?? true}
369
+ onCheckedChange={v => onPatch({ active: v })} />
370
+ <ToggleRow
371
+ label={t('ui.enumEditor.finalOption', 'Final option')}
372
+ hint={t('ui.enumEditor.finalOptionHint', 'Marks a terminal choice (Done / Cancelled)')}
373
+ checked={option.is_final_option ?? false}
374
+ onCheckedChange={v => onPatch({ is_final_option: v })} />
375
+ <ToggleRow
376
+ label={t('ui.enumEditor.forceDescription', 'Require note')}
377
+ checked={option.force_description ?? false}
378
+ onCheckedChange={v => onPatch({ force_description: v })} />
379
+ <ToggleRow
380
+ label={t('ui.enumEditor.forceFollowup', 'Require follow-up date')}
381
+ checked={option.force_followup_date ?? false}
382
+ onCheckedChange={v => onPatch({ force_followup_date: v })} />
383
+ </PopoverContent>
384
+ </Popover>
385
+ );
386
+ }
387
+
388
+ function ToggleRow({
389
+ label,
390
+ hint,
391
+ checked,
392
+ onCheckedChange
393
+ }: {
394
+ label: string;
395
+ hint?: string;
396
+ checked: boolean;
397
+ onCheckedChange: (checked: boolean) => void;
398
+ }) {
399
+ return (
400
+ <div className="flex items-center justify-between gap-3">
401
+ <div className="min-w-0">
402
+ <p className="text-xs font-medium">{label}</p>
403
+ {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
404
+ </div>
405
+ <Switch checked={checked} onCheckedChange={onCheckedChange} />
406
+ </div>
407
+ );
408
+ }
409
+
410
+ interface EnumOptionRowProps {
411
+ option: EnumEditorOption;
412
+ readOnly?: boolean;
413
+ allowReorder?: boolean;
414
+ allowDelete?: boolean;
415
+ pending?: boolean;
416
+ error?: string;
417
+ onPatch: (patch: Partial<EnumOptionInput>) => void;
418
+ onDelete: () => void;
419
+ onRevert: () => void;
420
+ }
421
+
422
+ function EnumOptionRow({
423
+ option,
424
+ readOnly,
425
+ allowReorder,
426
+ allowDelete,
427
+ pending,
428
+ error,
429
+ onPatch,
430
+ onDelete,
431
+ onRevert
432
+ }: EnumOptionRowProps) {
433
+ const { t } = useUiTranslation();
434
+ const [name, setName] = useState(option.name);
435
+ const isInherited = option.origin === 'inherited';
436
+ const badge = getEnumBadgeColors(option.color);
437
+
438
+ /*
439
+ * Sync the local editing buffer when the option's name changes externally
440
+ * (reorder / refetch) — render-time reset, not an effect.
441
+ */
442
+ const prevNameRef = useRef(option.name);
443
+
444
+ if (option.name !== prevNameRef.current) {
445
+ prevNameRef.current = option.name;
446
+ setName(option.name);
447
+ }
448
+
449
+ const commitName = useCallback(() => {
450
+ const next = name.trim();
451
+
452
+ if (next && next !== option.name) onPatch({ name: next });
453
+ else if (!next) setName(option.name);
454
+ }, [name, option.name, onPatch]);
455
+
456
+ return (
457
+ <div className="flex flex-col gap-1">
458
+ <div
459
+ className={cn(
460
+ 'flex items-center gap-1.5 rounded-md border bg-background px-1.5 py-1',
461
+ error && 'border-destructive',
462
+ (option.active ?? true) ? '' : 'opacity-60'
463
+ )}>
464
+ {allowReorder && !readOnly ? (
465
+ <SortableItemHandle asChild>
466
+ <Button
467
+ type="button"
468
+ variant="ghost"
469
+ size="icon-sm"
470
+ className="shrink-0 text-muted-foreground"
471
+ aria-label={t('ui.enumEditor.reorder', 'Reorder')}>
472
+ <GripVertical className="size-4" />
473
+ </Button>
474
+ </SortableItemHandle>
475
+ ) : (
476
+ <span className="w-2" />
477
+ )}
478
+
479
+ <OptionIconPicker value={option.icon} disabled={readOnly} onChange={v => onPatch({ icon: v })} />
480
+ <OptionColorPicker value={option.color} disabled={readOnly} onChange={v => onPatch({ color: v })} />
481
+
482
+ <Input
483
+ value={name}
484
+ disabled={readOnly}
485
+ onChange={e => setName(e.target.value)}
486
+ onBlur={commitName}
487
+ onKeyDown={(e) => {
488
+ if (e.key === 'Enter') {
489
+ e.preventDefault();
490
+ (e.target as HTMLInputElement).blur();
491
+ }
492
+ }}
493
+ className="h-8 flex-1 border-transparent bg-transparent px-2 shadow-none focus-visible:border-input focus-visible:bg-background" />
494
+
495
+ {isInherited && (
496
+ <Badge variant="secondary" className="hidden shrink-0 text-xs font-normal sm:inline-flex">
497
+ {option.isCustomized ? t('ui.enumEditor.overridden', 'Overridden') : t('ui.enumEditor.inherited', 'Inherited')}
498
+ </Badge>
499
+ )}
500
+
501
+ {pending && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />}
502
+
503
+ {!readOnly && <AdvancedPopover option={option} disabled={pending} onPatch={onPatch} />}
504
+
505
+ {!readOnly && allowDelete && (
506
+ isInherited ? (
507
+ <Button
508
+ type="button"
509
+ variant="ghost"
510
+ size="icon-sm"
511
+ disabled={pending || !option.isCustomized}
512
+ className="shrink-0 text-muted-foreground hover:text-foreground"
513
+ aria-label={t('ui.enumEditor.revert', 'Revert to default')}
514
+ title={t('ui.enumEditor.revert', 'Revert to default')}
515
+ onClick={onRevert}>
516
+ <RotateCcw className="size-4" />
517
+ </Button>
518
+ ) : (
519
+ <Button
520
+ type="button"
521
+ variant="ghost"
522
+ size="icon-sm"
523
+ disabled={pending}
524
+ className="shrink-0 text-muted-foreground hover:text-destructive"
525
+ aria-label={t('ui.enumEditor.delete', 'Delete')}
526
+ onClick={onDelete}>
527
+ <Trash2 className="size-4" />
528
+ </Button>
529
+ )
530
+ )}
531
+
532
+ {/* live preview chip */}
533
+ {(option.color || option.icon) && (
534
+ <Badge
535
+ variant="secondary"
536
+ className={cn('hidden shrink-0 max-w-32 gap-1 rounded-md px-1.5 py-0.5 font-normal lg:inline-flex', badge.className)}
537
+ style={badge.style}>
538
+ {option.icon && <KivaIcon icon={option.icon} className="size-3 shrink-0" />}
539
+ <span className="truncate">{option.name}</span>
540
+ </Badge>
541
+ )}
542
+ </div>
543
+ {error && <p className="px-2 text-xs text-destructive">{error}</p>}
544
+ </div>
545
+ );
546
+ }
547
+
548
+ export function EnumOptionEditor({
549
+ options,
550
+ onCreateOption,
551
+ onUpdateOption,
552
+ onDeleteOption,
553
+ onRevertOption,
554
+ onReorder,
555
+ readOnly = false,
556
+ allowCreate = true,
557
+ allowDelete = true,
558
+ allowReorder = true,
559
+ noticeText,
560
+ emptyText,
561
+ className
562
+ }: EnumOptionEditorProps) {
563
+ const { t } = useUiTranslation();
564
+ const [rows, setRows] = useState<EnumEditorOption[]>(() => sortOptions(options));
565
+ const [pendingIds, setPendingIds] = useState<Set<string>>(() => new Set());
566
+ const [rowErrors, setRowErrors] = useState<Record<string, string>>({});
567
+ const [newName, setNewName] = useState('');
568
+ const [createError, setCreateError] = useState('');
569
+ const [creating, setCreating] = useState(false);
570
+
571
+ const tempIdRef = useRef(0);
572
+ const lastSignatureRef = useRef(optionsSignature(options));
573
+
574
+ /*
575
+ * Reseed from the parent whenever the incoming options actually change
576
+ * (e.g. the Kiva wrapper re-read after a successful mutation). Render-time
577
+ * reset guarded by a signature ref — not an effect.
578
+ */
579
+ const incomingSignature = optionsSignature(options);
580
+
581
+ if (incomingSignature !== lastSignatureRef.current) {
582
+ lastSignatureRef.current = incomingSignature;
583
+ setRows(sortOptions(options));
584
+ }
585
+
586
+ const setPending = useCallback((id: string, on: boolean) => {
587
+ setPendingIds((prev) => {
588
+ const next = new Set(prev);
589
+
590
+ if (on) next.add(id);
591
+ else next.delete(id);
592
+
593
+ return next;
594
+ });
595
+ }, []);
596
+
597
+ const setError = useCallback((id: string, message: string) => {
598
+ setRowErrors(prev => ({ ...prev, [id]: message }));
599
+ }, []);
600
+
601
+ const clearError = useCallback((id: string) => {
602
+ setRowErrors((prev) => {
603
+ if (!(id in prev)) return prev;
604
+ const next = { ...prev };
605
+
606
+ delete next[id];
607
+
608
+ return next;
609
+ });
610
+ }, []);
611
+
612
+ const isDuplicateName = useCallback(
613
+ (name: string, exceptId?: string) => rows.some(
614
+ r => r.id !== exceptId && r.name.trim().toLowerCase() === name.trim().toLowerCase()
615
+ ),
616
+ [rows]
617
+ );
618
+
619
+ const handlePatch = useCallback(
620
+ async (id: string, patch: Partial<EnumOptionInput>) => {
621
+ if (patch.name !== undefined && isDuplicateName(patch.name, id)) {
622
+ setError(id, t('ui.enumEditor.duplicateName', 'An option with this name already exists.'));
623
+
624
+ return;
625
+ }
626
+ clearError(id);
627
+
628
+ const prevRows = rows;
629
+
630
+ setRows(prev => prev.map(r => (r.id === id ? { ...r, ...patch } : r)));
631
+
632
+ if (!onUpdateOption) return;
633
+ setPending(id, true);
634
+ try {
635
+ await onUpdateOption(id, patch);
636
+ } catch (e) {
637
+ setRows(prevRows);
638
+ setError(id, e instanceof Error ? e.message : t('ui.enumEditor.saveFailed', 'Failed to save.'));
639
+ } finally {
640
+ setPending(id, false);
641
+ }
642
+ },
643
+ [
644
+ rows,
645
+ onUpdateOption,
646
+ isDuplicateName,
647
+ setError,
648
+ clearError,
649
+ setPending,
650
+ t
651
+ ]
652
+ );
653
+
654
+ const handleDelete = useCallback(
655
+ async (id: string) => {
656
+ const prevRows = rows;
657
+
658
+ setRows(prev => prev.filter(r => r.id !== id));
659
+ clearError(id);
660
+
661
+ if (!onDeleteOption) return;
662
+ setPending(id, true);
663
+ try {
664
+ await onDeleteOption(id);
665
+ } catch (e) {
666
+ setRows(prevRows);
667
+ setError(id, e instanceof Error ? e.message : t('ui.enumEditor.deleteFailed', 'Failed to delete.'));
668
+ } finally {
669
+ setPending(id, false);
670
+ }
671
+ },
672
+ [
673
+ rows,
674
+ onDeleteOption,
675
+ clearError,
676
+ setError,
677
+ setPending,
678
+ t
679
+ ]
680
+ );
681
+
682
+ const handleRevert = useCallback(
683
+ async (id: string) => {
684
+ if (!onRevertOption) return;
685
+ setPending(id, true);
686
+ clearError(id);
687
+ try {
688
+ await onRevertOption(id);
689
+ } catch (e) {
690
+ setError(id, e instanceof Error ? e.message : t('ui.enumEditor.revertFailed', 'Failed to revert.'));
691
+ } finally {
692
+ setPending(id, false);
693
+ }
694
+ },
695
+ [
696
+ onRevertOption,
697
+ clearError,
698
+ setError,
699
+ setPending,
700
+ t
701
+ ]
702
+ );
703
+
704
+ const handleReorder = useCallback(
705
+ async (next: EnumEditorOption[]) => {
706
+ const prevRows = rows;
707
+
708
+ setRows(next);
709
+
710
+ if (!onReorder) return;
711
+ try {
712
+ await onReorder(next.map(r => r.id));
713
+ } catch {
714
+ setRows(prevRows);
715
+ }
716
+ },
717
+ [rows, onReorder]
718
+ );
719
+
720
+ const handleCreate = useCallback(async () => {
721
+ const name = newName.trim();
722
+
723
+ if (!name) return;
724
+
725
+ if (isDuplicateName(name)) {
726
+ setCreateError(t('ui.enumEditor.duplicateName', 'An option with this name already exists.'));
727
+
728
+ return;
729
+ }
730
+ setCreateError('');
731
+
732
+ const maxOrder = rows.reduce((m, r) => Math.max(m, r.sort_order ?? 0), 0);
733
+ const input: EnumOptionInput = { name, sort_order: maxOrder + 10, active: true };
734
+
735
+ if (!onCreateOption) {
736
+ const tempId = `tmp_${++tempIdRef.current}`;
737
+
738
+ setRows(prev => [...prev, { id: tempId, origin: 'custom', ...input }]);
739
+ setNewName('');
740
+
741
+ return;
742
+ }
743
+
744
+ setCreating(true);
745
+ try {
746
+ const created = await onCreateOption(input);
747
+
748
+ setRows(prev => [...prev, { origin: 'custom', ...created }]);
749
+ setNewName('');
750
+ } catch (e) {
751
+ setCreateError(e instanceof Error ? e.message : t('ui.enumEditor.createFailed', 'Failed to create option.'));
752
+ } finally {
753
+ setCreating(false);
754
+ }
755
+ }, [
756
+ newName,
757
+ rows,
758
+ onCreateOption,
759
+ isDuplicateName,
760
+ t
761
+ ]);
762
+
763
+ return (
764
+ <div className={cn('flex flex-col gap-3', className)}>
765
+ {noticeText && (
766
+ <Alert>
767
+ <AlertDescription>{noticeText}</AlertDescription>
768
+ </Alert>
769
+ )}
770
+
771
+ {rows.length === 0 && (
772
+ <p className="rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground">
773
+ {emptyText ?? t('ui.enumEditor.empty', 'No options yet.')}
774
+ </p>
775
+ )}
776
+
777
+ {rows.length > 0 && (
778
+ <Sortable
779
+ {...{
780
+ value: rows,
781
+ getItemValue: (item: EnumEditorOption) => item.id,
782
+ onValueChange: handleReorder,
783
+ orientation: 'vertical'
784
+ } as SortableProps<EnumEditorOption>}>
785
+ <SortableContent className="space-y-1.5">
786
+ {rows.map(option => (
787
+ <SortableItem key={option.id} value={option.id} asChild disabled={readOnly || !allowReorder}>
788
+ <div>
789
+ <EnumOptionRow
790
+ option={option}
791
+ readOnly={readOnly}
792
+ allowReorder={allowReorder}
793
+ allowDelete={allowDelete}
794
+ pending={pendingIds.has(option.id)}
795
+ error={rowErrors[option.id]}
796
+ onPatch={patch => handlePatch(option.id, patch)}
797
+ onDelete={() => handleDelete(option.id)}
798
+ onRevert={() => handleRevert(option.id)} />
799
+ </div>
800
+ </SortableItem>
801
+ ))}
802
+ </SortableContent>
803
+ <SortableOverlay>
804
+ <div className="h-10 rounded-md border bg-background shadow-lg" />
805
+ </SortableOverlay>
806
+ </Sortable>
807
+ )}
808
+
809
+ {!readOnly && allowCreate && (
810
+ <div className="flex flex-col gap-1">
811
+ <div className="flex items-center gap-2">
812
+ <Input
813
+ value={newName}
814
+ onChange={(e) => {
815
+ setNewName(e.target.value);
816
+ if (createError) setCreateError('');
817
+ }}
818
+ onKeyDown={(e) => {
819
+ if (e.key === 'Enter') {
820
+ e.preventDefault();
821
+ void handleCreate();
822
+ }
823
+ }}
824
+ placeholder={t('ui.enumEditor.addPlaceholder', 'New option name…')}
825
+ className="h-9 flex-1" />
826
+ <Button
827
+ type="button"
828
+ variant="outline"
829
+ size="sm"
830
+ disabled={!newName.trim() || creating}
831
+ onClick={() => void handleCreate()}>
832
+ {creating ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />}
833
+ {t('ui.enumEditor.add', 'Add')}
834
+ </Button>
835
+ </div>
836
+ {createError && <p className="px-1 text-xs text-destructive">{createError}</p>}
837
+ </div>
838
+ )}
839
+ </div>
840
+ );
841
+ }
842
+
843
+ export function EnumOptionEditorDialog({
844
+ trigger,
845
+ open: controlledOpen,
846
+ onOpenChange,
847
+ title,
848
+ description,
849
+ disabled,
850
+ ...editorProps
851
+ }: EnumOptionEditorDialogProps) {
852
+ const { t } = useUiTranslation();
853
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
854
+
855
+ const isControlled = controlledOpen !== undefined;
856
+ const open = isControlled ? controlledOpen : uncontrolledOpen;
857
+
858
+ const setOpen = useCallback(
859
+ (next: boolean) => {
860
+ if (!isControlled) setUncontrolledOpen(next);
861
+ onOpenChange?.(next);
862
+ },
863
+ [isControlled, onOpenChange]
864
+ );
865
+
866
+ const defaultTrigger: ReactNode = (
867
+ <Button type="button" variant="outline" size="sm" disabled={disabled}>
868
+ <ChevronsUpDown className="size-4" />
869
+ {t('ui.enumEditor.manageOptions', 'Manage options')}
870
+ </Button>
871
+ );
872
+
873
+ return (
874
+ <Dialog open={open} onOpenChange={setOpen}>
875
+ {trigger !== null && (
876
+ <DialogTrigger asChild>{trigger ?? defaultTrigger}</DialogTrigger>
877
+ )}
878
+ <DialogContent className="max-w-lg gap-3 p-4 sm:max-w-lg">
879
+ <DialogHeader>
880
+ <DialogTitle>{title ?? t('ui.enumEditor.title', 'Manage options')}</DialogTitle>
881
+ {description !== undefined ? <DialogDescription>{description}</DialogDescription> : <DialogDescription>{t('ui.enumEditor.dialogDescription', 'Add, edit, reorder and retire the selectable options for this field.')}</DialogDescription>}
882
+ </DialogHeader>
883
+ <ScrollArea className="max-h-[60vh]">
884
+ <div className="pr-3">
885
+ {open && <EnumOptionEditor {...editorProps} />}
886
+ </div>
887
+ </ScrollArea>
888
+ </DialogContent>
889
+ </Dialog>
890
+ );
891
+ }