@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.
- package/package.json +167 -1
- package/src/.kiva/config.json +27 -0
- package/src/components/avatar-group.tsx +222 -0
- package/src/components/kiva/bulk-update-dialog/bulk-update-dialog.tsx +240 -0
- package/src/components/kiva/bulk-update-dialog/index.tsx +6 -0
- package/src/components/kiva/bulk-update-dialog/types.ts +33 -0
- package/src/components/kiva/calendar/animations.ts +40 -0
- package/src/components/kiva/calendar/calendar-body.tsx +106 -0
- package/src/components/kiva/calendar/calendar-sidebar.tsx +103 -0
- package/src/components/kiva/calendar/calendar.tsx +243 -0
- package/src/components/kiva/calendar/constants.ts +12 -0
- package/src/components/kiva/calendar/contexts/calendar-context.tsx +696 -0
- package/src/components/kiva/calendar/contexts/dnd-context.tsx +173 -0
- package/src/components/kiva/calendar/dialogs/add-edit-event-dialog.tsx +287 -0
- package/src/components/kiva/calendar/dialogs/delete-event-dialog.tsx +73 -0
- package/src/components/kiva/calendar/dialogs/event-details-dialog.tsx +163 -0
- package/src/components/kiva/calendar/dialogs/events-list-dialog.tsx +122 -0
- package/src/components/kiva/calendar/dnd/draggable-event.tsx +66 -0
- package/src/components/kiva/calendar/dnd/droppable-area.tsx +53 -0
- package/src/components/kiva/calendar/dnd/resizable-event.tsx +190 -0
- package/src/components/kiva/calendar/header/calendar-header.tsx +84 -0
- package/src/components/kiva/calendar/header/date-navigator.tsx +188 -0
- package/src/components/kiva/calendar/header/filter.tsx +80 -0
- package/src/components/kiva/calendar/header/today-button.tsx +49 -0
- package/src/components/kiva/calendar/header/user-select.tsx +111 -0
- package/src/components/kiva/calendar/header/view-tabs.tsx +144 -0
- package/src/components/kiva/calendar/helpers.ts +617 -0
- package/src/components/kiva/calendar/hooks/use-disclosure.ts +19 -0
- package/src/components/kiva/calendar/hooks/use-local-storage.ts +40 -0
- package/src/components/kiva/calendar/hooks/use-media-query.ts +25 -0
- package/src/components/kiva/calendar/hooks.ts +5 -0
- package/src/components/kiva/calendar/index.tsx +27 -0
- package/src/components/kiva/calendar/interfaces.ts +35 -0
- package/src/components/kiva/calendar/schemas.ts +20 -0
- package/src/components/kiva/calendar/settings/settings.tsx +116 -0
- package/src/components/kiva/calendar/skeletons/calendar-header-skeleton.tsx +27 -0
- package/src/components/kiva/calendar/skeletons/calendar-skeleton.tsx +19 -0
- package/src/components/kiva/calendar/skeletons/day-view-skeleton.tsx +40 -0
- package/src/components/kiva/calendar/skeletons/month-view-skeleton.tsx +36 -0
- package/src/components/kiva/calendar/skeletons/week-view-skeleton.tsx +48 -0
- package/src/components/kiva/calendar/skeletons/year-view-skeleton.tsx +42 -0
- package/src/components/kiva/calendar/types.ts +25 -0
- package/src/components/kiva/calendar/views/agenda-view/agenda-events.tsx +150 -0
- package/src/components/kiva/calendar/views/month-view/calendar-month-view.tsx +82 -0
- package/src/components/kiva/calendar/views/month-view/day-cell.tsx +218 -0
- package/src/components/kiva/calendar/views/month-view/event-bullet.tsx +46 -0
- package/src/components/kiva/calendar/views/month-view/month-event-badge.tsx +154 -0
- package/src/components/kiva/calendar/views/timeline/calendar-timeline-view.tsx +100 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-layout.ts +130 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-model.ts +504 -0
- package/src/components/kiva/calendar/views/timeline/timeline-event-bar.tsx +68 -0
- package/src/components/kiva/calendar/views/timeline/timeline-grid-header.tsx +125 -0
- package/src/components/kiva/calendar/views/timeline/timeline-row.tsx +159 -0
- package/src/components/kiva/calendar/views/timeline/timeline-section.tsx +61 -0
- package/src/components/kiva/calendar/views/timeline/use-timeline-sections.ts +278 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-day-view.tsx +277 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-time-line.tsx +47 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-week-view.tsx +229 -0
- package/src/components/kiva/calendar/views/week-and-day-view/day-view-multi-day-events-row.tsx +79 -0
- package/src/components/kiva/calendar/views/week-and-day-view/event-block.tsx +116 -0
- package/src/components/kiva/calendar/views/week-and-day-view/render-grouped-events.tsx +54 -0
- package/src/components/kiva/calendar/views/week-and-day-view/week-view-multi-day-events-row.tsx +159 -0
- package/src/components/kiva/calendar/views/year-view/calendar-year-view.tsx +159 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-active-chips.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-clear.tsx +34 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-search.tsx +67 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-section.tsx +77 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-async-options.tsx +354 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-boolean.tsx +66 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-checkbox-list.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-date-range.tsx +204 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-numeric-range.tsx +162 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-options-dropdown.tsx +191 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-text.tsx +53 -0
- package/src/components/kiva/data-table-side-filters/core/query-translator.ts +367 -0
- package/src/components/kiva/data-table-side-filters/core/types.ts +81 -0
- package/src/components/kiva/data-table-side-filters/data-table-side-filters.tsx +483 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-data-table-side-filters.tsx +160 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-show-more.tsx +62 -0
- package/src/components/kiva/data-table-side-filters/index.tsx +44 -0
- package/src/components/kiva/data-table-side-filters/lib/render-mode.ts +62 -0
- package/src/components/kiva/date-time-picker.tsx +163 -0
- package/src/components/kiva/editable-record-detail.tsx +809 -0
- package/src/components/kiva/enum-option-editor/enum-option-editor.tsx +891 -0
- package/src/components/kiva/enum-option-editor/index.tsx +26 -0
- package/src/components/kiva/enum-option-editor/kiva-enum-option-editor.tsx +320 -0
- package/src/components/kiva/enum-option-editor/types.ts +90 -0
- package/src/components/kiva/kanban.tsx +1376 -0
- package/src/components/kiva/kiva-data-export-menu.tsx +543 -0
- package/src/components/kiva/map.tsx +1631 -0
- package/src/components/kiva/pivot-calendar/components/group-sidebar.tsx +95 -0
- package/src/components/kiva/pivot-calendar/components/pivot-calendar-toolbar.tsx +113 -0
- package/src/components/kiva/pivot-calendar/components/stats-cell.tsx +126 -0
- package/src/components/kiva/pivot-calendar/helpers.ts +374 -0
- package/src/components/kiva/pivot-calendar/hooks/use-pivot-calendar.ts +222 -0
- package/src/components/kiva/pivot-calendar/index.tsx +32 -0
- package/src/components/kiva/pivot-calendar/pivot-calendar.tsx +107 -0
- package/src/components/kiva/pivot-calendar/types.ts +154 -0
- package/src/components/kiva/pivot-calendar/views/days-of-month-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/days-of-week-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/month-calendar-view.tsx +154 -0
- package/src/components/kiva/pivot-calendar/views/months-of-year-view.tsx +40 -0
- package/src/components/kiva/pivot-calendar/views/pivot-grid-view.tsx +251 -0
- package/src/components/kiva/pivot-filter/index.tsx +9 -0
- package/src/components/kiva/pivot-filter/pivot-filter-item.tsx +159 -0
- package/src/components/kiva/pivot-filter/pivot-filter-settings.tsx +161 -0
- package/src/components/kiva/pivot-filter/pivot-filter.tsx +187 -0
- package/src/components/kiva/pivot-filter/types.ts +82 -0
- package/src/components/kiva/pivot-grid/hooks/use-pivot-grid.ts +683 -0
- package/src/components/kiva/pivot-grid/index.tsx +23 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-color-rules.ts +98 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-export.ts +265 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-model.ts +1110 -0
- package/src/components/kiva/pivot-grid/pivot-grid-demo-data.ts +200 -0
- package/src/components/kiva/pivot-grid/pivot-grid-export-menu.tsx +66 -0
- package/src/components/kiva/pivot-grid/pivot-grid-toolbar.tsx +85 -0
- package/src/components/kiva/pivot-grid/pivot-grid.tsx +601 -0
- package/src/components/kiva/pivot-grid/types.ts +195 -0
- package/src/components/kiva/place-autocomplete.tsx +484 -0
- package/src/components/kiva/record-delete-confirm-dialog/index.tsx +10 -0
- package/src/components/kiva/record-delete-confirm-dialog/record-delete-confirm-dialog.tsx +266 -0
- package/src/components/kiva/record-delete-confirm-dialog/types.ts +25 -0
- package/src/hooks/kiva/_internal/autonumber-setting.ts +112 -0
- package/src/hooks/kiva/_internal/form-layout-to-view.ts +665 -0
- package/src/hooks/kiva/_internal/kiva-hook-utils.ts +143 -0
- package/src/hooks/kiva/_internal/use-computed-field-evaluator.tsx +310 -0
- package/src/hooks/kiva/_internal/use-field-actions-evaluator.tsx +398 -0
- package/src/hooks/kiva/_internal/use-form-actions-evaluator.tsx +363 -0
- package/src/hooks/kiva/_internal/use-form-view-engine.tsx +2200 -0
- package/src/hooks/kiva/_internal/use-kiva-form-view-fields.tsx +190 -0
- package/src/hooks/kiva/_internal/use-kiva-kanban-cards.tsx +311 -0
- package/src/hooks/kiva/use-data-export.tsx +265 -0
- package/src/hooks/kiva/use-kiva-calendar.tsx +992 -0
- package/src/hooks/kiva/use-kiva-data-export.tsx +173 -0
- package/src/hooks/kiva/use-kiva-data-grid.tsx +4750 -0
- package/src/hooks/kiva/use-kiva-data-view-select.tsx +1273 -0
- package/src/hooks/kiva/use-kiva-form-view.tsx +1581 -0
- package/src/hooks/kiva/use-kiva-inventory.tsx +184 -0
- package/src/hooks/kiva/use-kiva-kanban.tsx +1750 -0
- package/src/hooks/kiva/use-kiva-map-view.tsx +2255 -0
- package/src/hooks/kiva/use-kiva-pivot-calendar.tsx +759 -0
- package/src/hooks/kiva/use-kiva-pivot-filter.tsx +1523 -0
- package/src/hooks/kiva/use-kiva-pivot-grid.tsx +543 -0
- package/src/hooks/kiva/use-kiva-tenant.tsx +313 -0
- package/src/hooks/kiva/use-parameter-persistence.ts +191 -0
|
@@ -0,0 +1,1581 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
// @ts-nocheck
|
|
4
|
+
/* eslint-disable */
|
|
5
|
+
import {
|
|
6
|
+
useCallback,
|
|
7
|
+
useMemo,
|
|
8
|
+
type ReactNode
|
|
9
|
+
} from 'react';
|
|
10
|
+
|
|
11
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
12
|
+
import {
|
|
13
|
+
createDataSourceClient,
|
|
14
|
+
type DataSource,
|
|
15
|
+
type DataSourceField
|
|
16
|
+
} from '@kivacore/app-utils';
|
|
17
|
+
import { useQuery } from '@tanstack/react-query';
|
|
18
|
+
import { Plus } from 'lucide-react';
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
KivaEnumOptionEditor,
|
|
22
|
+
useKivaEnumEditorPermission
|
|
23
|
+
} from '@kivacore/ui-pro-shared/components/kiva/enum-option-editor';
|
|
24
|
+
import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
|
|
25
|
+
import { Button } from '@kivacore/ui-pro-shared/components/button';
|
|
26
|
+
|
|
27
|
+
import { getSharedKivaInventory } from '@kivacore/ui-pro-shared/hooks/kiva/use-kiva-inventory';
|
|
28
|
+
import { AUTONUMBER_FIELD_SLUG, isAutonumberEditable } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/autonumber-setting';
|
|
29
|
+
|
|
30
|
+
import {
|
|
31
|
+
type ComputedBooleanFormula,
|
|
32
|
+
type EnumOption,
|
|
33
|
+
type FormAction,
|
|
34
|
+
type FormCustomValidationRule,
|
|
35
|
+
type IField,
|
|
36
|
+
type IFieldType,
|
|
37
|
+
type StoredFileValue
|
|
38
|
+
} from '@kivacore/ui-pro-shared/components/kiva/form-fields/types';
|
|
39
|
+
import { normalizeValidationTokens } from '@kivacore/ui-pro-shared/components/kiva/form-fields/lib/validation-tokens';
|
|
40
|
+
|
|
41
|
+
/*
|
|
42
|
+
* The rendering / state / computed / action / validation / submit engine lives
|
|
43
|
+
* in the shared `_internal/use-form-view-engine` module (imported via the
|
|
44
|
+
* `@ui/library/hooks/...` alias so the registry BFS bundles it). This hook is
|
|
45
|
+
* now a thin Kiva adapter: it does the schema / item / option fetching and
|
|
46
|
+
* the record persistence, then hands already-normalized fields + resolved
|
|
47
|
+
* options + an `onSubmit` sink to `useFormViewEngine`. The backend-agnostic
|
|
48
|
+
* sibling `useDynamicFormView` drives the same engine from caller-provided
|
|
49
|
+
* inputs.
|
|
50
|
+
*/
|
|
51
|
+
import {
|
|
52
|
+
useFormViewEngine,
|
|
53
|
+
buildInitialValues,
|
|
54
|
+
extractStaticEnumOptions,
|
|
55
|
+
getFieldQueryKeys,
|
|
56
|
+
normalizeEnumOption,
|
|
57
|
+
type KivaFormViewField,
|
|
58
|
+
type KivaFormViewFieldLayout,
|
|
59
|
+
type KivaFormViewLayoutItem,
|
|
60
|
+
type KivaFormViewMode,
|
|
61
|
+
type KivaFormViewRenderFieldOptions,
|
|
62
|
+
type KivaFormViewRenderLayoutOptions,
|
|
63
|
+
type KivaFormViewValidationTokenMode,
|
|
64
|
+
type FormViewEngineInput
|
|
65
|
+
} from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-form-view-engine';
|
|
66
|
+
import {
|
|
67
|
+
convertKivaFormLayout,
|
|
68
|
+
mergeKivaFieldLayouts
|
|
69
|
+
} from '@kivacore/ui-pro-shared/hooks/kiva/_internal/form-layout-to-view';
|
|
70
|
+
|
|
71
|
+
/*
|
|
72
|
+
* The saved-layout bridge, re-exported from the public hook module. Apps that
|
|
73
|
+
* fetch a `DataForm.layout` themselves (or render it through
|
|
74
|
+
* `useDynamicFormView` instead of this hook) need the same conversion, and the
|
|
75
|
+
* converter lives in `_internal/` only so the registry scanner doesn't surface
|
|
76
|
+
* it as a hook of its own.
|
|
77
|
+
*/
|
|
78
|
+
export { convertKivaFormLayout, mergeKivaFieldLayouts };
|
|
79
|
+
export type { ConvertedKivaFormLayout } from '@kivacore/ui-pro-shared/hooks/kiva/_internal/form-layout-to-view';
|
|
80
|
+
|
|
81
|
+
/*
|
|
82
|
+
* Re-export the shared render / layout / field types under their canonical
|
|
83
|
+
* `KivaFormView*` names so every existing consumer
|
|
84
|
+
* (`import { KivaFormViewField } from '.../use-kiva-form-view'`, etc.)
|
|
85
|
+
* keeps compiling unchanged after the engine extraction.
|
|
86
|
+
*/
|
|
87
|
+
export type {
|
|
88
|
+
KivaFormViewMode,
|
|
89
|
+
KivaFormViewRenderMode,
|
|
90
|
+
KivaFormViewValidationTokenMode,
|
|
91
|
+
KivaFormViewColSpan,
|
|
92
|
+
KivaFormViewLayoutFieldItem,
|
|
93
|
+
KivaFormViewFieldsetSection,
|
|
94
|
+
KivaFormViewTabSection,
|
|
95
|
+
KivaFormViewTabPanelSection,
|
|
96
|
+
KivaFormViewSection,
|
|
97
|
+
KivaFormViewLayoutItem,
|
|
98
|
+
KivaFormViewFieldLayout,
|
|
99
|
+
KivaFormViewRenderFieldOptions,
|
|
100
|
+
KivaFormViewRenderLayoutOptions,
|
|
101
|
+
KivaFormViewField,
|
|
102
|
+
LocalFormShape
|
|
103
|
+
} from '@kivacore/ui-pro-shared/hooks/kiva/_internal/use-form-view-engine';
|
|
104
|
+
|
|
105
|
+
export interface KivaFormViewCollection<TItem extends object> {
|
|
106
|
+
get?: (
|
|
107
|
+
recordId: string,
|
|
108
|
+
params?: Record<string, unknown>
|
|
109
|
+
) => Promise<TItem | { data: TItem }>;
|
|
110
|
+
create?: (data: Record<string, unknown>) => Promise<unknown>;
|
|
111
|
+
update?: (recordId: string, data: Record<string, unknown>) => Promise<unknown>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface KivaFormViewGetParams {
|
|
115
|
+
columns?: string | Array<string>;
|
|
116
|
+
expand?: string | Array<string>;
|
|
117
|
+
expandTypes?: Array<'user' | 'enum' | 'relation'>;
|
|
118
|
+
[key: string]: unknown;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface KivaFormViewCallbackContext {
|
|
122
|
+
mode: KivaFormViewMode;
|
|
123
|
+
itemId?: string;
|
|
124
|
+
values: Record<string, unknown>;
|
|
125
|
+
fields: Array<KivaFormViewField>;
|
|
126
|
+
dataSource?: DataSource;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface UseKivaFormViewOptions<TItem extends object> {
|
|
130
|
+
client: RestApiClient;
|
|
131
|
+
appSlug: string;
|
|
132
|
+
dataSourceSlug: string;
|
|
133
|
+
itemId?: string;
|
|
134
|
+
mode?: KivaFormViewMode;
|
|
135
|
+
item?: Record<string, unknown> | null;
|
|
136
|
+
collection?: KivaFormViewCollection<TItem>;
|
|
137
|
+
/**
|
|
138
|
+
* Pre-resolved data-source schema. When provided, the hook skips its
|
|
139
|
+
* internal `getBySlug` schema fetch entirely and reads fields / metadata
|
|
140
|
+
* from this object instead — useful for previews, the form builder, or any
|
|
141
|
+
* surface that already holds the schema in memory and must not hit the DB.
|
|
142
|
+
* Pair with `item` (record data) and `layout` for a fully fetch-free form.
|
|
143
|
+
*/
|
|
144
|
+
dataSource?: DataSource | null;
|
|
145
|
+
enabled?: boolean;
|
|
146
|
+
staleTime?: number;
|
|
147
|
+
/**
|
|
148
|
+
* `expand` query param sent with the data-source schema fetch. Defaults to
|
|
149
|
+
* `'enums'` (so select/status fields carry their option metadata). Pass
|
|
150
|
+
* `false` (or `''`) to omit `expand` entirely for backends that don't
|
|
151
|
+
* support it (e.g. core/tenant system data sources).
|
|
152
|
+
*/
|
|
153
|
+
schemaExpand?: string | false;
|
|
154
|
+
disabled?: boolean;
|
|
155
|
+
defaultValues?: Record<string, unknown>;
|
|
156
|
+
itemQueryParams?: KivaFormViewGetParams;
|
|
157
|
+
fieldSlugs?: Array<string>;
|
|
158
|
+
fieldOrder?: Array<string>;
|
|
159
|
+
hiddenFieldSlugs?: Array<string>;
|
|
160
|
+
fieldLayout?: Record<string, KivaFormViewFieldLayout>;
|
|
161
|
+
layout?: Array<KivaFormViewLayoutItem>;
|
|
162
|
+
/**
|
|
163
|
+
* A Kiva saved-form `layout` (the native `KvFormView` tree returned by
|
|
164
|
+
* `GET /v1/apps/{app}/data-sources/{ds}/forms`). When provided, the hook
|
|
165
|
+
* converts it internally — resolving stored field **ids** to slugs against
|
|
166
|
+
* the fetched schema — into `layout` + per-field overrides + a `fieldSlugs`
|
|
167
|
+
* whitelist, and derives the grid column count from the form. Explicit
|
|
168
|
+
* `layout` / `fieldSlugs` / `gridColumns` props win; explicit `fieldLayout`
|
|
169
|
+
* entries are merged on top (per field). Pass `form.layout` straight through.
|
|
170
|
+
*/
|
|
171
|
+
formLayout?: Record<string, unknown> | null;
|
|
172
|
+
mapField?: (field: DataSourceField, defaultMapped: IField) => IField | null;
|
|
173
|
+
/**
|
|
174
|
+
* Translate / override each field's display label (`IField.name`) before it
|
|
175
|
+
* is rendered. Called with the raw schema label; return the string to show.
|
|
176
|
+
* Lets consumers map labels from their own i18n dictionaries without having
|
|
177
|
+
* to hand-write a `mapField` per field. Applied after `mapField`, so a
|
|
178
|
+
* `mapField` override still wins if it sets `name` explicitly — the
|
|
179
|
+
* translator receives whatever `name` the mapped field carries.
|
|
180
|
+
*/
|
|
181
|
+
dynamicLabelTranslator?: (label: string) => string;
|
|
182
|
+
/**
|
|
183
|
+
* Translate / override each enum option's display label (`EnumOption.name`)
|
|
184
|
+
* before it is rendered in dropdowns, chips, and read-only value rows.
|
|
185
|
+
* Called once per option with the option and its owning field; return the
|
|
186
|
+
* text to show. Options carry a stable, language-independent `slug` — build
|
|
187
|
+
* keys like `enums.<field.slug>.<option.slug>` and translate `name` while
|
|
188
|
+
* `slug` / `color` / `icon` are preserved. Return the option's `name`
|
|
189
|
+
* unchanged for anything you don't want to translate. Applies to static enum
|
|
190
|
+
* options (`field-select`, `field-status`, …); also runs over resolved user /
|
|
191
|
+
* relation options, so key by `field.slug` and fall back to `option.name` to
|
|
192
|
+
* leave those untouched.
|
|
193
|
+
*/
|
|
194
|
+
dynamicEnumOptionTranslator?: (option: EnumOption, field: IField) => string;
|
|
195
|
+
includeReadOnlyFields?: boolean;
|
|
196
|
+
unsupportedFieldBehavior?: 'skip' | 'value';
|
|
197
|
+
/**
|
|
198
|
+
* Enforce the `validations` token constraints (`minLength:` / `maxLength:` /
|
|
199
|
+
* `pattern:` / `min:` / `max:`) on submit. `required` is always enforced and
|
|
200
|
+
* is unaffected.
|
|
201
|
+
*
|
|
202
|
+
* - `'off'` (default) — tokens stay advisory, so a stale bound on a
|
|
203
|
+
* data-source field can never block an existing record.
|
|
204
|
+
* - `'form'` — enforce only what the saved form declares for a field.
|
|
205
|
+
* - `'all'` — also enforce the data-source field's own tokens.
|
|
206
|
+
*/
|
|
207
|
+
validationTokens?: KivaFormViewValidationTokenMode;
|
|
208
|
+
gridColumns?: 1 | 2 | 3 | 4;
|
|
209
|
+
/** Form-level label placement — overrides the value derived from `formLayout`. */
|
|
210
|
+
labelAlign?: 'top' | 'left';
|
|
211
|
+
/** Label column width bucket for `labelAlign: 'left'`. */
|
|
212
|
+
labelWidth?: 'sm' | 'md' | 'lg';
|
|
213
|
+
/** Form-level field density. */
|
|
214
|
+
fieldSize?: 'sm' | 'md' | 'lg';
|
|
215
|
+
/** Form-level input style. */
|
|
216
|
+
fieldVariant?: 'outline' | 'filled';
|
|
217
|
+
clickToEdit?: boolean;
|
|
218
|
+
resolveUserOptions?: boolean;
|
|
219
|
+
resolveRelationOptions?: boolean;
|
|
220
|
+
optionLimit?: number;
|
|
221
|
+
enumOptions?: Record<string, Array<EnumOption>>;
|
|
222
|
+
transformSubmit?: (
|
|
223
|
+
payload: Record<string, unknown>,
|
|
224
|
+
context: KivaFormViewCallbackContext
|
|
225
|
+
) => Record<string, unknown>;
|
|
226
|
+
onSubmit?: (payload: Record<string, unknown>, context: KivaFormViewCallbackContext) => Promise<unknown> | unknown;
|
|
227
|
+
onSubmitSuccess?: (result: unknown, payload: Record<string, unknown>) => void;
|
|
228
|
+
onSubmitError?: (error: unknown, payload: Record<string, unknown>) => void;
|
|
229
|
+
/** Form-level lifecycle actions (onFormLoad, onFormBeforeSubmit, onFormAfterSubmit) */
|
|
230
|
+
formActions?: FormAction[] | null;
|
|
231
|
+
/** Form-level validation rules evaluated on submit — errors shown as a banner */
|
|
232
|
+
formCustomValidations?: FormCustomValidationRule[] | null;
|
|
233
|
+
/**
|
|
234
|
+
* Enable the permission-gated in-form enum option editor. When `true`, **enum**
|
|
235
|
+
* fields (`field-enum` / `field-systemEnum`) gain a "Manage options" footer at
|
|
236
|
+
* the bottom of their dropdown that opens a `KivaEnumOptionEditor` — but
|
|
237
|
+
* ONLY for users allowed to manage options. The hook reads that permission
|
|
238
|
+
* from `/v1/users/me` (ADMIN / ARCHITECT role) unless `canManageEnumOptions`
|
|
239
|
+
* is passed explicitly. On save the schema is refreshed so the dropdown picks
|
|
240
|
+
* up the new options. Default `false` (fully backward compatible).
|
|
241
|
+
*/
|
|
242
|
+
enumEditor?: boolean;
|
|
243
|
+
/**
|
|
244
|
+
* Explicit override for the enum-editor permission gate. When provided, the
|
|
245
|
+
* hook skips the `/v1/users/me` fetch and uses this value verbatim.
|
|
246
|
+
*/
|
|
247
|
+
canManageEnumOptions?: boolean;
|
|
248
|
+
/** Role ids allowed to manage options (default ADMIN + ARCHITECT). */
|
|
249
|
+
enumEditorAdminRoleIds?: Array<string>;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export interface UseKivaFormViewResult {
|
|
253
|
+
mode: KivaFormViewMode;
|
|
254
|
+
dataSource: DataSource | undefined;
|
|
255
|
+
item: Record<string, unknown>;
|
|
256
|
+
form: { Field: ({ name, children }: { name: string; children: (field: any) => ReactNode }) => ReactNode };
|
|
257
|
+
values: Record<string, unknown>;
|
|
258
|
+
defaultValues: Record<string, unknown>;
|
|
259
|
+
columns: Array<string>;
|
|
260
|
+
fields: Array<KivaFormViewField>;
|
|
261
|
+
allFields: Array<KivaFormViewField>;
|
|
262
|
+
unsupportedFields: Array<KivaFormViewField>;
|
|
263
|
+
validationErrors: Map<string, string>;
|
|
264
|
+
/** Form-level validation errors from formCustomValidations — shown as a banner above the form */
|
|
265
|
+
formValidationErrors: string[];
|
|
266
|
+
isDirty: boolean;
|
|
267
|
+
isLoading: boolean;
|
|
268
|
+
isSubmitting: boolean;
|
|
269
|
+
error: Error | null;
|
|
270
|
+
setValue: (slug: string, value: unknown) => void;
|
|
271
|
+
validate: () => Promise<boolean>;
|
|
272
|
+
reset: () => void;
|
|
273
|
+
submit: () => Promise<unknown>;
|
|
274
|
+
refetch: () => void;
|
|
275
|
+
/** Clear all accumulated field-action property overrides (hidden/readOnly/disabled/required). */
|
|
276
|
+
resetActionOverrides: () => void;
|
|
277
|
+
renderField: (slug: string, options?: KivaFormViewRenderFieldOptions) => ReactNode;
|
|
278
|
+
renderLayout: (options?: KivaFormViewRenderLayoutOptions) => ReactNode;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
interface RemoteFieldOptionsResult {
|
|
282
|
+
users: Array<EnumOption>;
|
|
283
|
+
relations: Record<string, Array<EnumOption>>;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function useKivaFormView<TItem extends object = Record<string, unknown>>(
|
|
287
|
+
options: UseKivaFormViewOptions<TItem>
|
|
288
|
+
): UseKivaFormViewResult {
|
|
289
|
+
const {
|
|
290
|
+
client,
|
|
291
|
+
appSlug,
|
|
292
|
+
dataSourceSlug,
|
|
293
|
+
itemId,
|
|
294
|
+
mode: providedMode,
|
|
295
|
+
item: providedItem,
|
|
296
|
+
collection,
|
|
297
|
+
dataSource: providedDataSource,
|
|
298
|
+
enabled = true,
|
|
299
|
+
staleTime = 30_000,
|
|
300
|
+
schemaExpand = 'enums',
|
|
301
|
+
disabled = false,
|
|
302
|
+
defaultValues: providedDefaultValues,
|
|
303
|
+
itemQueryParams,
|
|
304
|
+
fieldSlugs: fieldSlugsOption,
|
|
305
|
+
fieldOrder,
|
|
306
|
+
hiddenFieldSlugs,
|
|
307
|
+
fieldLayout: fieldLayoutOption,
|
|
308
|
+
layout: layoutOption,
|
|
309
|
+
formLayout,
|
|
310
|
+
mapField,
|
|
311
|
+
dynamicLabelTranslator,
|
|
312
|
+
dynamicEnumOptionTranslator,
|
|
313
|
+
includeReadOnlyFields: includeReadOnlyFieldsOption,
|
|
314
|
+
unsupportedFieldBehavior: unsupportedFieldBehaviorOption,
|
|
315
|
+
validationTokens,
|
|
316
|
+
gridColumns: gridColumnsOption,
|
|
317
|
+
labelAlign: labelAlignOption,
|
|
318
|
+
labelWidth: labelWidthOption,
|
|
319
|
+
fieldSize: fieldSizeOption,
|
|
320
|
+
fieldVariant: fieldVariantOption,
|
|
321
|
+
clickToEdit = false,
|
|
322
|
+
resolveUserOptions = true,
|
|
323
|
+
resolveRelationOptions = true,
|
|
324
|
+
optionLimit = 100,
|
|
325
|
+
enumOptions: enumOptionsOverrides,
|
|
326
|
+
transformSubmit,
|
|
327
|
+
onSubmit,
|
|
328
|
+
onSubmitSuccess,
|
|
329
|
+
onSubmitError,
|
|
330
|
+
formActions,
|
|
331
|
+
formCustomValidations,
|
|
332
|
+
enumEditor = true,
|
|
333
|
+
canManageEnumOptions: canManageEnumOptionsOption,
|
|
334
|
+
enumEditorAdminRoleIds
|
|
335
|
+
} = options;
|
|
336
|
+
|
|
337
|
+
const mode: KivaFormViewMode = providedMode ?? (itemId ? 'edit' : 'create');
|
|
338
|
+
/*
|
|
339
|
+
* When a saved `formLayout` is supplied, the form author explicitly chose the
|
|
340
|
+
* fields (including read-only ones), so render them regardless of mode. Without
|
|
341
|
+
* a form layout, keep the legacy default: read-only fields show in edit/view.
|
|
342
|
+
*/
|
|
343
|
+
const includeReadOnlyFields = includeReadOnlyFieldsOption ?? (formLayout ? true : mode !== 'create');
|
|
344
|
+
const unsupportedFieldBehavior = unsupportedFieldBehaviorOption ?? (mode === 'create' ? 'skip' : 'value');
|
|
345
|
+
|
|
346
|
+
/*
|
|
347
|
+
* Inventory-backed data-source client. Reads flow through the shared,
|
|
348
|
+
* post-sign-in-warmed app-utils inventory cache (see
|
|
349
|
+
* `getSharedKivaInventory`), so the schema fetch below and the
|
|
350
|
+
* relation-target lookups in `remoteFieldOptionsQuery` are all served by the
|
|
351
|
+
* single `/v1/apps/data-sources?expand=views,forms,fields` request the
|
|
352
|
+
* inventory already made at bootstrap — no per-instance
|
|
353
|
+
* `getBySlug(expand=enums)` round-trip and no `/v1/apps/enums` fan-out.
|
|
354
|
+
* `schemaExpand` is kept only as the cache-key discriminator / the cache-miss
|
|
355
|
+
* fallback expansion (system data sources aren't in the inventory list and
|
|
356
|
+
* must be fetched scoped, with fields).
|
|
357
|
+
*/
|
|
358
|
+
const dataSourcesClient = useMemo(
|
|
359
|
+
() => createDataSourceClient(client, { inventory: getSharedKivaInventory(client) }),
|
|
360
|
+
[client]
|
|
361
|
+
);
|
|
362
|
+
|
|
363
|
+
const dataSourceQuery = useQuery({
|
|
364
|
+
/*
|
|
365
|
+
* Keyed per (app, ds) — the inventory cache dedupes the underlying network
|
|
366
|
+
* call across every `useKivaFormView` instance, form dialog, and any
|
|
367
|
+
* other hook that shares the same inventory, so a grid + its record forms
|
|
368
|
+
* resolve their schema from a single fetch.
|
|
369
|
+
*/
|
|
370
|
+
queryKey: [
|
|
371
|
+
'kiva',
|
|
372
|
+
'dataSource',
|
|
373
|
+
appSlug,
|
|
374
|
+
dataSourceSlug,
|
|
375
|
+
schemaExpand || 'none'
|
|
376
|
+
],
|
|
377
|
+
queryFn: async () => {
|
|
378
|
+
/*
|
|
379
|
+
* Cache-first: no `expand` → the inventory serves the data source with
|
|
380
|
+
* `fields` (incl. inline enum options), `views`, and `forms` already
|
|
381
|
+
* embedded. On a cache miss the app-utils client falls back to a scoped
|
|
382
|
+
* GET with no expand (basic shape, no fields) — detected by the absent
|
|
383
|
+
* `fields` array — so re-fetch scoped WITH expand to cover data sources
|
|
384
|
+
* that live outside the inventory list (e.g. system data sources).
|
|
385
|
+
*/
|
|
386
|
+
const cached = await dataSourcesClient.getBySlug(appSlug, dataSourceSlug);
|
|
387
|
+
|
|
388
|
+
if (Array.isArray((cached as DataSource | undefined)?.fields)) {
|
|
389
|
+
return cached;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
return dataSourcesClient.getBySlug(
|
|
393
|
+
appSlug,
|
|
394
|
+
dataSourceSlug,
|
|
395
|
+
{ expand: schemaExpand || 'enums' }
|
|
396
|
+
);
|
|
397
|
+
},
|
|
398
|
+
enabled: enabled && !providedDataSource && Boolean(appSlug) && Boolean(dataSourceSlug),
|
|
399
|
+
staleTime
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
/*
|
|
403
|
+
* Caller-supplied schema wins over the fetched one. When `providedDataSource`
|
|
404
|
+
* is set the query above is disabled, so this is the only source of fields /
|
|
405
|
+
* metadata for every downstream derivation.
|
|
406
|
+
*/
|
|
407
|
+
const resolvedDataSource = providedDataSource ?? dataSourceQuery.data;
|
|
408
|
+
|
|
409
|
+
/*
|
|
410
|
+
* When a native Kiva saved-form `layout` is supplied, convert it against
|
|
411
|
+
* the resolved schema (field ids → slugs) into the internal `layout` /
|
|
412
|
+
* `fieldLayout` / `fieldSlugs` / column-count shape. Explicit props still win;
|
|
413
|
+
* explicit `fieldLayout` entries merge on top of the derived ones per field.
|
|
414
|
+
*/
|
|
415
|
+
const derivedFormLayout = useMemo(
|
|
416
|
+
() => (formLayout ? convertKivaFormLayout(formLayout, resolvedDataSource?.fields ?? []) : null),
|
|
417
|
+
[formLayout, resolvedDataSource?.fields]
|
|
418
|
+
);
|
|
419
|
+
|
|
420
|
+
const fieldSlugs = fieldSlugsOption ?? derivedFormLayout?.fieldSlugs;
|
|
421
|
+
const layout = layoutOption ?? derivedFormLayout?.layout;
|
|
422
|
+
const gridColumns = gridColumnsOption ?? derivedFormLayout?.columns ?? 2;
|
|
423
|
+
const fieldLayout = useMemo(
|
|
424
|
+
() => mergeKivaFieldLayouts(derivedFormLayout?.fieldLayout, fieldLayoutOption),
|
|
425
|
+
[derivedFormLayout, fieldLayoutOption]
|
|
426
|
+
);
|
|
427
|
+
|
|
428
|
+
const { t } = useUiTranslation();
|
|
429
|
+
|
|
430
|
+
/*
|
|
431
|
+
* Permission-gated in-form enum editor (opt-in via `enumEditor`). The hook
|
|
432
|
+
* reads the ADMIN / ARCHITECT gate from `/v1/users/me` (skipped when the
|
|
433
|
+
* caller passes `canManageEnumOptions`), then injects a "Manage options"
|
|
434
|
+
* footer into every enum field's dropdown via `fieldProps.renderOptionsEditor`
|
|
435
|
+
* — which the engine spreads onto the field component. Only `field-enum` /
|
|
436
|
+
* `field-systemEnum` are targeted (plain selects / status / tag / multi / radio
|
|
437
|
+
* are deliberately excluded).
|
|
438
|
+
*/
|
|
439
|
+
const enumEditorPermission = useKivaEnumEditorPermission(client, {
|
|
440
|
+
enabled: enumEditor && canManageEnumOptionsOption === undefined,
|
|
441
|
+
adminRoleIds: enumEditorAdminRoleIds
|
|
442
|
+
});
|
|
443
|
+
const enumEditorActive = enumEditor && (canManageEnumOptionsOption ?? enumEditorPermission.canManage);
|
|
444
|
+
|
|
445
|
+
const refreshSchema = useCallback(() => {
|
|
446
|
+
getSharedKivaInventory(client)?.invalidateDataSources();
|
|
447
|
+
void dataSourceQuery.refetch();
|
|
448
|
+
}, [client, dataSourceQuery]);
|
|
449
|
+
|
|
450
|
+
const fieldLayoutWithEnumEditor = useMemo(() => {
|
|
451
|
+
if (!enumEditorActive || !resolvedDataSource) return fieldLayout;
|
|
452
|
+
|
|
453
|
+
const appId = (resolvedDataSource.tenant_app_id as string | null | undefined)
|
|
454
|
+
?? resolvedDataSource.appSlug
|
|
455
|
+
?? appSlug;
|
|
456
|
+
const dataSourceId = resolvedDataSource.id;
|
|
457
|
+
const fields = resolvedDataSource.fields ?? [];
|
|
458
|
+
|
|
459
|
+
if (!appId || !dataSourceId || fields.length === 0) return fieldLayout;
|
|
460
|
+
|
|
461
|
+
const next: Record<string, KivaFormViewFieldLayout> = { ...(fieldLayout ?? {}) };
|
|
462
|
+
|
|
463
|
+
for (const f of fields) {
|
|
464
|
+
if (f.type !== 'field-enum' && f.type !== 'field-systemEnum') continue;
|
|
465
|
+
const fieldId = f.id;
|
|
466
|
+
|
|
467
|
+
if (!fieldId) continue;
|
|
468
|
+
const existing = next[f.slug] ?? {};
|
|
469
|
+
|
|
470
|
+
next[f.slug] = {
|
|
471
|
+
...existing,
|
|
472
|
+
fieldProps: {
|
|
473
|
+
...existing.fieldProps,
|
|
474
|
+
renderOptionsEditor: () => (
|
|
475
|
+
<KivaEnumOptionEditor
|
|
476
|
+
client={client}
|
|
477
|
+
appId={appId}
|
|
478
|
+
dataSourceId={dataSourceId}
|
|
479
|
+
fieldId={fieldId}
|
|
480
|
+
fieldName={f.name}
|
|
481
|
+
onChanged={refreshSchema}
|
|
482
|
+
trigger={(
|
|
483
|
+
<Button
|
|
484
|
+
type="button"
|
|
485
|
+
variant="ghost"
|
|
486
|
+
size="sm"
|
|
487
|
+
className="w-full justify-start gap-2 text-muted-foreground">
|
|
488
|
+
<Plus className="size-4" />
|
|
489
|
+
{t('ui.enumEditor.manageOptions', 'Manage options')}
|
|
490
|
+
</Button>
|
|
491
|
+
)} />
|
|
492
|
+
)
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
return next;
|
|
498
|
+
}, [
|
|
499
|
+
enumEditorActive,
|
|
500
|
+
resolvedDataSource,
|
|
501
|
+
fieldLayout,
|
|
502
|
+
client,
|
|
503
|
+
appSlug,
|
|
504
|
+
refreshSchema,
|
|
505
|
+
t
|
|
506
|
+
]);
|
|
507
|
+
|
|
508
|
+
/*
|
|
509
|
+
* Form-level actions/validations auto-resolve from the saved form layout when
|
|
510
|
+
* the caller doesn't pass them explicitly. A build-studio form stores its
|
|
511
|
+
* `formActions` / `formCustomValidations` inside `formLayout`, so binding a
|
|
512
|
+
* form to a view runs its lifecycle actions automatically — no per-page
|
|
513
|
+
* wiring. Explicit props always win (e.g. the form-builder test page).
|
|
514
|
+
*/
|
|
515
|
+
const resolvedFormActions = formActions ?? derivedFormLayout?.formActions;
|
|
516
|
+
const resolvedFormCustomValidations = formCustomValidations ?? derivedFormLayout?.formCustomValidations;
|
|
517
|
+
const resolvedLabelAlign = labelAlignOption ?? derivedFormLayout?.labelAlign;
|
|
518
|
+
const resolvedLabelWidth = labelWidthOption ?? derivedFormLayout?.labelWidth;
|
|
519
|
+
const resolvedFieldSize = fieldSizeOption ?? derivedFormLayout?.fieldSize;
|
|
520
|
+
const resolvedFieldVariant = fieldVariantOption ?? derivedFormLayout?.fieldVariant;
|
|
521
|
+
|
|
522
|
+
/*
|
|
523
|
+
* The record number takes input where the data source's metadata says it can
|
|
524
|
+
* be set by hand, in create and edit forms; view mode and click-to-edit keep
|
|
525
|
+
* it read-only, shown as before.
|
|
526
|
+
*/
|
|
527
|
+
const autonumberEditable = mode !== 'view' && isAutonumberEditable(resolvedDataSource);
|
|
528
|
+
|
|
529
|
+
const mappedFields = useMemo<Array<{ sourceField: DataSourceField; field: IField }>>(() => {
|
|
530
|
+
const sourceFields = resolvedDataSource?.fields ?? [];
|
|
531
|
+
|
|
532
|
+
return sourceFields
|
|
533
|
+
.map((sourceField) => {
|
|
534
|
+
const base = autonumberEditable ? unlockAutonumberField(dataSourceFieldToIField(sourceField)) : dataSourceFieldToIField(sourceField);
|
|
535
|
+
const mapped = mapField ? mapField(sourceField, base) : base;
|
|
536
|
+
|
|
537
|
+
if (!mapped) return null;
|
|
538
|
+
if (fieldSlugs && !fieldSlugs.includes(mapped.slug)) return null;
|
|
539
|
+
|
|
540
|
+
const field = dynamicLabelTranslator && typeof mapped.name === 'string' ? { ...mapped, name: dynamicLabelTranslator(mapped.name) } : mapped;
|
|
541
|
+
|
|
542
|
+
return { sourceField, field };
|
|
543
|
+
})
|
|
544
|
+
.filter((entry): entry is { sourceField: DataSourceField; field: IField } => entry !== null);
|
|
545
|
+
}, [
|
|
546
|
+
resolvedDataSource?.fields,
|
|
547
|
+
fieldSlugs,
|
|
548
|
+
mapField,
|
|
549
|
+
dynamicLabelTranslator,
|
|
550
|
+
autonumberEditable
|
|
551
|
+
]);
|
|
552
|
+
|
|
553
|
+
const baseColumns = useMemo(() => buildFieldQueryColumns(mappedFields.map(entry => entry.field)), [mappedFields]);
|
|
554
|
+
const columns = useMemo(() => {
|
|
555
|
+
const extraColumns = normalizeColumnsInput(itemQueryParams?.columns);
|
|
556
|
+
|
|
557
|
+
return uniqueStrings([...baseColumns, ...extraColumns]);
|
|
558
|
+
}, [baseColumns, itemQueryParams?.columns]);
|
|
559
|
+
|
|
560
|
+
const itemQuery = useQuery<Record<string, unknown>>({
|
|
561
|
+
queryKey: [
|
|
562
|
+
'kiva',
|
|
563
|
+
'formView',
|
|
564
|
+
'item',
|
|
565
|
+
appSlug,
|
|
566
|
+
dataSourceSlug,
|
|
567
|
+
itemId,
|
|
568
|
+
columns,
|
|
569
|
+
itemQueryParams
|
|
570
|
+
],
|
|
571
|
+
queryFn: async () => {
|
|
572
|
+
if (!itemId) return {};
|
|
573
|
+
|
|
574
|
+
const fetchItem = async (requestColumns: Array<string>): Promise<Record<string, unknown>> => {
|
|
575
|
+
if (collection?.get) {
|
|
576
|
+
return unwrapRecord(await collection.get(itemId, {
|
|
577
|
+
columns: requestColumns,
|
|
578
|
+
...itemQueryParams
|
|
579
|
+
}));
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
const response = await client.get<Record<string, unknown> | { data: Record<string, unknown> }>(
|
|
583
|
+
`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items/${itemId}`,
|
|
584
|
+
{
|
|
585
|
+
...(itemQueryParams ?? {}),
|
|
586
|
+
columns: requestColumns.join(', ')
|
|
587
|
+
} as Parameters<typeof client.get>[1]
|
|
588
|
+
);
|
|
589
|
+
|
|
590
|
+
return unwrapRecord(response);
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
try {
|
|
594
|
+
return await fetchItem(columns);
|
|
595
|
+
} catch (error) {
|
|
596
|
+
/*
|
|
597
|
+
* The Kiva record GET fails the whole request with HTTP 500 when a
|
|
598
|
+
* single requested column does not physically exist on the data source
|
|
599
|
+
* (e.g. a companion column the backend never materialized). Recover by
|
|
600
|
+
* stripping the offending column and retrying once. This protects every
|
|
601
|
+
* valid companion (currency / country / secondary / …) and any
|
|
602
|
+
* caller-supplied itemQueryParams.columns uniformly, without needing to
|
|
603
|
+
* cross-check the data source schema up front.
|
|
604
|
+
*/
|
|
605
|
+
const missingColumn = extractMissingColumn(error);
|
|
606
|
+
|
|
607
|
+
if (!missingColumn) throw error;
|
|
608
|
+
|
|
609
|
+
const prunedColumns = columns.filter(column => column !== missingColumn);
|
|
610
|
+
|
|
611
|
+
if (prunedColumns.length > 0 && prunedColumns.length < columns.length) {
|
|
612
|
+
return fetchItem(prunedColumns);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
throw error;
|
|
616
|
+
}
|
|
617
|
+
},
|
|
618
|
+
enabled: enabled && mode !== 'create' && !providedItem && Boolean(itemId) && columns.length > 0,
|
|
619
|
+
staleTime
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
const relationFields = useMemo(() => mappedFields.filter(({ field }) => field.type === 'field-relation' && !enumOptionsOverrides?.[field.slug]), [mappedFields, enumOptionsOverrides]);
|
|
623
|
+
|
|
624
|
+
const userFields = useMemo(() => mappedFields.filter(({ field }) => (field.type === 'field-userSelect' || field.type === 'field-userMultiSelect') && !enumOptionsOverrides?.[field.slug]), [mappedFields, enumOptionsOverrides]);
|
|
625
|
+
|
|
626
|
+
/*
|
|
627
|
+
* Enum options (`field-select` / `field-status` / …) normally come with the
|
|
628
|
+
* schema: the inventory-backed fetch above returns each enum-backed field
|
|
629
|
+
* with its options inlined as `field.enums` (the `expand=…,fields` inventory
|
|
630
|
+
* expansion embeds them — see the backend `getDataSource` note), which
|
|
631
|
+
* `dataSourceFieldToIField` preserves and `resolveEnumOptions` reads via
|
|
632
|
+
* `extractStaticEnumOptions`. No per-field fan-out, no whole-tenant fetch.
|
|
633
|
+
*
|
|
634
|
+
* That embed narrows enum rows to `tenant_id = <tenant> OR tenant_id IS NULL`
|
|
635
|
+
* though, so a tenant holding rows outside that filter gets a field whose
|
|
636
|
+
* dropdown opens onto nothing — no error, just an option list that cannot be
|
|
637
|
+
* picked from. `/v1/apps/enums` resolves the same options through row-level
|
|
638
|
+
* security, so it stays tenant-scoped and keeps the tenant's own enum
|
|
639
|
+
* customizations, and it fills those gaps.
|
|
640
|
+
*/
|
|
641
|
+
const slugsMissingEnumOptions = useMemo(
|
|
642
|
+
() => mappedFields
|
|
643
|
+
.filter(({ field }) => INLINE_ENUM_FIELD_TYPES.has(field.type)
|
|
644
|
+
&& !enumOptionsOverrides?.[field.slug]
|
|
645
|
+
&& extractStaticEnumOptions(field).length === 0)
|
|
646
|
+
.map(({ field }) => field.slug),
|
|
647
|
+
[mappedFields, enumOptionsOverrides]
|
|
648
|
+
);
|
|
649
|
+
|
|
650
|
+
/*
|
|
651
|
+
* One whole-tenant fetch, shared by every form view through a fixed key, and
|
|
652
|
+
* only when a field is actually missing its options — the common case never
|
|
653
|
+
* touches the network. Tenant enum metadata barely moves, hence the long
|
|
654
|
+
* stale time.
|
|
655
|
+
*/
|
|
656
|
+
const tenantEnumsQuery = useQuery<TenantEnumTree>({
|
|
657
|
+
queryKey: ['kiva', 'tenantEnums'],
|
|
658
|
+
queryFn: async () => unwrapRecord(
|
|
659
|
+
await client.get<Record<string, unknown>>('/v1/apps/enums')
|
|
660
|
+
) as TenantEnumTree,
|
|
661
|
+
enabled: enabled && slugsMissingEnumOptions.length > 0,
|
|
662
|
+
staleTime: TENANT_ENUMS_STALE_TIME
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
const remoteFieldOptionsQuery = useQuery<RemoteFieldOptionsResult>({
|
|
666
|
+
queryKey: [
|
|
667
|
+
'kiva',
|
|
668
|
+
'formView',
|
|
669
|
+
'remoteOptions',
|
|
670
|
+
appSlug,
|
|
671
|
+
dataSourceSlug,
|
|
672
|
+
mappedFields.map(entry => ({
|
|
673
|
+
slug: entry.field.slug,
|
|
674
|
+
type: entry.field.type,
|
|
675
|
+
relationDataSourceId: entry.field.relationDataSourceId ?? null
|
|
676
|
+
})),
|
|
677
|
+
optionLimit,
|
|
678
|
+
resolveUserOptions,
|
|
679
|
+
resolveRelationOptions
|
|
680
|
+
],
|
|
681
|
+
queryFn: async () => {
|
|
682
|
+
const result: RemoteFieldOptionsResult = {
|
|
683
|
+
users: [],
|
|
684
|
+
relations: {}
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
const [usersResponse] = await Promise.all([
|
|
688
|
+
resolveUserOptions && userFields.length > 0 ? client.get<{ data: Array<Record<string, unknown>> }>('/v1/users') : Promise.resolve(null),
|
|
689
|
+
/*
|
|
690
|
+
* Relation dropdowns need the target data source's app slug + slug +
|
|
691
|
+
* fields to build the option query. Resolve each target through the
|
|
692
|
+
* inventory cache (`getById`) instead of pulling the ENTIRE tenant
|
|
693
|
+
* catalog with `/v1/apps/data-sources?expand=fields`. The first
|
|
694
|
+
* `getById` warms the shared inventory (one request, shared with the
|
|
695
|
+
* schema fetch above); the rest are cache hits. Only the related
|
|
696
|
+
* records themselves (`/items`) remain a genuine per-relation fetch.
|
|
697
|
+
*/
|
|
698
|
+
resolveRelationOptions && relationFields.length > 0 ? Promise.all(relationFields.map(async ({ field }) => {
|
|
699
|
+
const { relationDataSourceId } = field;
|
|
700
|
+
|
|
701
|
+
if (!relationDataSourceId) return;
|
|
702
|
+
|
|
703
|
+
const target = await dataSourcesClient.getById(relationDataSourceId).catch(() => null);
|
|
704
|
+
|
|
705
|
+
if (!target) return;
|
|
706
|
+
|
|
707
|
+
const targetRecord = toRecord(target);
|
|
708
|
+
const targetAppSlug = pickString(targetRecord, 'appSlug', 'app_slug');
|
|
709
|
+
const targetSlug = pickString(targetRecord, 'slug');
|
|
710
|
+
|
|
711
|
+
if (!targetAppSlug || !targetSlug) return;
|
|
712
|
+
|
|
713
|
+
const targetFields = Array.isArray(targetRecord.fields) ? (targetRecord.fields as Array<DataSourceField>) : [];
|
|
714
|
+
|
|
715
|
+
const optionColumns = buildRelationOptionColumns(field, targetFields);
|
|
716
|
+
|
|
717
|
+
const relationItemsResponse = await client.get<Array<Record<string, unknown>> | { data: Array<Record<string, unknown>> }>(
|
|
718
|
+
`/v1/apps/${targetAppSlug}/data-sources/${targetSlug}/items`,
|
|
719
|
+
{
|
|
720
|
+
columns: optionColumns.join(', '),
|
|
721
|
+
limit: optionLimit
|
|
722
|
+
} as Parameters<typeof client.get>[1]
|
|
723
|
+
);
|
|
724
|
+
|
|
725
|
+
const items = unwrapArray(relationItemsResponse);
|
|
726
|
+
|
|
727
|
+
result.relations[field.slug] = items
|
|
728
|
+
.map(record => relationRecordToEnumOption(record, field, targetFields))
|
|
729
|
+
.filter((option): option is EnumOption => option !== null);
|
|
730
|
+
})) : Promise.resolve(null)
|
|
731
|
+
]);
|
|
732
|
+
|
|
733
|
+
if (usersResponse) {
|
|
734
|
+
result.users = unwrapArray(usersResponse).map(userRecordToEnumOption).filter((option): option is EnumOption => option !== null);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return result;
|
|
738
|
+
},
|
|
739
|
+
enabled: enabled && mappedFields.length > 0 && (
|
|
740
|
+
(resolveUserOptions && userFields.length > 0)
|
|
741
|
+
|| (resolveRelationOptions && relationFields.length > 0)
|
|
742
|
+
),
|
|
743
|
+
staleTime
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
const rawItem = useMemo(() => providedItem ?? itemQuery.data ?? {}, [providedItem, itemQuery.data]);
|
|
747
|
+
|
|
748
|
+
const mergedDefaultValues = useMemo(() => buildInitialValues(mappedFields.map(entry => entry.field), rawItem, providedDefaultValues), [mappedFields, rawItem, providedDefaultValues]);
|
|
749
|
+
|
|
750
|
+
/*
|
|
751
|
+
* Upload a picked File to Kiva storage and resolve to the stored value
|
|
752
|
+
* (`{ source, file_name, signed_url, file_type, file_size }`). Injected into
|
|
753
|
+
* image / file fields (via the engine's `uploadFile`) so they persist a real
|
|
754
|
+
* value instead of a raw `File` (which JSON-serializes to `{}` and silently
|
|
755
|
+
* drops the upload). The endpoint is record-agnostic, so it works in create
|
|
756
|
+
* mode too.
|
|
757
|
+
*/
|
|
758
|
+
const uploadFieldFile = useCallback(
|
|
759
|
+
async (_type: IFieldType, file: File): Promise<StoredFileValue | null> => {
|
|
760
|
+
const formData = new FormData();
|
|
761
|
+
|
|
762
|
+
formData.append('file', file, file.name);
|
|
763
|
+
|
|
764
|
+
const response = await client.post<unknown>(
|
|
765
|
+
`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/files/upload`,
|
|
766
|
+
formData as Parameters<typeof client.post>[1]
|
|
767
|
+
);
|
|
768
|
+
|
|
769
|
+
let payload: unknown = response;
|
|
770
|
+
|
|
771
|
+
for (let depth = 0; depth < 3; depth++) {
|
|
772
|
+
if (
|
|
773
|
+
payload
|
|
774
|
+
&& typeof payload === 'object'
|
|
775
|
+
&& 'data' in payload
|
|
776
|
+
&& !('file_name' in payload)
|
|
777
|
+
&& !('signed_url' in payload)
|
|
778
|
+
) {
|
|
779
|
+
payload = (payload as { data: unknown }).data;
|
|
780
|
+
} else {
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
return payload && typeof payload === 'object' ? (payload as StoredFileValue) : null;
|
|
786
|
+
},
|
|
787
|
+
[client, appSlug, dataSourceSlug]
|
|
788
|
+
);
|
|
789
|
+
|
|
790
|
+
const resolveEnumOptionsForField = useCallback(
|
|
791
|
+
(field: IField) => {
|
|
792
|
+
let options = resolveEnumOptions(field, remoteFieldOptionsQuery.data, enumOptionsOverrides);
|
|
793
|
+
|
|
794
|
+
/*
|
|
795
|
+
* Nothing inline for an enum-backed field — read the tenant enum tree
|
|
796
|
+
* instead of leaving the user with a dropdown that opens onto nothing.
|
|
797
|
+
*/
|
|
798
|
+
if (
|
|
799
|
+
options.length === 0
|
|
800
|
+
&& INLINE_ENUM_FIELD_TYPES.has(field.type)
|
|
801
|
+
&& !enumOptionsOverrides?.[field.slug]
|
|
802
|
+
) {
|
|
803
|
+
options = tenantEnumOptions(
|
|
804
|
+
tenantEnumsQuery.data,
|
|
805
|
+
appSlug,
|
|
806
|
+
dataSourceSlug,
|
|
807
|
+
field.slug
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/*
|
|
812
|
+
* Relation options are fetched as a bounded window (`optionLimit`). When
|
|
813
|
+
* the currently-selected record falls outside that window the dropdown
|
|
814
|
+
* would render an empty placeholder even though the record carries a
|
|
815
|
+
* value. The item already comes back expanded as `{ id, name }`, so seed
|
|
816
|
+
* that record as an option when it is missing — the field then shows its
|
|
817
|
+
* label regardless of the fetch window.
|
|
818
|
+
*/
|
|
819
|
+
if (field.type === 'field-relation') {
|
|
820
|
+
const seed = relationSeedOptionFromValue(rawItem[field.slug]);
|
|
821
|
+
|
|
822
|
+
if (seed && !options.some(option => option.id === seed.id)) {
|
|
823
|
+
options = [seed, ...options];
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (!dynamicEnumOptionTranslator) return options;
|
|
828
|
+
|
|
829
|
+
return options.map((option) => {
|
|
830
|
+
const next = dynamicEnumOptionTranslator(option, field);
|
|
831
|
+
|
|
832
|
+
return typeof next === 'string' && next !== option.name ? { ...option, name: next } : option;
|
|
833
|
+
});
|
|
834
|
+
},
|
|
835
|
+
[
|
|
836
|
+
remoteFieldOptionsQuery.data,
|
|
837
|
+
tenantEnumsQuery.data,
|
|
838
|
+
appSlug,
|
|
839
|
+
dataSourceSlug,
|
|
840
|
+
enumOptionsOverrides,
|
|
841
|
+
dynamicEnumOptionTranslator,
|
|
842
|
+
rawItem
|
|
843
|
+
]
|
|
844
|
+
);
|
|
845
|
+
|
|
846
|
+
/*
|
|
847
|
+
* Persistence sink handed to the engine. Mirrors the previous `submitMutation`
|
|
848
|
+
* branching: caller `onSubmit` wins, else create/update via the generated
|
|
849
|
+
* `collection` or the raw Kiva items endpoint. `forceUpdate` is set by
|
|
850
|
+
* inline click-to-edit saves in `view` mode.
|
|
851
|
+
*/
|
|
852
|
+
const handleSubmit = useCallback<FormViewEngineInput['onSubmit']>(
|
|
853
|
+
async (payload, context, forceUpdate) => {
|
|
854
|
+
if (onSubmit) {
|
|
855
|
+
return onSubmit(payload, context as KivaFormViewCallbackContext);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
if (context.mode === 'create' && !forceUpdate) {
|
|
859
|
+
if (collection?.create) {
|
|
860
|
+
return collection.create(payload);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
return client.post(`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items`, payload);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
if ((context.mode === 'edit' || forceUpdate) && context.itemId) {
|
|
867
|
+
if (collection?.update) {
|
|
868
|
+
return collection.update(context.itemId, payload);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
return client.patch(`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items/${context.itemId}`, payload);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
return payload;
|
|
875
|
+
},
|
|
876
|
+
[
|
|
877
|
+
onSubmit,
|
|
878
|
+
collection,
|
|
879
|
+
client,
|
|
880
|
+
appSlug,
|
|
881
|
+
dataSourceSlug
|
|
882
|
+
]
|
|
883
|
+
);
|
|
884
|
+
|
|
885
|
+
const engineTransformSubmit = useMemo<FormViewEngineInput['transformSubmit']>(
|
|
886
|
+
() => (payload, context) => withChangedAutonumberOnly(
|
|
887
|
+
transformSubmit ? transformSubmit(payload, context as KivaFormViewCallbackContext) : payload,
|
|
888
|
+
mergedDefaultValues
|
|
889
|
+
),
|
|
890
|
+
[transformSubmit, mergedDefaultValues]
|
|
891
|
+
);
|
|
892
|
+
|
|
893
|
+
const refetchItem = useCallback(() => {
|
|
894
|
+
if (!providedItem) {
|
|
895
|
+
void itemQuery.refetch();
|
|
896
|
+
}
|
|
897
|
+
}, [itemQuery, providedItem]);
|
|
898
|
+
|
|
899
|
+
/*
|
|
900
|
+
* The tenant enum fetch counts too: without it a field the schema left empty
|
|
901
|
+
* would render its (empty) dropdown for a beat before the fallback lands.
|
|
902
|
+
*/
|
|
903
|
+
const isFormReady = !dataSourceQuery.isLoading
|
|
904
|
+
&& !itemQuery.isLoading
|
|
905
|
+
&& !remoteFieldOptionsQuery.isLoading
|
|
906
|
+
&& !tenantEnumsQuery.isLoading;
|
|
907
|
+
|
|
908
|
+
const engineFieldLayout = useMemo(() => {
|
|
909
|
+
if (!autonumberEditable) return fieldLayoutWithEnumEditor;
|
|
910
|
+
const current = fieldLayoutWithEnumEditor?.[AUTONUMBER_FIELD_SLUG];
|
|
911
|
+
|
|
912
|
+
return {
|
|
913
|
+
...fieldLayoutWithEnumEditor,
|
|
914
|
+
[AUTONUMBER_FIELD_SLUG]: {
|
|
915
|
+
...current,
|
|
916
|
+
fieldProps: { decimal: false, thousandsSeparator: '', ...current?.fieldProps } as KivaFormViewFieldLayout['fieldProps']
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
}, [autonumberEditable, fieldLayoutWithEnumEditor]);
|
|
920
|
+
|
|
921
|
+
const engine = useFormViewEngine({
|
|
922
|
+
fields: mappedFields,
|
|
923
|
+
mode,
|
|
924
|
+
initialValues: mergedDefaultValues,
|
|
925
|
+
itemId,
|
|
926
|
+
dataSource: resolvedDataSource,
|
|
927
|
+
fieldOrder,
|
|
928
|
+
hiddenFieldSlugs,
|
|
929
|
+
fieldLayout: engineFieldLayout,
|
|
930
|
+
layout,
|
|
931
|
+
gridColumns,
|
|
932
|
+
labelAlign: resolvedLabelAlign,
|
|
933
|
+
labelWidth: resolvedLabelWidth,
|
|
934
|
+
fieldSize: resolvedFieldSize,
|
|
935
|
+
fieldVariant: resolvedFieldVariant,
|
|
936
|
+
includeReadOnlyFields,
|
|
937
|
+
validationTokens,
|
|
938
|
+
unsupportedFieldBehavior,
|
|
939
|
+
disabled,
|
|
940
|
+
clickToEdit,
|
|
941
|
+
isReady: isFormReady,
|
|
942
|
+
resolveEnumOptions: resolveEnumOptionsForField,
|
|
943
|
+
uploadFile: uploadFieldFile,
|
|
944
|
+
formActions: resolvedFormActions,
|
|
945
|
+
formCustomValidations: resolvedFormCustomValidations,
|
|
946
|
+
onSubmit: handleSubmit,
|
|
947
|
+
transformSubmit: engineTransformSubmit,
|
|
948
|
+
onSubmitSuccess,
|
|
949
|
+
onSubmitError,
|
|
950
|
+
refetchItem,
|
|
951
|
+
appSlug,
|
|
952
|
+
dataSourceSlug,
|
|
953
|
+
client
|
|
954
|
+
});
|
|
955
|
+
|
|
956
|
+
const refetch = useCallback(() => {
|
|
957
|
+
void dataSourceQuery.refetch();
|
|
958
|
+
if (itemId && !providedItem) {
|
|
959
|
+
void itemQuery.refetch();
|
|
960
|
+
}
|
|
961
|
+
if (remoteFieldOptionsQuery.isEnabled) {
|
|
962
|
+
void remoteFieldOptionsQuery.refetch();
|
|
963
|
+
}
|
|
964
|
+
if (tenantEnumsQuery.isEnabled) {
|
|
965
|
+
void tenantEnumsQuery.refetch();
|
|
966
|
+
}
|
|
967
|
+
}, [
|
|
968
|
+
dataSourceQuery,
|
|
969
|
+
itemId,
|
|
970
|
+
itemQuery,
|
|
971
|
+
providedItem,
|
|
972
|
+
remoteFieldOptionsQuery,
|
|
973
|
+
tenantEnumsQuery
|
|
974
|
+
]);
|
|
975
|
+
|
|
976
|
+
/*
|
|
977
|
+
* The enum fallback is deliberately left out: it only ever adds options, so a
|
|
978
|
+
* failed fetch must not take the whole form down with it.
|
|
979
|
+
*/
|
|
980
|
+
const error = (dataSourceQuery.error ?? itemQuery.error ?? remoteFieldOptionsQuery.error) as Error | null;
|
|
981
|
+
|
|
982
|
+
return {
|
|
983
|
+
...engine,
|
|
984
|
+
dataSource: resolvedDataSource,
|
|
985
|
+
columns,
|
|
986
|
+
isLoading: dataSourceQuery.isLoading
|
|
987
|
+
|| itemQuery.isLoading
|
|
988
|
+
|| remoteFieldOptionsQuery.isLoading
|
|
989
|
+
|| tenantEnumsQuery.isLoading,
|
|
990
|
+
error,
|
|
991
|
+
refetch
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
const SYSTEM_USER_SLUGS = new Set([
|
|
996
|
+
'created_by',
|
|
997
|
+
'last_modified_by',
|
|
998
|
+
'record_owner',
|
|
999
|
+
'modified_by',
|
|
1000
|
+
'updated_by',
|
|
1001
|
+
'owner',
|
|
1002
|
+
'assigned_to',
|
|
1003
|
+
'assignee'
|
|
1004
|
+
]);
|
|
1005
|
+
|
|
1006
|
+
function isSystemUserSlug(slug: string): boolean {
|
|
1007
|
+
if (!slug) return false;
|
|
1008
|
+
const normalized = slug.toLowerCase();
|
|
1009
|
+
|
|
1010
|
+
if (SYSTEM_USER_SLUGS.has(normalized)) return true;
|
|
1011
|
+
|
|
1012
|
+
/*
|
|
1013
|
+
* Catch common variants like `assigned_to_user`, `approved_by_user_id`,
|
|
1014
|
+
* `record_owner_id` without forcing every Kiva app to maintain a
|
|
1015
|
+
* bespoke `mapField` override.
|
|
1016
|
+
*/
|
|
1017
|
+
return /(?:^|_)(?:created|modified|updated|approved|assigned|owned)_by(?:_|$)/.test(normalized)
|
|
1018
|
+
|| /(?:^|_)owner(?:_|$)/.test(normalized);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/** The record number as a plain number input; the API keeps it only when the setting is on. */
|
|
1022
|
+
function unlockAutonumberField(field: IField): IField {
|
|
1023
|
+
if (field.slug !== AUTONUMBER_FIELD_SLUG) return field;
|
|
1024
|
+
|
|
1025
|
+
return { ...field, type: field.type === 'field-autonumber' ? 'field-number' : field.type, readOnly: false };
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/*
|
|
1029
|
+
* The record number goes out only when it was changed from the value the form
|
|
1030
|
+
* started with: re-sending a loaded number could undo someone else's
|
|
1031
|
+
* renumbering, a number copied in through `defaultValues` (a duplicate) belongs
|
|
1032
|
+
* to another record, and an emptied one means "assign one" on create and "keep
|
|
1033
|
+
* it" on edit.
|
|
1034
|
+
*/
|
|
1035
|
+
function withChangedAutonumberOnly(payload: Record<string, unknown>, initial: Record<string, unknown>): Record<string, unknown> {
|
|
1036
|
+
if (!(AUTONUMBER_FIELD_SLUG in payload)) return payload;
|
|
1037
|
+
const value = payload[AUTONUMBER_FIELD_SLUG];
|
|
1038
|
+
const empty = value === null || value === undefined || value === '';
|
|
1039
|
+
const unchanged = String(value ?? '') === String(initial[AUTONUMBER_FIELD_SLUG] ?? '');
|
|
1040
|
+
|
|
1041
|
+
if (!empty && !unchanged) return payload;
|
|
1042
|
+
const { [AUTONUMBER_FIELD_SLUG]: _unchanged, ...rest } = payload;
|
|
1043
|
+
|
|
1044
|
+
return rest;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function dataSourceFieldToIField(field: DataSourceField): IField {
|
|
1048
|
+
const raw = toRecord(field);
|
|
1049
|
+
const options = mergeFieldOptions(raw);
|
|
1050
|
+
const slug = pickString(raw, 'slug') ?? pickString(raw, 'id') ?? '';
|
|
1051
|
+
const rawType = (pickString(raw, 'type') ?? 'field-text') as IFieldType;
|
|
1052
|
+
/*
|
|
1053
|
+
* System audit fields (`created_by`, `last_modified_by`, `record_owner`,
|
|
1054
|
+
* …) come back from Kiva as plain UUID strings typed `field-text`.
|
|
1055
|
+
* Treat them as `field-userSelect` so the form view renders a user
|
|
1056
|
+
* picker (and the value renderer shows the user chip) without each app
|
|
1057
|
+
* having to override `mapField` manually.
|
|
1058
|
+
*
|
|
1059
|
+
* The coercion is gated on the raw type still being `field-text` — the
|
|
1060
|
+
* heuristic exists solely to upgrade those untyped UUID columns. A field
|
|
1061
|
+
* whose schema already declares a concrete type must keep it: e.g.
|
|
1062
|
+
* `owner_product_id` is `field-relation` → core_product on system data
|
|
1063
|
+
* sources, and the slug heuristic used to hijack it into a user picker
|
|
1064
|
+
* (issue #2596).
|
|
1065
|
+
*/
|
|
1066
|
+
const type = rawType === 'field-text' && isSystemUserSlug(slug) ? 'field-userSelect' as IFieldType : rawType;
|
|
1067
|
+
|
|
1068
|
+
const editorOptions = toRecord(options?.editorOptions);
|
|
1069
|
+
/*
|
|
1070
|
+
* Preserve the enum options the backend inlines onto enum-backed fields when
|
|
1071
|
+
* the schema is fetched with `expand=…,fields` (via the inventory cache).
|
|
1072
|
+
* Without this the mapped `IField` dropped `enums`, forcing the old
|
|
1073
|
+
* `/v1/apps/enums` whole-tenant fallback. `extractStaticEnumOptions` reads
|
|
1074
|
+
* this array directly.
|
|
1075
|
+
*/
|
|
1076
|
+
const inlineEnums = Array.isArray(raw.enums) ? extractStaticEnumOptions(field as unknown as IField) : undefined;
|
|
1077
|
+
|
|
1078
|
+
return {
|
|
1079
|
+
id: pickString(raw, 'id') ?? pickString(raw, 'slug') ?? '',
|
|
1080
|
+
name: pickString(raw, 'name') ?? pickString(raw, 'slug') ?? '',
|
|
1081
|
+
slug,
|
|
1082
|
+
type,
|
|
1083
|
+
enums: inlineEnums,
|
|
1084
|
+
defaultValue: pickString(raw, 'defaultValue', 'default_value') ?? null,
|
|
1085
|
+
/*
|
|
1086
|
+
* Also accepts the designer's TUPLE spelling (`['maxValue', 10]`), which a
|
|
1087
|
+
* plain string filter dropped — so a numeric or length bound configured on
|
|
1088
|
+
* the data-source field never reached the runtime.
|
|
1089
|
+
*/
|
|
1090
|
+
validations: pickValidationTokens(raw, 'validations', 'validationRules'),
|
|
1091
|
+
/*
|
|
1092
|
+
* `editorOptions.forceReadOnly` / `editorOptions.readOnly` lock a field at
|
|
1093
|
+
* the schema level. Reading only the top-level column meant system-managed
|
|
1094
|
+
* fields (a version counter, a trigger-maintained total) rendered editable,
|
|
1095
|
+
* promising an edit the backend then discards.
|
|
1096
|
+
*/
|
|
1097
|
+
readOnly: (pickBoolean(raw, 'readOnly', 'read_only') ?? false)
|
|
1098
|
+
|| (pickBoolean(editorOptions ?? {}, 'forceReadOnly', 'readOnly') ?? false),
|
|
1099
|
+
options,
|
|
1100
|
+
relationDataSourceId: pickString(raw, 'relationDataSourceId', 'relation_data_source_id') ?? null,
|
|
1101
|
+
avatarMapping: normalizeAvatarMapping(raw, options),
|
|
1102
|
+
/*
|
|
1103
|
+
* A tree/hierarchical relation is marked with `editorOptions.nestedByField`
|
|
1104
|
+
* (the parent-pointer slug) — its presence IS the flag. Reading only a
|
|
1105
|
+
* `nested` boolean + `nestedByProp`, keys the stored config never uses, let
|
|
1106
|
+
* a configured tree relation silently render flat. Legacy keys stay
|
|
1107
|
+
* higher-priority so an explicit setting still wins.
|
|
1108
|
+
*/
|
|
1109
|
+
nested: pickBoolean(raw, 'nested')
|
|
1110
|
+
?? pickBoolean(options ?? {}, 'nested')
|
|
1111
|
+
?? (pickString(editorOptions ?? {}, 'nestedByField') ? true : null),
|
|
1112
|
+
nestedByProp: pickString(raw, 'nestedByProp', 'nested_by_prop')
|
|
1113
|
+
?? pickString(options ?? {}, 'nestedByProp', 'nested_by_prop')
|
|
1114
|
+
?? pickString(editorOptions ?? {}, 'nestedByField')
|
|
1115
|
+
?? null,
|
|
1116
|
+
itemMapping: normalizeItemMapping(raw, options),
|
|
1117
|
+
computedHidden: normalizeComputedBooleanFormula(editorOptions?.computedHidden),
|
|
1118
|
+
computedRequired: normalizeComputedBooleanFormula(editorOptions?.computedRequired),
|
|
1119
|
+
computedReadonly: normalizeComputedBooleanFormula(editorOptions?.computedReadonly),
|
|
1120
|
+
computedLabel: typeof editorOptions?.computedLabel === 'string' ? editorOptions.computedLabel : null,
|
|
1121
|
+
computedDescription: typeof editorOptions?.computedDescription === 'string' ? editorOptions.computedDescription : null,
|
|
1122
|
+
computedFormula: typeof editorOptions?.computedFormula === 'string' ? editorOptions.computedFormula : null
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
function mergeFieldOptions(raw: Record<string, unknown>): Record<string, unknown> | null {
|
|
1127
|
+
const directOptions = toRecord(raw.options);
|
|
1128
|
+
const directEditorOptions = toRecord(raw.editorOptions);
|
|
1129
|
+
const nestedEditorOptions = directOptions ? toRecord(directOptions.editorOptions) : null;
|
|
1130
|
+
const merged: Record<string, unknown> = {
|
|
1131
|
+
...(directOptions ?? {})
|
|
1132
|
+
};
|
|
1133
|
+
|
|
1134
|
+
if (directEditorOptions && !('editorOptions' in merged)) {
|
|
1135
|
+
merged.editorOptions = directEditorOptions;
|
|
1136
|
+
} else if (nestedEditorOptions) {
|
|
1137
|
+
merged.editorOptions = nestedEditorOptions;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
return Object.keys(merged).length > 0 ? merged : null;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
function normalizeAvatarMapping(
|
|
1144
|
+
raw: Record<string, unknown>,
|
|
1145
|
+
options: Record<string, unknown> | null
|
|
1146
|
+
): IField['avatarMapping'] {
|
|
1147
|
+
const source = toRecord(raw.avatarMapping) ?? toRecord(options?.avatarMapping);
|
|
1148
|
+
|
|
1149
|
+
if (!source) return null;
|
|
1150
|
+
|
|
1151
|
+
return {
|
|
1152
|
+
iconField: pickString(source, 'iconField', 'icon_field') ?? null,
|
|
1153
|
+
colorField: pickString(source, 'colorField', 'color_field') ?? null,
|
|
1154
|
+
imageField: pickString(source, 'imageField', 'image_field') ?? null
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
function normalizeItemMapping(
|
|
1159
|
+
raw: Record<string, unknown>,
|
|
1160
|
+
options: Record<string, unknown> | null
|
|
1161
|
+
): IField['itemMapping'] {
|
|
1162
|
+
const source = toRecord(raw.itemMapping) ?? toRecord(options?.itemMapping);
|
|
1163
|
+
|
|
1164
|
+
if (!source) return null;
|
|
1165
|
+
|
|
1166
|
+
return {
|
|
1167
|
+
iconField: pickString(source, 'iconField', 'icon_field') ?? null,
|
|
1168
|
+
colorField: pickString(source, 'colorField', 'color_field') ?? null,
|
|
1169
|
+
imageField: pickString(source, 'imageField', 'image_field') ?? null,
|
|
1170
|
+
descriptionField: pickString(source, 'descriptionField', 'description_field') ?? null
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function normalizeComputedBooleanFormula(raw: unknown): ComputedBooleanFormula {
|
|
1175
|
+
if (!raw) return null;
|
|
1176
|
+
if (typeof raw === 'string') return raw || null;
|
|
1177
|
+
if (
|
|
1178
|
+
typeof raw === 'object'
|
|
1179
|
+
&& 'combinator' in raw
|
|
1180
|
+
&& 'rules' in raw
|
|
1181
|
+
&& Array.isArray((raw as Record<string, unknown>).rules)
|
|
1182
|
+
) {
|
|
1183
|
+
return raw as ComputedBooleanFormula;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
return null;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
const MISSING_COLUMN_PATTERN = /Field '([^']+)' not found in data source/i;
|
|
1190
|
+
|
|
1191
|
+
/**
|
|
1192
|
+
* Pull the offending column slug out of a Kiva "Field 'X' not found in data
|
|
1193
|
+
* source" error so the item query can strip it and retry. The error surfaces
|
|
1194
|
+
* differently across HTTP clients (directly on the thrown object, on
|
|
1195
|
+
* `error.response.data`, or in `error.message`), so we probe all three shapes.
|
|
1196
|
+
*/
|
|
1197
|
+
function extractMissingColumn(error: unknown): string | null {
|
|
1198
|
+
if (!error || typeof error !== 'object') return null;
|
|
1199
|
+
|
|
1200
|
+
const candidates: Array<unknown> = [];
|
|
1201
|
+
const record = error as Record<string, unknown>;
|
|
1202
|
+
|
|
1203
|
+
candidates.push(record.error_description, record.message);
|
|
1204
|
+
|
|
1205
|
+
const { response } = record;
|
|
1206
|
+
|
|
1207
|
+
if (response && typeof response === 'object') {
|
|
1208
|
+
const { data } = response as Record<string, unknown>;
|
|
1209
|
+
|
|
1210
|
+
if (data && typeof data === 'object') {
|
|
1211
|
+
candidates.push(
|
|
1212
|
+
(data as Record<string, unknown>).error_description,
|
|
1213
|
+
(data as Record<string, unknown>).message
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
for (const candidate of candidates) {
|
|
1219
|
+
if (typeof candidate === 'string') {
|
|
1220
|
+
const match = candidate.match(MISSING_COLUMN_PATTERN);
|
|
1221
|
+
|
|
1222
|
+
if (match?.[1]) return match[1];
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
return null;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
function buildFieldQueryColumns(fields: Array<IField>): Array<string> {
|
|
1230
|
+
return uniqueStrings(fields.flatMap(getFieldQueryKeys));
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
const LABEL_FIELD_CANDIDATES = [
|
|
1234
|
+
'name',
|
|
1235
|
+
'title',
|
|
1236
|
+
'display_name',
|
|
1237
|
+
'displayName',
|
|
1238
|
+
'full_name',
|
|
1239
|
+
'fullName',
|
|
1240
|
+
'subject',
|
|
1241
|
+
'code',
|
|
1242
|
+
'email',
|
|
1243
|
+
'label',
|
|
1244
|
+
'slug'
|
|
1245
|
+
] as const;
|
|
1246
|
+
|
|
1247
|
+
const TEXTUAL_FIELD_TYPES = new Set<IFieldType>([
|
|
1248
|
+
'field-text',
|
|
1249
|
+
'field-textarea',
|
|
1250
|
+
'field-email',
|
|
1251
|
+
'field-phone',
|
|
1252
|
+
'field-url',
|
|
1253
|
+
'field-color',
|
|
1254
|
+
'field-icon',
|
|
1255
|
+
'field-display',
|
|
1256
|
+
'field-htmlEditor',
|
|
1257
|
+
'field-emailEditor',
|
|
1258
|
+
'field-codeEditor',
|
|
1259
|
+
'field-formula',
|
|
1260
|
+
'field-relatedField',
|
|
1261
|
+
'field-enum',
|
|
1262
|
+
'field-code',
|
|
1263
|
+
'field-number',
|
|
1264
|
+
'field-money',
|
|
1265
|
+
'field-percent',
|
|
1266
|
+
'field-duration',
|
|
1267
|
+
'field-rating',
|
|
1268
|
+
'field-select',
|
|
1269
|
+
'field-radioGroup',
|
|
1270
|
+
'field-status',
|
|
1271
|
+
'field-json',
|
|
1272
|
+
'field-docEditor',
|
|
1273
|
+
'field-systemEnum'
|
|
1274
|
+
]);
|
|
1275
|
+
|
|
1276
|
+
/** Field types whose options are carried by the schema's inline `enums`. */
|
|
1277
|
+
const INLINE_ENUM_FIELD_TYPES = new Set<IFieldType>([
|
|
1278
|
+
'field-select',
|
|
1279
|
+
'field-radioGroup',
|
|
1280
|
+
'field-enum',
|
|
1281
|
+
'field-systemEnum',
|
|
1282
|
+
'field-status',
|
|
1283
|
+
'field-multiSelect',
|
|
1284
|
+
'field-tagSelect'
|
|
1285
|
+
]);
|
|
1286
|
+
|
|
1287
|
+
/** Tenant enum tree: app slug → data source slug → field slug → options. */
|
|
1288
|
+
type TenantEnumTree = Record<
|
|
1289
|
+
string,
|
|
1290
|
+
Record<string, Record<string, Array<unknown>>>
|
|
1291
|
+
>;
|
|
1292
|
+
|
|
1293
|
+
const TENANT_ENUMS_STALE_TIME = 30 * 60 * 1000;
|
|
1294
|
+
|
|
1295
|
+
/*
|
|
1296
|
+
* Read one field's options out of the `/v1/apps/enums` tree. The endpoint
|
|
1297
|
+
* returns rows unordered, so sort them the way the schema embed does — by sort
|
|
1298
|
+
* order with unset values last, then by name.
|
|
1299
|
+
*/
|
|
1300
|
+
function tenantEnumOptions(
|
|
1301
|
+
tree: TenantEnumTree | undefined,
|
|
1302
|
+
appSlug: string,
|
|
1303
|
+
dataSourceSlug: string,
|
|
1304
|
+
fieldSlug: string
|
|
1305
|
+
): Array<EnumOption> {
|
|
1306
|
+
const rows = tree?.[appSlug]?.[dataSourceSlug]?.[fieldSlug];
|
|
1307
|
+
|
|
1308
|
+
if (!Array.isArray(rows)) return [];
|
|
1309
|
+
|
|
1310
|
+
return rows
|
|
1311
|
+
.map((row) => {
|
|
1312
|
+
const record = toRecord(row);
|
|
1313
|
+
const option = normalizeEnumOption(row);
|
|
1314
|
+
|
|
1315
|
+
if (!option) return null;
|
|
1316
|
+
|
|
1317
|
+
const sortOrder = pickNumber(record, 'sortOrder', 'sort_order');
|
|
1318
|
+
|
|
1319
|
+
return { option, sortOrder: sortOrder ?? Number.MAX_SAFE_INTEGER };
|
|
1320
|
+
})
|
|
1321
|
+
.filter((entry): entry is { option: EnumOption; sortOrder: number } => entry !== null)
|
|
1322
|
+
.sort((left, right) => {
|
|
1323
|
+
if (left.sortOrder !== right.sortOrder) return left.sortOrder - right.sortOrder;
|
|
1324
|
+
|
|
1325
|
+
return left.option.name.localeCompare(right.option.name);
|
|
1326
|
+
})
|
|
1327
|
+
.map(entry => entry.option);
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
function resolveEnumOptions(
|
|
1331
|
+
field: IField,
|
|
1332
|
+
remote: RemoteFieldOptionsResult | undefined,
|
|
1333
|
+
overrides?: Record<string, Array<EnumOption>>
|
|
1334
|
+
): Array<EnumOption> {
|
|
1335
|
+
if (overrides?.[field.slug]) {
|
|
1336
|
+
return overrides[field.slug] ?? [];
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
switch (field.type) {
|
|
1340
|
+
case 'field-select':
|
|
1341
|
+
|
|
1342
|
+
case 'field-radioGroup':
|
|
1343
|
+
|
|
1344
|
+
case 'field-enum':
|
|
1345
|
+
|
|
1346
|
+
case 'field-systemEnum':
|
|
1347
|
+
|
|
1348
|
+
case 'field-status':
|
|
1349
|
+
|
|
1350
|
+
case 'field-multiSelect':
|
|
1351
|
+
|
|
1352
|
+
case 'field-tagSelect':
|
|
1353
|
+
/*
|
|
1354
|
+
* Options come from the field's inline `enums` (embedded by the
|
|
1355
|
+
* inventory-cached schema fetch and preserved by
|
|
1356
|
+
* `dataSourceFieldToIField`). When that comes back empty the caller falls
|
|
1357
|
+
* back to the tenant enum tree — see `resolveEnumOptionsForField`.
|
|
1358
|
+
*/
|
|
1359
|
+
return extractStaticEnumOptions(field);
|
|
1360
|
+
|
|
1361
|
+
case 'field-userSelect':
|
|
1362
|
+
|
|
1363
|
+
case 'field-userMultiSelect':
|
|
1364
|
+
return remote?.users ?? [];
|
|
1365
|
+
|
|
1366
|
+
case 'field-relation':
|
|
1367
|
+
return remote?.relations[field.slug] ?? [];
|
|
1368
|
+
|
|
1369
|
+
default:
|
|
1370
|
+
return [];
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function buildRelationOptionColumns(field: IField, targetFields: Array<DataSourceField>): Array<string> {
|
|
1375
|
+
const targetSlugs = new Set(targetFields.map(targetField => pickString(toRecord(targetField), 'slug')).filter((slug): slug is string => Boolean(slug)));
|
|
1376
|
+
const labelField = pickRelationLabelField(targetFields);
|
|
1377
|
+
const nestedByProp = field.nestedByProp ?? 'parent';
|
|
1378
|
+
const columns = [
|
|
1379
|
+
'id',
|
|
1380
|
+
labelField,
|
|
1381
|
+
field.itemMapping?.iconField,
|
|
1382
|
+
field.itemMapping?.colorField,
|
|
1383
|
+
field.itemMapping?.imageField,
|
|
1384
|
+
field.itemMapping?.descriptionField,
|
|
1385
|
+
field.nested ? nestedByProp : undefined
|
|
1386
|
+
];
|
|
1387
|
+
|
|
1388
|
+
const existingColumns = columns.filter((column): column is string => typeof column === 'string' && column.length > 0);
|
|
1389
|
+
|
|
1390
|
+
return uniqueStrings(existingColumns.filter(column => column === 'id' || targetSlugs.has(column)));
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
function pickRelationLabelField(targetFields: Array<DataSourceField>): string {
|
|
1394
|
+
const slugs = targetFields
|
|
1395
|
+
.map(field => ({
|
|
1396
|
+
slug: pickString(toRecord(field), 'slug'),
|
|
1397
|
+
type: (pickString(toRecord(field), 'type') ?? '') as IFieldType
|
|
1398
|
+
}))
|
|
1399
|
+
.filter((field): field is { slug: string; type: IFieldType } => Boolean(field.slug));
|
|
1400
|
+
|
|
1401
|
+
for (const candidate of LABEL_FIELD_CANDIDATES) {
|
|
1402
|
+
const matched = slugs.find(field => field.slug === candidate);
|
|
1403
|
+
|
|
1404
|
+
if (matched) return matched.slug;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
const textual = slugs.find(field => TEXTUAL_FIELD_TYPES.has(field.type));
|
|
1408
|
+
|
|
1409
|
+
if (textual) return textual.slug;
|
|
1410
|
+
|
|
1411
|
+
return slugs[0]?.slug ?? 'id';
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
/*
|
|
1415
|
+
* Build an option from the record's own expanded relation value (`{ id, name }`
|
|
1416
|
+
* as returned by the items endpoint). Used to guarantee the selected record is
|
|
1417
|
+
* always present in a relation dropdown, independent of the fetched window.
|
|
1418
|
+
* Returns null for plain-string ids (no label to render) or missing ids.
|
|
1419
|
+
*/
|
|
1420
|
+
function relationSeedOptionFromValue(value: unknown): EnumOption | null {
|
|
1421
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
1422
|
+
|
|
1423
|
+
const record = toRecord(value);
|
|
1424
|
+
const id = pickString(record, 'id');
|
|
1425
|
+
|
|
1426
|
+
if (!id) return null;
|
|
1427
|
+
|
|
1428
|
+
const name = pickString(record, 'name', 'title', 'display_name', 'displayName', 'label') ?? id;
|
|
1429
|
+
|
|
1430
|
+
return {
|
|
1431
|
+
id,
|
|
1432
|
+
name
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
function relationRecordToEnumOption(
|
|
1437
|
+
record: Record<string, unknown>,
|
|
1438
|
+
field: IField,
|
|
1439
|
+
targetFields: Array<DataSourceField>
|
|
1440
|
+
): EnumOption | null {
|
|
1441
|
+
const id = pickString(record, 'id');
|
|
1442
|
+
|
|
1443
|
+
if (!id) return null;
|
|
1444
|
+
|
|
1445
|
+
const labelField = pickRelationLabelField(targetFields);
|
|
1446
|
+
const name = pickString(record, labelField, 'name', 'title', 'display_name', 'displayName') ?? id;
|
|
1447
|
+
const nestedByProp = field.nestedByProp ?? 'parent';
|
|
1448
|
+
const parentValue = field.nested ? record[nestedByProp] : undefined;
|
|
1449
|
+
|
|
1450
|
+
return {
|
|
1451
|
+
id,
|
|
1452
|
+
name,
|
|
1453
|
+
icon: field.itemMapping?.iconField ? (pickString(record, field.itemMapping.iconField) ?? undefined) : undefined,
|
|
1454
|
+
color: field.itemMapping?.colorField ? (pickString(record, field.itemMapping.colorField) ?? undefined) : undefined,
|
|
1455
|
+
description: field.itemMapping?.descriptionField ? (pickString(record, field.itemMapping.descriptionField) ?? undefined) : undefined,
|
|
1456
|
+
parent: normalizeRelatedId(parentValue) ?? undefined
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function userRecordToEnumOption(record: Record<string, unknown>): EnumOption | null {
|
|
1461
|
+
const id = pickString(record, 'id', 'userId', 'user_id');
|
|
1462
|
+
|
|
1463
|
+
if (!id) return null;
|
|
1464
|
+
|
|
1465
|
+
const first = pickString(record, 'firstname', 'firstName', 'first_name', 'givenName', 'given_name');
|
|
1466
|
+
const last = pickString(record, 'lastname', 'lastName', 'last_name', 'familyName', 'family_name', 'surname');
|
|
1467
|
+
const fullName = [first, last].filter(Boolean).join(' ').trim();
|
|
1468
|
+
|
|
1469
|
+
/*
|
|
1470
|
+
* Prefer the person's name over contact details: `/v1/users` returns both a
|
|
1471
|
+
* name and an email, so falling back to email first turned user pickers into
|
|
1472
|
+
* lists of email addresses.
|
|
1473
|
+
*/
|
|
1474
|
+
const name = (fullName || null)
|
|
1475
|
+
?? pickString(record, 'display_name', 'displayName', 'fullName', 'full_name', 'name', 'title', 'username', 'email')
|
|
1476
|
+
?? id;
|
|
1477
|
+
|
|
1478
|
+
return {
|
|
1479
|
+
id,
|
|
1480
|
+
name,
|
|
1481
|
+
icon: pickString(record, 'avatar_url', 'avatarUrl', 'profile_image_url', 'profileImageUrl', 'picture', 'photo', 'avatar') ?? undefined
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
function normalizeRelatedId(value: unknown): string | null {
|
|
1486
|
+
if (typeof value === 'string' && value.length > 0) return value;
|
|
1487
|
+
if (value && typeof value === 'object') {
|
|
1488
|
+
const record = toRecord(value);
|
|
1489
|
+
|
|
1490
|
+
return pickString(record, 'id');
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
return null;
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
function normalizeColumnsInput(columns: unknown): Array<string> {
|
|
1497
|
+
if (Array.isArray(columns)) {
|
|
1498
|
+
return uniqueStrings(columns.filter((column): column is string => typeof column === 'string' && column.length > 0));
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
if (typeof columns === 'string') {
|
|
1502
|
+
return uniqueStrings(columns.split(',').map(column => column.trim()).filter(Boolean));
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
return [];
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function uniqueStrings(values: Array<string | null | undefined>): Array<string> {
|
|
1509
|
+
return Array.from(new Set(values.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)));
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
function unwrapArray<T>(value: Array<T> | { data: Array<T> } | null): Array<T> {
|
|
1513
|
+
if (Array.isArray(value)) return value;
|
|
1514
|
+
if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
|
|
1515
|
+
return (value as { data: Array<T> }).data;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
return [];
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
function unwrapRecord(
|
|
1522
|
+
value: object | { data: object } | null | undefined
|
|
1523
|
+
): Record<string, unknown> {
|
|
1524
|
+
if (!value) return {};
|
|
1525
|
+
if ('data' in value && value.data && typeof value.data === 'object' && !Array.isArray(value.data)) {
|
|
1526
|
+
return value.data as Record<string, unknown>;
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
return value as Record<string, unknown>;
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
function pickString(record: Record<string, unknown>, ...keys: Array<string>): string | null {
|
|
1533
|
+
for (const key of keys) {
|
|
1534
|
+
const value = record[key];
|
|
1535
|
+
|
|
1536
|
+
if (typeof value === 'string' && value.length > 0) return value;
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
function pickBoolean(record: Record<string, unknown>, ...keys: Array<string>): boolean | null {
|
|
1543
|
+
for (const key of keys) {
|
|
1544
|
+
const value = record[key];
|
|
1545
|
+
|
|
1546
|
+
if (typeof value === 'boolean') return value;
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
return null;
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
function pickNumber(record: Record<string, unknown>, ...keys: Array<string>): number | null {
|
|
1553
|
+
for (const key of keys) {
|
|
1554
|
+
const value = record[key];
|
|
1555
|
+
|
|
1556
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
return null;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
/** Validation rules, keeping the designer's tuple form (`['maxValue', 10]`). */
|
|
1563
|
+
function pickValidationTokens(record: Record<string, unknown>, ...keys: Array<string>): Array<string> | null {
|
|
1564
|
+
for (const key of keys) {
|
|
1565
|
+
if (!Array.isArray(record[key])) continue;
|
|
1566
|
+
|
|
1567
|
+
const tokens = normalizeValidationTokens(record[key]);
|
|
1568
|
+
|
|
1569
|
+
return tokens.length > 0 ? tokens : null;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
return null;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function toRecord(value: unknown): Record<string, unknown> {
|
|
1576
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
1577
|
+
return {};
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
return value as Record<string, unknown>;
|
|
1581
|
+
}
|