@kissflow/create-component 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -5,5 +5,22 @@
5
5
  ## To scaffold a custom component project,
6
6
 
7
7
  ```bash
8
- npm create kf-component
8
+ npx @kissflow/create-component@latest
9
+ ```
10
+
11
+ ## Non-interactive usage
12
+
13
+ Any value not supplied as a flag falls back to an interactive prompt, unless `--yes` is set (then a missing required value is an error instead of a prompt). Useful for AI agents or CI.
14
+
15
+ | Flag | Description |
16
+ | ------------- | --------------------------------------------------------------------- |
17
+ | `--name` | Project name. |
18
+ | `--target` | `page`, `form`, or `form-field`. |
19
+ | `--framework` | `page` target only. `HTML` or `React`. |
20
+ | `--yes`, `-y` | Run non-interactively; error instead of prompting for missing values. |
21
+
22
+ ```bash
23
+ npx @kissflow/create-component@latest --target page --framework React --name my-page --yes
24
+ npx @kissflow/create-component@latest --target form --name my-form --yes
25
+ npx @kissflow/create-component@latest --target form-field --name my-field --yes
9
26
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kissflow/create-component",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "CLI that scaffolds Kissflow custom page, form, and form-field component projects.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -770,9 +770,7 @@ export function useForm({
770
770
  await refresh();
771
771
  },
772
772
  updateRow: async (rowId, fieldId, value) => {
773
- await (
774
- await getSDKTable()
775
- )
773
+ await (await getSDKTable())
776
774
  .getRow(rowId)
777
775
  .updateField({ [fieldId]: value });
778
776
  await refresh();
@@ -1 +0,0 @@
1
- export { useForm } from "./useForm";
@@ -1,363 +0,0 @@
1
- import { useEffect, useState, useCallback, useRef } from "react";
2
-
3
- /**
4
- * Parses the raw getFormConfiguration() response into a clean schema object.
5
- * Shape of rawConfig must match the actual API response — adjust field mappings as needed.
6
- *
7
- * @param {object} rawConfig - Raw response from formInstance.getFormConfiguration()
8
- * @returns {{ sections: Array }} Pure schema with no data or ops attached
9
- */
10
- /**
11
- * Custom hook to manage form state with full validation, dynamic config, and child table support.
12
- *
13
- * @param {string} flowType - "dataform" | "board" | "process"
14
- * @param {string} flowId - ID of the dataform/board/process
15
- * @param {string} [instanceId] - Record instance ID (omit to create new)
16
- *
17
- * @returns {object}
18
- * - formData: object - Current field values
19
- * - config: Array - Raw getFormConfiguration() response. Each entry is either:
20
- * { type:'Section', id, name, fields:[{id, name, type, widget, required}], isHidden } or
21
- * { type:'Model', id, name, fields:[{id, name, type, widget}], isHidden }
22
- * - errors: object - Validation errors { fieldId: [...] }
23
- * - loading: boolean
24
- * - error: string|null
25
- * - isDirty: boolean
26
- * - isNewRecord: boolean
27
- * - updateField(fieldId, value): Promise<boolean>
28
- * - updateFields(updates): Promise<boolean>
29
- * - getField(fieldId): Promise<object>
30
- * - getFieldOptions(fieldId): Promise<object[]>
31
- * - getFormData(): Promise<object>
32
- * - save(): Promise<boolean>
33
- * - reset(): void
34
- * - getTable(tableId): { rows, addRow, addRows, deleteRow, deleteRows, updateRow, getRowField, getSelectedRows }
35
- *
36
- * @example
37
- * const { formData, config, updateField, getTable } = useForm("dataform", "EmpMaster", "emp_123");
38
- *
39
- * config.filter(s => !s.isHidden).map(section => {
40
- * if (section.type === 'Section') {
41
- * return section.fields.map(field =>
42
- * <input key={field.id} value={formData[field.id] || ''} onChange={e => updateField(field.id, e.target.value)} />
43
- * );
44
- * }
45
- * if (section.type === 'Model') {
46
- * const table = getTable(section.id);
47
- * return table.rows.map(row => ...);
48
- * }
49
- * });
50
- */
51
- export function useForm(flowType, flowId, instanceId) {
52
- const [formData, setFormData] = useState({});
53
- const [config, setConfig] = useState([]);
54
- const [errors, setErrors] = useState({});
55
- const [loading, setLoading] = useState(false);
56
- const [error, setError] = useState(null);
57
- const [isDirty, setIsDirty] = useState(false);
58
- const [isNewRecord, setIsNewRecord] = useState(false);
59
-
60
- const originalDataRef = useRef({});
61
- const formInstanceRef = useRef(null);
62
- const flowInstanceRef = useRef(null);
63
- const formDataRef = useRef({}); // always-fresh copy of formData for getTable rows getter
64
- const tableOpsRef = useRef({}); // memoized table op objects per tableId
65
-
66
- // Keep formDataRef in sync with formData state
67
- useEffect(() => {
68
- formDataRef.current = formData;
69
- }, [formData]);
70
-
71
- // Get flow instance (dataform / board / process) — for flow-level ops like getFieldOptions
72
- const getFlowInstance = useCallback(async () => {
73
- if (!window.kf)
74
- throw new Error("SDK not initialized. Make sure window.kf is available.");
75
- if (flowInstanceRef.current) return flowInstanceRef.current;
76
- if (!flowType || !flowId)
77
- throw new Error("getFlowInstance requires both flowType and flowId");
78
-
79
- if (flowType === "dataform")
80
- flowInstanceRef.current = window.kf.app.getDataform(flowId);
81
- else if (flowType === "board")
82
- flowInstanceRef.current = window.kf.app.getBoard(flowId);
83
- else if (flowType === "process")
84
- flowInstanceRef.current = window.kf.app.getProcess(flowId);
85
- else throw new Error(`Unknown flow type: ${flowType}`);
86
-
87
- return flowInstanceRef.current;
88
- }, [flowType, flowId]);
89
-
90
- // Get form instance — initialized via initForm() on the flow instance
91
- const getFormInstance = useCallback(async () => {
92
- if (!window.kf)
93
- throw new Error("SDK not initialized. Make sure window.kf is available.");
94
- if (formInstanceRef.current) return formInstanceRef.current;
95
-
96
- if (flowType && flowId) {
97
- const flowInstance = await getFlowInstance();
98
- formInstanceRef.current = await flowInstance.initForm(instanceId);
99
- setIsNewRecord(!instanceId);
100
- return formInstanceRef.current;
101
- }
102
-
103
- // Legacy: page form context
104
- if (flowType && !flowId) {
105
- if (window.kf.context && window.kf.context.toJSON) {
106
- formInstanceRef.current = window.kf.context;
107
- setIsNewRecord(false);
108
- return formInstanceRef.current;
109
- }
110
- throw new Error(
111
- "Form context not available. Ensure component is placed on a form page."
112
- );
113
- }
114
-
115
- throw new Error(
116
- "useForm requires (flowType, flowId) or a page form context"
117
- );
118
- }, [flowType, flowId, instanceId, getFlowInstance]);
119
-
120
- // Initialize form: load data + config in parallel
121
- useEffect(() => {
122
- async function initializeForm() {
123
- try {
124
- setLoading(true);
125
- setError(null);
126
- setErrors({});
127
-
128
- const formInstance = await getFormInstance();
129
-
130
- const [data, rawConfig] = await Promise.all([
131
- formInstance.toJSON(),
132
- formInstance.getFormConfiguration()
133
- ]);
134
-
135
- setFormData(data || {});
136
- setConfig(parseConfig(rawConfig));
137
- originalDataRef.current = JSON.parse(JSON.stringify(data || {}));
138
- setIsDirty(false);
139
- } catch (err) {
140
- setError(err.message || "Failed to load form");
141
- console.error("Form initialization error:", err);
142
- } finally {
143
- setLoading(false);
144
- }
145
- }
146
-
147
- if (window.kf && (flowId || flowType)) {
148
- initializeForm();
149
- }
150
- }, [flowType, flowId, instanceId, getFormInstance]);
151
-
152
- // Update single field — uses { formData, error } returned directly by updateField
153
- const updateField = useCallback(
154
- async (fieldId, value) => {
155
- try {
156
- setError(null);
157
- const formInstance = await getFormInstance();
158
-
159
- const currentData = await formInstance.toJSON();
160
- if (currentData[fieldId] === value) return true;
161
-
162
- const { formData: updatedData, error: fieldError } =
163
- await formInstance.updateField({ [fieldId]: value });
164
- setFormData(updatedData || {});
165
- setErrors(fieldError || {});
166
- setIsDirty(true);
167
- return true;
168
- } catch (err) {
169
- setError(err.message || "Failed to update field");
170
- console.error("Field update error:", err);
171
- throw err;
172
- }
173
- },
174
- [getFormInstance]
175
- );
176
-
177
- // Update multiple fields
178
- const updateFields = useCallback(
179
- async (updates) => {
180
- try {
181
- setError(null);
182
- const formInstance = await getFormInstance();
183
- const currentData = await formInstance.toJSON();
184
- let hasChanges = false;
185
-
186
- for (const [fieldId, value] of Object.entries(updates)) {
187
- if (currentData[fieldId] === value) continue;
188
- hasChanges = true;
189
- await formInstance.updateField({ [fieldId]: value });
190
- }
191
-
192
- if (!hasChanges) return true;
193
-
194
- const updatedData = await formInstance.toJSON();
195
- setFormData(updatedData || {});
196
-
197
- const validationErrors = await formInstance.getValidationErrors();
198
- setErrors(validationErrors || {});
199
- setIsDirty(true);
200
- return true;
201
- } catch (err) {
202
- setError(err.message || "Failed to update fields");
203
- console.error("Fields update error:", err);
204
- throw err;
205
- }
206
- },
207
- [getFormInstance]
208
- );
209
-
210
- // Get a single field's details
211
- const getField = useCallback(
212
- async (fieldId) => {
213
- try {
214
- const formInstance = await getFormInstance();
215
- return formInstance.getField(fieldId);
216
- } catch (err) {
217
- setError(err.message || "Failed to get field");
218
- console.error("Get field error:", err);
219
- throw err;
220
- }
221
- },
222
- [getFormInstance]
223
- );
224
-
225
- // Get dropdown/select options for a field
226
- const getFieldOptions = useCallback(
227
- async (fieldId) => {
228
- try {
229
- const flowInstance = await getFlowInstance();
230
- const formInstance = await getFormInstance();
231
- return flowInstance.getFieldOptions({
232
- fieldId,
233
- instanceId: formInstance.instanceId
234
- });
235
- } catch (err) {
236
- setError(err.message || "Failed to get field options");
237
- console.error("Get field options error:", err);
238
- throw err;
239
- }
240
- },
241
- [getFlowInstance, getFormInstance]
242
- );
243
-
244
- // Get latest form data
245
- const getFormData = useCallback(async () => {
246
- const formInstance = await getFormInstance();
247
- return formInstance.toJSON();
248
- }, [getFormInstance]);
249
-
250
- // Save: validate then persist
251
- const save = useCallback(async () => {
252
- try {
253
- setLoading(true);
254
- setError(null);
255
- const formInstance = await getFormInstance();
256
-
257
- const validationErrors = await formInstance.getValidationErrors();
258
- setErrors(validationErrors || {});
259
-
260
- if (Object.keys(validationErrors || {}).length > 0) {
261
- setError("Form has validation errors. Please fix them before saving.");
262
- return false;
263
- }
264
-
265
- originalDataRef.current = JSON.parse(JSON.stringify(formData));
266
- setIsDirty(false);
267
- return true;
268
- } catch (err) {
269
- setError(err.message || "Failed to save form");
270
- console.error("Save error:", err);
271
- throw err;
272
- } finally {
273
- setLoading(false);
274
- }
275
- }, [formData, getFormInstance]);
276
-
277
- // Reset to last saved state
278
- const reset = useCallback(() => {
279
- setFormData(originalDataRef.current);
280
- setErrors({});
281
- setError(null);
282
- setIsDirty(false);
283
- }, []);
284
-
285
- // Get table ops for a given tableId.
286
- // rows is a getter that always reads formDataRef — fresh without stale closures.
287
- // All mutations call the SDK then refresh formData via toJSON().
288
- const getTable = useCallback(
289
- (tableId) => {
290
- if (tableOpsRef.current[tableId]) return tableOpsRef.current[tableId];
291
-
292
- const getSDKTable = async () =>
293
- (await getFormInstance()).getTable(tableId);
294
-
295
- const refresh = async () => {
296
- const data = await (await getFormInstance()).toJSON();
297
- setFormData(data || {});
298
- };
299
-
300
- tableOpsRef.current[tableId] = {
301
- get rows() {
302
- return formDataRef.current[tableId] || [];
303
- },
304
- addRow: async (rowData) => {
305
- await (await getSDKTable()).addRow(rowData);
306
- await refresh();
307
- },
308
- addRows: async (rows) => {
309
- await (await getSDKTable()).addRows(rows);
310
- await refresh();
311
- },
312
- deleteRow: async (rowId) => {
313
- await (await getSDKTable()).deleteRow(rowId);
314
- await refresh();
315
- },
316
- deleteRows: async (rowIds) => {
317
- await (await getSDKTable()).deleteRows(rowIds);
318
- await refresh();
319
- },
320
- updateRow: async (rowId, fieldId, value) => {
321
- await (
322
- await getSDKTable()
323
- )
324
- .getRow(rowId)
325
- .updateField({ [fieldId]: value });
326
- await refresh();
327
- },
328
- getRowField: async (rowId, fieldId) => {
329
- return (await getSDKTable()).getRow(rowId).getField(fieldId);
330
- },
331
- getSelectedRows: async () => {
332
- return (await getSDKTable()).getSelectedRows();
333
- }
334
- };
335
-
336
- return tableOpsRef.current[tableId];
337
- },
338
- [getFormInstance]
339
- );
340
-
341
- return {
342
- // State
343
- formData,
344
- config,
345
- errors,
346
- loading,
347
- error,
348
- isDirty,
349
- isNewRecord,
350
-
351
- // Field ops
352
- updateField,
353
- updateFields,
354
- getField,
355
- getFieldOptions,
356
- getFormData,
357
- save,
358
- reset,
359
-
360
- // Table ops
361
- getTable
362
- };
363
- }