@kissflow/create-app 0.1.0

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +9 -0
  3. package/bin/index.js +80 -0
  4. package/package.json +47 -0
  5. package/scaffolders/app/index.js +49 -0
  6. package/scaffolders/app/template/_CLAUDE.md +104 -0
  7. package/scaffolders/app/template/_README.md +54 -0
  8. package/scaffolders/app/template/_env.example +10 -0
  9. package/scaffolders/app/template/_gitignore +6 -0
  10. package/scaffolders/app/template/_package.json +55 -0
  11. package/scaffolders/app/template/_prettierrc +6 -0
  12. package/scaffolders/app/template/agents/design-guidelines.md +172 -0
  13. package/scaffolders/app/template/agents/kissflow-sdk.md +257 -0
  14. package/scaffolders/app/template/agents/theming.md +61 -0
  15. package/scaffolders/app/template/cert/localhost.crt +18 -0
  16. package/scaffolders/app/template/cert/localhost.key +28 -0
  17. package/scaffolders/app/template/components.json +21 -0
  18. package/scaffolders/app/template/index.html +12 -0
  19. package/scaffolders/app/template/jsconfig.json +8 -0
  20. package/scaffolders/app/template/lib/kf-schema.json +7 -0
  21. package/scaffolders/app/template/scripts/zip.js +54 -0
  22. package/scaffolders/app/template/src/components/app-shell.jsx +208 -0
  23. package/scaffolders/app/template/src/components/fields/AggregationField.jsx +42 -0
  24. package/scaffolders/app/template/src/components/fields/AttachmentField.jsx +175 -0
  25. package/scaffolders/app/template/src/components/fields/BooleanField.jsx +47 -0
  26. package/scaffolders/app/template/src/components/fields/CheckboxField.jsx +79 -0
  27. package/scaffolders/app/template/src/components/fields/ChecklistField.jsx +190 -0
  28. package/scaffolders/app/template/src/components/fields/CurrencyField.jsx +183 -0
  29. package/scaffolders/app/template/src/components/fields/DateField.jsx +65 -0
  30. package/scaffolders/app/template/src/components/fields/DateTimeField.jsx +186 -0
  31. package/scaffolders/app/template/src/components/fields/EmailField.jsx +30 -0
  32. package/scaffolders/app/template/src/components/fields/FieldError.jsx +11 -0
  33. package/scaffolders/app/template/src/components/fields/FieldLabel.jsx +14 -0
  34. package/scaffolders/app/template/src/components/fields/GeolocationField.jsx +99 -0
  35. package/scaffolders/app/template/src/components/fields/ImageField.jsx +149 -0
  36. package/scaffolders/app/template/src/components/fields/LookupField.jsx +256 -0
  37. package/scaffolders/app/template/src/components/fields/MultiSelectField.jsx +152 -0
  38. package/scaffolders/app/template/src/components/fields/MultiUserSelectField.jsx +153 -0
  39. package/scaffolders/app/template/src/components/fields/NumberField.jsx +30 -0
  40. package/scaffolders/app/template/src/components/fields/RadioField.jsx +78 -0
  41. package/scaffolders/app/template/src/components/fields/RatingField.jsx +64 -0
  42. package/scaffolders/app/template/src/components/fields/ScannerField.jsx +62 -0
  43. package/scaffolders/app/template/src/components/fields/SelectField.jsx +74 -0
  44. package/scaffolders/app/template/src/components/fields/SequenceNumberField.jsx +22 -0
  45. package/scaffolders/app/template/src/components/fields/SignatureField.jsx +344 -0
  46. package/scaffolders/app/template/src/components/fields/SliderField.jsx +39 -0
  47. package/scaffolders/app/template/src/components/fields/SmartAttachmentField.jsx +188 -0
  48. package/scaffolders/app/template/src/components/fields/TextField.jsx +30 -0
  49. package/scaffolders/app/template/src/components/fields/TextareaField.jsx +30 -0
  50. package/scaffolders/app/template/src/components/fields/UserSelectField.jsx +76 -0
  51. package/scaffolders/app/template/src/components/fields/index.js +87 -0
  52. package/scaffolders/app/template/src/components/fields/useGeolocationPicker.js +42 -0
  53. package/scaffolders/app/template/src/components/fields/useScanner.js +43 -0
  54. package/scaffolders/app/template/src/components/form/FormAction.jsx +86 -0
  55. package/scaffolders/app/template/src/components/form/FormBody.jsx +163 -0
  56. package/scaffolders/app/template/src/components/form/FormHeader.jsx +65 -0
  57. package/scaffolders/app/template/src/components/form/ProcessActions.jsx +270 -0
  58. package/scaffolders/app/template/src/components/form/index.jsx +119 -0
  59. package/scaffolders/app/template/src/components/form/shared.jsx +213 -0
  60. package/scaffolders/app/template/src/components/tablefields/TableAggregationField.jsx +14 -0
  61. package/scaffolders/app/template/src/components/tablefields/TableAttachmentField.jsx +53 -0
  62. package/scaffolders/app/template/src/components/tablefields/TableBooleanField.jsx +26 -0
  63. package/scaffolders/app/template/src/components/tablefields/TableCheckboxField.jsx +6 -0
  64. package/scaffolders/app/template/src/components/tablefields/TableChecklistField.jsx +48 -0
  65. package/scaffolders/app/template/src/components/tablefields/TableCurrencyField.jsx +140 -0
  66. package/scaffolders/app/template/src/components/tablefields/TableDateField.jsx +49 -0
  67. package/scaffolders/app/template/src/components/tablefields/TableDateTimeField.jsx +170 -0
  68. package/scaffolders/app/template/src/components/tablefields/TableGeolocationField.jsx +69 -0
  69. package/scaffolders/app/template/src/components/tablefields/TableImageField.jsx +78 -0
  70. package/scaffolders/app/template/src/components/tablefields/TableLookupField.jsx +165 -0
  71. package/scaffolders/app/template/src/components/tablefields/TableMultiSelectField.jsx +111 -0
  72. package/scaffolders/app/template/src/components/tablefields/TableMultiUserSelectField.jsx +109 -0
  73. package/scaffolders/app/template/src/components/tablefields/TableNumberField.jsx +33 -0
  74. package/scaffolders/app/template/src/components/tablefields/TableRatingField.jsx +45 -0
  75. package/scaffolders/app/template/src/components/tablefields/TableScannerField.jsx +67 -0
  76. package/scaffolders/app/template/src/components/tablefields/TableSelectField.jsx +47 -0
  77. package/scaffolders/app/template/src/components/tablefields/TableSequenceNumberField.jsx +7 -0
  78. package/scaffolders/app/template/src/components/tablefields/TableSignatureField.jsx +59 -0
  79. package/scaffolders/app/template/src/components/tablefields/TableSliderField.jsx +26 -0
  80. package/scaffolders/app/template/src/components/tablefields/TableTextField.jsx +28 -0
  81. package/scaffolders/app/template/src/components/tablefields/TableUserSelectField.jsx +51 -0
  82. package/scaffolders/app/template/src/components/tablefields/index.js +71 -0
  83. package/scaffolders/app/template/src/components/tablefields/useTableFieldOptions.js +33 -0
  84. package/scaffolders/app/template/src/components/ui/accordion.jsx +51 -0
  85. package/scaffolders/app/template/src/components/ui/avatar.jsx +92 -0
  86. package/scaffolders/app/template/src/components/ui/badge.jsx +40 -0
  87. package/scaffolders/app/template/src/components/ui/button.jsx +61 -0
  88. package/scaffolders/app/template/src/components/ui/calendar.jsx +207 -0
  89. package/scaffolders/app/template/src/components/ui/card.jsx +92 -0
  90. package/scaffolders/app/template/src/components/ui/chart.jsx +323 -0
  91. package/scaffolders/app/template/src/components/ui/checkbox.jsx +27 -0
  92. package/scaffolders/app/template/src/components/ui/command.jsx +154 -0
  93. package/scaffolders/app/template/src/components/ui/dialog.jsx +122 -0
  94. package/scaffolders/app/template/src/components/ui/dropdown-menu.jsx +200 -0
  95. package/scaffolders/app/template/src/components/ui/input.jsx +21 -0
  96. package/scaffolders/app/template/src/components/ui/label.jsx +19 -0
  97. package/scaffolders/app/template/src/components/ui/popover.jsx +40 -0
  98. package/scaffolders/app/template/src/components/ui/progress.jsx +25 -0
  99. package/scaffolders/app/template/src/components/ui/radio-group.jsx +37 -0
  100. package/scaffolders/app/template/src/components/ui/scroll-area.jsx +48 -0
  101. package/scaffolders/app/template/src/components/ui/select.jsx +156 -0
  102. package/scaffolders/app/template/src/components/ui/separator.jsx +26 -0
  103. package/scaffolders/app/template/src/components/ui/sheet.jsx +123 -0
  104. package/scaffolders/app/template/src/components/ui/skeleton.jsx +13 -0
  105. package/scaffolders/app/template/src/components/ui/slider.jsx +61 -0
  106. package/scaffolders/app/template/src/components/ui/sonner.jsx +60 -0
  107. package/scaffolders/app/template/src/components/ui/switch.jsx +26 -0
  108. package/scaffolders/app/template/src/components/ui/table.jsx +111 -0
  109. package/scaffolders/app/template/src/components/ui/tabs.jsx +74 -0
  110. package/scaffolders/app/template/src/components/ui/textarea.jsx +18 -0
  111. package/scaffolders/app/template/src/components/ui/tooltip.jsx +43 -0
  112. package/scaffolders/app/template/src/hooks/useForm.js +841 -0
  113. package/scaffolders/app/template/src/index.css +143 -0
  114. package/scaffolders/app/template/src/lib/utils.js +6 -0
  115. package/scaffolders/app/template/src/main.jsx +18 -0
  116. package/scaffolders/app/template/src/pages/index.jsx +244 -0
  117. package/scaffolders/app/template/src/themes.css +153 -0
  118. package/scaffolders/app/template/src/themes.js +32 -0
  119. package/scaffolders/app/template/vite-kf-live.js +117 -0
  120. package/scaffolders/app/template/vite.config.js +56 -0
  121. package/scaffolders/constants.js +25 -0
  122. package/scaffolders/helpers.js +12 -0
  123. package/scaffolders/utils.js +109 -0
@@ -0,0 +1,841 @@
1
+ import { useEffect, useState, useCallback, useRef } from "react";
2
+
3
+ /**
4
+ * Custom hook to manage form state with full validation, dynamic config, and child table support.
5
+ *
6
+ * Takes a single options object (not positional args).
7
+ *
8
+ * @param {object} options
9
+ * @param {"dataform"|"board"|"process"} options.flowType - Flow type
10
+ * @param {string} options.flowId - ID of the dataform/board/process
11
+ * @param {string} [options.instanceId] - Record instance ID (omit to create new)
12
+ * @param {string} [options.viewId] - Dataform/board only: view whose layout & permissions apply
13
+ * @param {string} [options.activityInstanceId] - Process only: activity (task) instance ID
14
+ *
15
+ * @returns {object}
16
+ * - formData: object - Current field values. Child-table rows live at formData[tableId].
17
+ * - config: object - Raw getFormConfiguration() response:
18
+ * { formPermission: 'Edit'|'View', sections: [...] }
19
+ * formPermission is the outer VBAC gate (whole flow/view access) and overrides
20
+ * every field's own Permission when 'View'. Each section is either:
21
+ * { Type:'Section', Id, Name, IsHidden, Permission, Fields:[{Id, Name, Type, Widget, Required, Permission, IsHidden, IsReadOnly, Validations}] } or
22
+ * { Type:'Model', Id, Name, IsHidden, Permission, Fields:[...] } (child table columns)
23
+ * - errors: object - Validation errors, nested: { _root: { fieldId: [...] }, tableId: { rowId: { fieldId: [...] } } }
24
+ * - loading: boolean
25
+ * - error: string|null
26
+ * - isSaving: boolean - true while an updateField/updateFields autosave is in flight
27
+ * - isNewRecord: boolean
28
+ * - updateField(fieldId, value): Promise<boolean> - persists immediately (autosave)
29
+ * - updateFields(updates): Promise<boolean> - persists immediately (autosave)
30
+ * - getField(fieldId): Promise<object>
31
+ * - getFieldOptions(fieldId, tableId?, rowId?): Promise<object[]>
32
+ * - getFormData(): Promise<object>
33
+ * - parseAttachment(fieldId, file): Promise<{appliedFields, suggestedBy}> - process flows only
34
+ * - runAction(action, extra?): Promise<boolean> - single dispatcher for every lifecycle
35
+ * action, resolved from flowType. Dataform/board: 'submit' (validates, and for a new
36
+ * record finalizes the draft) or 'discard' (deletes the draft). Process: 'submit',
37
+ * 'reject', 'sendback', 'reassign', 'withdraw', 'restart', 'discard' — see
38
+ * formActions for which ones are valid at the current step. For 'reassign',
39
+ * extra.reassignedFrom should be the subset of reassignFromCandidates being
40
+ * reassigned away (defaults to all of them when the step has one assignee).
41
+ * - reassignFromCandidates: object[] - Users currently assigned to this step (the
42
+ * Reassign "from" candidates) — pass the selection through as reassignedFrom.
43
+ * - getTable(tableId): { addRow, addRows, deleteRow, deleteRows, updateRow, getRowField, getSelectedRows }
44
+ *
45
+ * @example
46
+ * const { formData, config, updateField, getTable } = useForm({ flowType: "dataform", flowId: "EmpMaster", instanceId: "emp_123" });
47
+ *
48
+ * (config.sections || []).filter(s => !s.IsHidden).map(section => {
49
+ * if (section.Type === 'Section') {
50
+ * return section.Fields.map(field =>
51
+ * <input key={field.Id} value={formData[field.Id] || ''} onChange={e => updateField(field.Id, e.target.value)} />
52
+ * );
53
+ * }
54
+ * if (section.Type === 'Model') {
55
+ * const table = getTable(section.Id);
56
+ * return (formData[section.Id] || []).map(row => ...);
57
+ * }
58
+ * });
59
+ */
60
+ // Only the four scalar keys are comparable by value. Validations is always a
61
+ // new array reference (functions are stripped by sanitizeForPostMessage), so
62
+ // comparing it would always look "changed" and defeat the optimisation.
63
+ const FIELD_STATE_KEYS = ["Permission", "IsHidden", "IsReadOnly", "Required"];
64
+
65
+ // Process item statuses (values of item._status) — mirror of the platform's
66
+ // process form STATUS constants.
67
+ const STATUS = {
68
+ DRAFT: "Draft",
69
+ INPROGRESS: "InProgress",
70
+ COMPLETED: "Completed",
71
+ REJECTED: "Rejected",
72
+ WITHDRAWN: "Withdrawn",
73
+ SENDBACK: "SendBack"
74
+ };
75
+
76
+ // Descriptor per workflow action. `key` maps to runAction(key, extra).
77
+ // Submit/Restart are the primary (advancing) actions; the comment/confirm/
78
+ // reassignee flags drive the modal. There is no generic "Save" action —
79
+ // every flow type autosaves per field (the SDK's shared form store persists
80
+ // on each updateField/updateFields call), so only real lifecycle
81
+ // transitions are listed here.
82
+ const ACTION_DEFS = {
83
+ submit: { key: "submit", label: "Submit", primary: true },
84
+ reassign: {
85
+ key: "reassign",
86
+ label: "Reassign",
87
+ requiresReassignee: true,
88
+ requiresComment: true
89
+ },
90
+ sendback: { key: "sendback", label: "Send back", requiresComment: true },
91
+ reject: {
92
+ key: "reject",
93
+ label: "Reject",
94
+ destructive: true,
95
+ requiresComment: true
96
+ },
97
+ withdraw: {
98
+ key: "withdraw",
99
+ label: "Withdraw",
100
+ destructive: true,
101
+ requiresComment: true
102
+ },
103
+ restart: { key: "restart", label: "Restart", primary: true },
104
+ discard: {
105
+ key: "discard",
106
+ label: "Discard",
107
+ destructive: true,
108
+ confirm: true
109
+ }
110
+ };
111
+
112
+ // Which actions each resolved user-status shows, ordered secondary→primary to
113
+ // suit a right-aligned action bar. Mirrors the platform ACTION_MAPPING /
114
+ // PROCESS_BUTTONS / PROGRESS_BUTTONS / INITIATOR_BUTTONS groups.
115
+ const ACTION_GROUPS = {
116
+ Draft: ["discard", "submit"],
117
+ InitiatorProgress: ["reassign", "withdraw"],
118
+ ApproverProgress: ["reassign", "sendback", "reject", "submit"],
119
+ InitiatorRejected: ["restart"],
120
+ SendBackToInitiator: ["submit"],
121
+ None: []
122
+ };
123
+
124
+ // Actions that persist form data (a comment, a corrected field) alongside
125
+ // the transition, so the form must pass validation first. Withdraw/Restart/
126
+ // Discard are exit/reset actions and skip this gate — see runAction.
127
+ const VALIDATED_ACTIONS = ["submit", "reject", "sendback", "reassign"];
128
+
129
+ // Classify the current step into a user-status bucket, mirroring the platform's
130
+ // FormActions.getUserStatus(). The custom form is never the admin/report/preview
131
+ // surface, so those branches are omitted.
132
+ function resolveUserStatus({ status, isStartStep, isSendBackToInitiator }) {
133
+ if (isSendBackToInitiator) {
134
+ if (status === STATUS.INPROGRESS) return "SendBackToInitiator";
135
+ if (status === STATUS.COMPLETED) return "None";
136
+ }
137
+ if (isStartStep && status === STATUS.INPROGRESS) return "InitiatorProgress";
138
+ if (isStartStep && status === STATUS.DRAFT) return "Draft";
139
+ if (
140
+ !isStartStep &&
141
+ ![
142
+ STATUS.REJECTED,
143
+ STATUS.WITHDRAWN,
144
+ STATUS.COMPLETED,
145
+ STATUS.SENDBACK
146
+ ].includes(status)
147
+ ) {
148
+ return "ApproverProgress";
149
+ }
150
+ if (isStartStep && [STATUS.REJECTED, STATUS.WITHDRAWN].includes(status)) {
151
+ return "InitiatorRejected";
152
+ }
153
+ return "None";
154
+ }
155
+
156
+ // Resolve the ordered workflow-action descriptors for a process form's current
157
+ // step. Single source of truth for the step→action policy. Dataform/board
158
+ // (no workflow) return [] and fall back to the plain Save button.
159
+ export function resolveProcessActions({
160
+ flowType,
161
+ status,
162
+ isStartStep,
163
+ isSendBackToInitiator
164
+ }) {
165
+ if (flowType !== "process") return [];
166
+ // Default to Draft when the SDK hasn't surfaced status yet (host not on the
167
+ // updated build) so a brand-new item still offers Submit/Discard.
168
+ const userStatus = resolveUserStatus({
169
+ status: status || STATUS.DRAFT,
170
+ isStartStep: isStartStep ?? true,
171
+ isSendBackToInitiator: Boolean(isSendBackToInitiator)
172
+ });
173
+ return (ACTION_GROUPS[userStatus] || []).map((k) => ACTION_DEFS[k]);
174
+ }
175
+
176
+ // Reduce a validation-error map to only the fields/sections that are actually
177
+ // visible, per the computed config. Works around the SDK validating hidden
178
+ // fields/sections (its runValidation marks every field visible). Prevents a
179
+ // hidden required field from blocking submit.
180
+ export function filterVisibleErrors(validationErrors, config) {
181
+ if (!validationErrors) return {};
182
+ const sections = Array.isArray(config?.sections) ? config.sections : [];
183
+
184
+ // Field ids that are visible: section not hidden AND field not hidden.
185
+ const visibleRootFields = new Set();
186
+ // Model (child-table) sections keyed by section.Id, with their visible cols.
187
+ const visibleTableCols = {};
188
+ for (const section of sections) {
189
+ if (section.IsHidden) continue;
190
+ const visibleCols = new Set();
191
+ for (const field of section.Fields || []) {
192
+ if (field.IsHidden) continue;
193
+ visibleRootFields.add(field.Id);
194
+ visibleCols.add(field.Id);
195
+ }
196
+ if (section.Type === "Model") visibleTableCols[section.Id] = visibleCols;
197
+ }
198
+
199
+ const filtered = {};
200
+ const root = {};
201
+ for (const [key, value] of Object.entries(validationErrors)) {
202
+ if (key === "_root") {
203
+ for (const [fieldId, errs] of Object.entries(value || {})) {
204
+ if (visibleRootFields.has(fieldId)) root[fieldId] = errs;
205
+ }
206
+ continue;
207
+ }
208
+
209
+ // Only treat this key as a child table if it matches an actual
210
+ // Model-section id from config. The SDK doesn't always wrap
211
+ // root-level field errors under `_root` — for some flows it returns
212
+ // them flat as `{ fieldId: [...] }` — so any other key is a
213
+ // root-level field, not a table, regardless of its shape.
214
+ const cols = visibleTableCols[key];
215
+ if (cols) {
216
+ const rows = {};
217
+ for (const [rowId, fields] of Object.entries(value || {})) {
218
+ const rowErrs = {};
219
+ for (const [colId, errs] of Object.entries(fields || {})) {
220
+ if (cols.has(colId)) rowErrs[colId] = errs;
221
+ }
222
+ if (Object.keys(rowErrs).length) rows[rowId] = rowErrs;
223
+ }
224
+ if (Object.keys(rows).length) filtered[key] = rows;
225
+ } else if (visibleRootFields.has(key)) {
226
+ root[key] = value;
227
+ }
228
+ }
229
+ if (Object.keys(root).length) filtered._root = root;
230
+ return filtered;
231
+ }
232
+
233
+ // True if the (already visibility-filtered) error map has any errors.
234
+ function hasValidationErrors(validationErrors) {
235
+ return (
236
+ Object.keys(validationErrors?.["_root"] || {}).length > 0 ||
237
+ Object.entries(validationErrors || {})
238
+ .filter(([k]) => k !== "_root")
239
+ .some(([, rows]) =>
240
+ Object.values(rows).some(
241
+ (fields) => Object.keys(fields || {}).length > 0
242
+ )
243
+ )
244
+ );
245
+ }
246
+
247
+ function mergeFieldState(config, fieldState) {
248
+ if (!config?.sections || !fieldState) return config;
249
+ return {
250
+ ...config,
251
+ formPermission: fieldState.formPermission ?? config.formPermission,
252
+ sections: config.sections.map((section) => {
253
+ const sectionUpdate = fieldState.sections?.[section.Id];
254
+ const Fields = section.Fields.map((field) => {
255
+ const update = fieldState.fields?.[field.Id];
256
+ if (!update) return field;
257
+ const changed = FIELD_STATE_KEYS.some((k) => field[k] !== update[k]);
258
+ return changed ? { ...field, ...update } : field;
259
+ });
260
+ if (sectionUpdate) {
261
+ const sectionChanged = Object.keys(sectionUpdate).some(
262
+ (k) => section[k] !== sectionUpdate[k]
263
+ );
264
+ return sectionChanged
265
+ ? { ...section, ...sectionUpdate, Fields }
266
+ : { ...section, Fields };
267
+ }
268
+ return { ...section, Fields };
269
+ })
270
+ };
271
+ }
272
+
273
+ export function useForm({
274
+ flowType,
275
+ flowId,
276
+ viewId,
277
+ instanceId,
278
+ activityInstanceId
279
+ }) {
280
+ const [formData, setFormData] = useState({});
281
+ const [config, setConfig] = useState([]);
282
+ const [errors, setErrors] = useState({});
283
+ const [loading, setLoading] = useState(false);
284
+ const [error, setError] = useState(null);
285
+ const [isSaving, setIsSaving] = useState(false);
286
+ const [isNewRecord, setIsNewRecord] = useState(false);
287
+
288
+ const formInstanceRef = useRef(null);
289
+ const flowInstanceRef = useRef(null);
290
+ const formDataRef = useRef({}); // always-fresh copy of formData for getTable rows getter
291
+ const configRef = useRef(null); // always-fresh config for visibility-aware error filtering
292
+ const tableOpsRef = useRef({}); // memoized table op objects per tableId
293
+
294
+ // Keep formDataRef in sync with formData state
295
+ useEffect(() => {
296
+ formDataRef.current = formData;
297
+ }, [formData]);
298
+
299
+ // Keep configRef in sync so callbacks can filter errors by current visibility
300
+ useEffect(() => {
301
+ configRef.current = config;
302
+ }, [config]);
303
+
304
+ // Get flow instance (dataform / board / process) — for flow-level ops like getFieldOptions
305
+ const getFlowInstance = useCallback(async () => {
306
+ if (!window.kf)
307
+ throw new Error("SDK not initialized. Make sure window.kf is available.");
308
+ if (flowInstanceRef.current) return flowInstanceRef.current;
309
+ if (!flowType || !flowId)
310
+ throw new Error("getFlowInstance requires both flowType and flowId");
311
+
312
+ if (flowType === "dataform")
313
+ flowInstanceRef.current = window.kf.app.getDataform(flowId);
314
+ else if (flowType === "board")
315
+ flowInstanceRef.current = window.kf.app.getBoard(flowId);
316
+ else if (flowType === "process")
317
+ flowInstanceRef.current = window.kf.app.getProcess(flowId);
318
+ else throw new Error(`Unknown flow type: ${flowType}`);
319
+
320
+ return flowInstanceRef.current;
321
+ }, [flowType, flowId]);
322
+
323
+ // Get form instance — initialized via initForm() on the flow instance
324
+ const getFormInstance = useCallback(async () => {
325
+ if (!window.kf)
326
+ throw new Error("SDK not initialized. Make sure window.kf is available.");
327
+ if (formInstanceRef.current) return formInstanceRef.current;
328
+
329
+ if (flowType && flowId) {
330
+ const flowInstance = await getFlowInstance();
331
+ // process.initForm(instanceId, activityInstanceId); dataform/board.initForm(instanceId, viewId) —
332
+ // the second positional arg means something different per flow type.
333
+ formInstanceRef.current =
334
+ flowType === "process"
335
+ ? await flowInstance.initForm(instanceId, activityInstanceId)
336
+ : await flowInstance.initForm(instanceId, viewId);
337
+ setIsNewRecord(!instanceId);
338
+ return formInstanceRef.current;
339
+ }
340
+
341
+ throw new Error(
342
+ "useForm requires (flowType, flowId) or a page form context"
343
+ );
344
+ }, [
345
+ flowType,
346
+ flowId,
347
+ instanceId,
348
+ viewId,
349
+ activityInstanceId,
350
+ getFlowInstance
351
+ ]);
352
+
353
+ // Initialize form: load data + config in parallel
354
+ useEffect(() => {
355
+ async function initializeForm() {
356
+ try {
357
+ setLoading(true);
358
+ setError(null);
359
+ setErrors({});
360
+
361
+ const formInstance = await getFormInstance();
362
+
363
+ const [data, rawConfig] = await Promise.all([
364
+ formInstance.toJSON(),
365
+ formInstance.getFormConfiguration()
366
+ ]);
367
+
368
+ setFormData(data || {});
369
+ setConfig(rawConfig);
370
+ } catch (err) {
371
+ setError(err.message || "Failed to load form");
372
+ console.error("Form initialization error:", err);
373
+ } finally {
374
+ setLoading(false);
375
+ }
376
+ }
377
+
378
+ if (window.kf && (flowId || flowType)) {
379
+ initializeForm();
380
+ }
381
+ }, [flowType, flowId, instanceId, getFormInstance]);
382
+
383
+ // Update single field — uses { formData, error } returned directly by updateField
384
+ const updateField = useCallback(
385
+ async (fieldId, value) => {
386
+ try {
387
+ setError(null);
388
+ const formInstance = await getFormInstance();
389
+
390
+ const currentData = await formInstance.toJSON();
391
+ if (currentData[fieldId] === value) return true;
392
+
393
+ setIsSaving(true);
394
+ await formInstance.updateField({ [fieldId]: value });
395
+ const [updatedData, validationErrors, fieldState] = await Promise.all([
396
+ formInstance.toJSON(),
397
+ formInstance.getValidationErrors(),
398
+ formInstance.getFieldState()
399
+ ]);
400
+
401
+ const mergedConfig = mergeFieldState(configRef.current, fieldState);
402
+ setFormData(updatedData || {});
403
+ setErrors(filterVisibleErrors(validationErrors, mergedConfig));
404
+ setConfig(mergedConfig);
405
+ return true;
406
+ } catch (err) {
407
+ setError(err.message || "Failed to update field");
408
+ console.error("Field update error:", err);
409
+ throw err;
410
+ } finally {
411
+ setIsSaving(false);
412
+ }
413
+ },
414
+ [getFormInstance]
415
+ );
416
+
417
+ // Update multiple fields
418
+ const updateFields = useCallback(
419
+ async (updates) => {
420
+ try {
421
+ setError(null);
422
+ const formInstance = await getFormInstance();
423
+ const currentData = await formInstance.toJSON();
424
+ let hasChanges = false;
425
+
426
+ for (const [fieldId, value] of Object.entries(updates)) {
427
+ if (currentData[fieldId] === value) continue;
428
+ if (!hasChanges) setIsSaving(true);
429
+ hasChanges = true;
430
+ await formInstance.updateField({ [fieldId]: value });
431
+ }
432
+
433
+ if (!hasChanges) return true;
434
+
435
+ const [updatedData, validationErrors, fieldState] = await Promise.all([
436
+ formInstance.toJSON(),
437
+ formInstance.getValidationErrors(),
438
+ formInstance.getFieldState()
439
+ ]);
440
+
441
+ const mergedConfig = mergeFieldState(configRef.current, fieldState);
442
+ setFormData(updatedData || {});
443
+ setErrors(filterVisibleErrors(validationErrors, mergedConfig));
444
+ setConfig(mergedConfig);
445
+ return true;
446
+ } catch (err) {
447
+ setError(err.message || "Failed to update fields");
448
+ console.error("Fields update error:", err);
449
+ throw err;
450
+ } finally {
451
+ setIsSaving(false);
452
+ }
453
+ },
454
+ [getFormInstance]
455
+ );
456
+
457
+ // Get a single field's details
458
+ const getField = useCallback(
459
+ async (fieldId) => {
460
+ try {
461
+ const formInstance = await getFormInstance();
462
+ return formInstance.getField(fieldId);
463
+ } catch (err) {
464
+ setError(err.message || "Failed to get field");
465
+ console.error("Get field error:", err);
466
+ throw err;
467
+ }
468
+ },
469
+ [getFormInstance]
470
+ );
471
+
472
+ // Get dropdown/select options for a field
473
+ const getFieldOptions = useCallback(
474
+ async (fieldId, tableId, rowId) => {
475
+ try {
476
+ const formInstance = await getFormInstance();
477
+ const flowInstance = await getFlowInstance();
478
+ return flowInstance.getFieldOptions({
479
+ fieldId,
480
+ instanceId: formInstance.instanceId,
481
+ activityInstanceId: formInstance.activityInstanceId,
482
+ tableId,
483
+ tableRowId: rowId
484
+ });
485
+ } catch (err) {
486
+ setError(err.message || "Failed to get field options");
487
+ console.error("Get field options error:", err);
488
+ throw err;
489
+ }
490
+ },
491
+ [getFlowInstance, getFormInstance]
492
+ );
493
+
494
+ // Trigger AI document parsing on a Smart Attachment field. Matching empty
495
+ // fields are auto-filled by the platform directly into the form store —
496
+ // refresh formData afterward so the UI reflects the autofill immediately.
497
+ const parseAttachment = useCallback(
498
+ async (fieldId, file) => {
499
+ if (flowType !== "process") {
500
+ throw new Error(
501
+ "Smart Attachment parsing is only available for process flows today"
502
+ );
503
+ }
504
+ try {
505
+ setError(null);
506
+ const flowInstance = await getFlowInstance();
507
+ const formInstance = await getFormInstance();
508
+ const result = await flowInstance.parseAttachment({
509
+ instanceId: formInstance.instanceId,
510
+ activityInstanceId: formInstance.activityInstanceId,
511
+ fieldId,
512
+ file
513
+ });
514
+ const updatedData = await formInstance.toJSON();
515
+ setFormData(updatedData || {});
516
+ return result; // { appliedFields, suggestedBy }
517
+ } catch (err) {
518
+ setError(err.message || "Failed to parse attachment");
519
+ console.error("Parse attachment error:", err);
520
+ throw err;
521
+ }
522
+ },
523
+ [flowType, getFlowInstance, getFormInstance]
524
+ );
525
+
526
+ // Get latest form data
527
+ const getFormData = useCallback(async () => {
528
+ const formInstance = await getFormInstance();
529
+ return formInstance.toJSON();
530
+ }, [getFormInstance]);
531
+
532
+ // Single dispatcher for every lifecycle action, resolved from flowType —
533
+ // so every caller (footer buttons, ProcessActions) can call the same
534
+ // function uniformly instead of the UI needing to know which of
535
+ // save()/discard()/runProcessAction() applies to which flow type.
536
+ //
537
+ // Process: the full workflow-action set. `extra` carries action-specific
538
+ // payload — { comment } for reject/sendback/withdraw, { stepId } for
539
+ // sendback, { reassignTo, comment, reassignType } for reassign.
540
+ // Submit/Reject/Sendback/Reassign all persist form data (a comment, a
541
+ // corrected field) alongside the transition, so they validate first and
542
+ // abort on errors; Withdraw/Restart/Discard are exit/reset actions with
543
+ // no data of their own to lose, so they skip validation.
544
+ //
545
+ // Dataform/board: only 'submit' and 'discard' are supported. 'submit'
546
+ // validates, and for a brand-new record (still an unsubmitted draft
547
+ // created by initForm) calls submitItem to finalize it — Dataform takes
548
+ // { itemId }, Board takes { instanceId }. An existing record has nothing
549
+ // left to persist here since every field edit already autosaved via
550
+ // updateField. 'discard' deletes the draft outright — Dataform takes
551
+ // { viewId } (discards "the" draft scoped to flowId+viewId server-side,
552
+ // no instanceId), Board takes { instanceId }.
553
+ const runAction = useCallback(
554
+ async (action, extra = {}) => {
555
+ if (flowType === "process") {
556
+ try {
557
+ setLoading(true);
558
+ setError(null);
559
+ const flowInstance = await getFlowInstance();
560
+ const formInstance = await getFormInstance();
561
+
562
+ const instanceId = formInstance.instanceId;
563
+ const activityInstanceId = formInstance.activityInstanceId;
564
+
565
+ if (VALIDATED_ACTIONS.includes(action)) {
566
+ const rawErrors = await formInstance.getValidationErrors();
567
+ const validationErrors = filterVisibleErrors(
568
+ rawErrors,
569
+ configRef.current
570
+ );
571
+ setErrors(validationErrors);
572
+ if (hasValidationErrors(validationErrors)) {
573
+ setError(
574
+ "Form has validation errors. Please fix them before continuing."
575
+ );
576
+ return false;
577
+ }
578
+ }
579
+
580
+ switch (action) {
581
+ case "submit":
582
+ await flowInstance.submitItem({ instanceId, activityInstanceId });
583
+ break;
584
+ case "reject":
585
+ await flowInstance.rejectItem({
586
+ instanceId,
587
+ activityInstanceId,
588
+ comment: extra.comment
589
+ });
590
+ break;
591
+ case "sendback":
592
+ await flowInstance.sendbackItem({
593
+ instanceId,
594
+ activityInstanceId,
595
+ stepId: extra.stepId,
596
+ comment: extra.comment
597
+ });
598
+ break;
599
+ case "reassign":
600
+ await flowInstance.reassignItem({
601
+ instanceId,
602
+ activityInstanceId,
603
+ reassignTo: extra.reassignTo,
604
+ reassignedFrom: extra.reassignedFrom,
605
+ comment: extra.comment,
606
+ reassignType: extra.reassignType
607
+ });
608
+ break;
609
+ case "withdraw":
610
+ await flowInstance.withdrawItem({
611
+ instanceId,
612
+ comment: extra.comment
613
+ });
614
+ break;
615
+ case "restart":
616
+ await flowInstance.restartItem({
617
+ instanceId,
618
+ activityInstanceId
619
+ });
620
+ break;
621
+ case "discard":
622
+ await flowInstance.discardItem({ instanceId });
623
+ break;
624
+ default:
625
+ throw new Error(`Unknown process action: ${action}`);
626
+ }
627
+
628
+ return true;
629
+ } catch (err) {
630
+ setError(err.message || `Failed to ${action} item`);
631
+ console.error(`Process action "${action}" error:`, err);
632
+ throw err;
633
+ } finally {
634
+ setLoading(false);
635
+ }
636
+ }
637
+
638
+ if (action === "submit") {
639
+ try {
640
+ setLoading(true);
641
+ setError(null);
642
+ const formInstance = await getFormInstance();
643
+
644
+ const rawErrors = await formInstance.getValidationErrors();
645
+ const validationErrors = filterVisibleErrors(
646
+ rawErrors,
647
+ configRef.current
648
+ );
649
+ setErrors(validationErrors);
650
+
651
+ if (hasValidationErrors(validationErrors)) {
652
+ setError(
653
+ "Form has validation errors. Please fix them before submitting."
654
+ );
655
+ return false;
656
+ }
657
+
658
+ if (isNewRecord) {
659
+ const flowInstance = await getFlowInstance();
660
+ const itemId = formInstance.instanceId;
661
+ await flowInstance.submitItem(
662
+ flowType === "board" ? { instanceId: itemId } : { itemId }
663
+ );
664
+ setIsNewRecord(false);
665
+ }
666
+
667
+ return true;
668
+ } catch (err) {
669
+ setError(err.message || "Failed to save form");
670
+ console.error("Save error:", err);
671
+ throw err;
672
+ } finally {
673
+ setLoading(false);
674
+ }
675
+ }
676
+
677
+ if (action === "discard") {
678
+ try {
679
+ setLoading(true);
680
+ setError(null);
681
+ const formInstance = await getFormInstance();
682
+ const flowInstance = await getFlowInstance();
683
+ await flowInstance.discardItem(
684
+ flowType === "board"
685
+ ? { instanceId: formInstance.instanceId }
686
+ : { viewId }
687
+ );
688
+ return true;
689
+ } catch (err) {
690
+ setError(err.message || "Failed to discard");
691
+ console.error("Discard error:", err);
692
+ throw err;
693
+ } finally {
694
+ setLoading(false);
695
+ }
696
+ }
697
+
698
+ throw new Error(`Unknown action "${action}" for flowType "${flowType}"`);
699
+ },
700
+ [flowType, viewId, isNewRecord, getFlowInstance, getFormInstance]
701
+ );
702
+
703
+ // Fetch the candidate assignees for the current task (Reassign picker).
704
+ // Returns a plain array of user objects — the native process reassign UI
705
+ // (process/common/src/form/reassign/hook.js) consumes this same endpoint
706
+ // as a bare array directly, so that's the primary shape; { Data }/
707
+ // { options }/{ reassignees } are tolerated as a fallback in case the SDK
708
+ // ever wraps it.
709
+ const getReassignees = useCallback(
710
+ async (query = "") => {
711
+ if (flowType !== "process") return [];
712
+ try {
713
+ const flowInstance = await getFlowInstance();
714
+ const formInstance = await getFormInstance();
715
+ const res = await flowInstance.getReassignees({
716
+ instanceId: formInstance.instanceId,
717
+ activityInstanceId: formInstance.activityInstanceId,
718
+ query
719
+ });
720
+ if (Array.isArray(res)) return res;
721
+ const list = res?.Data || res?.options || res?.reassignees;
722
+ if (!list) {
723
+ console.warn(
724
+ "getReassignees: unrecognized response shape, returning empty list",
725
+ res
726
+ );
727
+ }
728
+ return list || [];
729
+ } catch (err) {
730
+ console.error("Get reassignees error:", err);
731
+ throw err;
732
+ }
733
+ },
734
+ [flowType, getFlowInstance, getFormInstance]
735
+ );
736
+
737
+ // Get table ops for a given tableId.
738
+ // rows is a getter that always reads formDataRef — fresh without stale closures.
739
+ // All mutations call the SDK then refresh formData via toJSON().
740
+ const getTable = useCallback(
741
+ (tableId) => {
742
+ if (tableOpsRef.current[tableId]) return tableOpsRef.current[tableId];
743
+
744
+ const getSDKTable = async () =>
745
+ (await getFormInstance()).getTable(tableId);
746
+
747
+ const refresh = async () => {
748
+ const data = await (await getFormInstance()).toJSON();
749
+ setFormData(data || {});
750
+ };
751
+
752
+ tableOpsRef.current[tableId] = {
753
+ addRow: async (rowData) => {
754
+ await (await getSDKTable()).addRow(rowData);
755
+ await refresh();
756
+ },
757
+ addRows: async (rows) => {
758
+ await (await getSDKTable()).addRows(rows);
759
+ await refresh();
760
+ },
761
+ deleteRow: async (rowId) => {
762
+ await (await getSDKTable()).deleteRow(rowId);
763
+ await refresh();
764
+ },
765
+ deleteRows: async (rowIds) => {
766
+ await (await getSDKTable()).deleteRows(rowIds);
767
+ await refresh();
768
+ },
769
+ updateRow: async (rowId, fieldId, value) => {
770
+ await (
771
+ await getSDKTable()
772
+ )
773
+ .getRow(rowId)
774
+ .updateField({ [fieldId]: value });
775
+ await refresh();
776
+ },
777
+ getRowField: async (rowId, fieldId) => {
778
+ return (await getSDKTable()).getRow(rowId).getField(fieldId);
779
+ },
780
+ getSelectedRows: async () => {
781
+ return (await getSDKTable()).getSelectedRows();
782
+ }
783
+ };
784
+
785
+ return tableOpsRef.current[tableId];
786
+ },
787
+ [getFormInstance]
788
+ );
789
+
790
+ // Step context surfaced by getFormConfiguration (process flows only) and the
791
+ // workflow actions available at that step.
792
+ const processStatus = config?.status;
793
+ const isStartStep = config?.isStartStep;
794
+ const formActions = resolveProcessActions({
795
+ flowType,
796
+ status: processStatus,
797
+ isStartStep,
798
+ isSendBackToInitiator: config?.isSendBackToInitiator
799
+ });
800
+
801
+ // Users currently assigned to this step — the Reassign "from" candidates.
802
+ // Mirrors process/common/src/form/reassign/hook.js's
803
+ // availableAssigneesForReassignFrom for the single-step (assignee) case:
804
+ // _current_context is a regular field on the process item (see
805
+ // process/common/src/schema/form.ts), one entry per step the current
806
+ // user/admin can act on; we only ever act on the current activityInstanceId.
807
+ const reassignFromCandidates =
808
+ (formData?._current_context || []).find(
809
+ (ctx) => ctx._context_activity_instance_id === activityInstanceId
810
+ )?._context_assigned_to || [];
811
+
812
+ return {
813
+ // State
814
+ formData,
815
+ config,
816
+ errors,
817
+ loading,
818
+ error,
819
+ isSaving,
820
+ isNewRecord,
821
+
822
+ // Process step context + actions
823
+ processStatus,
824
+ isStartStep,
825
+ formActions,
826
+ reassignFromCandidates,
827
+
828
+ // Field ops
829
+ updateField,
830
+ updateFields,
831
+ getField,
832
+ getFieldOptions,
833
+ getFormData,
834
+ parseAttachment,
835
+ runAction,
836
+ getReassignees,
837
+
838
+ // Table ops
839
+ getTable
840
+ };
841
+ }