@react-fabric/form 1.0.0-beta.33 → 1.0.0-beta.35

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 (69) hide show
  1. package/dist/cjs/builder/FormField.js +3 -3
  2. package/dist/cjs/builder/SchemaEditor.js +43 -404
  3. package/dist/cjs/builder/components/AddSchemaFields.js +62 -0
  4. package/dist/cjs/builder/components/SchemaArrayForm.js +144 -0
  5. package/dist/cjs/builder/components/SchemaField.js +411 -0
  6. package/dist/cjs/form/Form.js +11 -8
  7. package/dist/cjs/index.js +1 -0
  8. package/dist/cjs/input/ColorInput.js +1 -1
  9. package/dist/cjs/input/DateInput.js +2 -2
  10. package/dist/cjs/input/File.js +1 -1
  11. package/dist/cjs/input/Hidden.js +1 -1
  12. package/dist/cjs/input/Input.js +1 -1
  13. package/dist/cjs/input/Number.js +1 -1
  14. package/dist/cjs/input/Password.js +1 -1
  15. package/dist/cjs/input/RangeSlider.js +1 -1
  16. package/dist/cjs/input/Search.js +1 -1
  17. package/dist/cjs/input/Slider.js +1 -1
  18. package/dist/cjs/input/Textarea.js +1 -1
  19. package/dist/cjs/types/schema.js +2 -0
  20. package/dist/esm/builder/FormField.js +3 -3
  21. package/dist/esm/builder/SchemaEditor.js +45 -406
  22. package/dist/esm/builder/components/AddSchemaFields.js +62 -0
  23. package/dist/esm/builder/components/SchemaArrayForm.js +144 -0
  24. package/dist/esm/builder/components/SchemaField.js +411 -0
  25. package/dist/esm/form/Form.js +11 -8
  26. package/dist/esm/index.js +1 -1
  27. package/dist/esm/input/ColorInput.js +1 -1
  28. package/dist/esm/input/DateInput.js +2 -2
  29. package/dist/esm/input/File.js +1 -1
  30. package/dist/esm/input/Hidden.js +1 -1
  31. package/dist/esm/input/Input.js +1 -1
  32. package/dist/esm/input/Number.js +1 -1
  33. package/dist/esm/input/Password.js +1 -1
  34. package/dist/esm/input/RangeSlider.js +1 -1
  35. package/dist/esm/input/Search.js +1 -1
  36. package/dist/esm/input/Slider.js +1 -1
  37. package/dist/esm/input/Textarea.js +1 -1
  38. package/dist/esm/types/schema.js +2 -1
  39. package/dist/types/builder/SchemaEditor.d.ts +2 -10
  40. package/dist/types/builder/components/AddSchemaFields.d.ts +2 -0
  41. package/dist/types/builder/components/SchemaArrayForm.d.ts +2 -0
  42. package/dist/types/builder/components/SchemaField.d.ts +10 -0
  43. package/dist/types/form/Form.d.ts +1 -5
  44. package/dist/types/index.d.ts +1 -1
  45. package/dist/types/input/ColorInput.d.ts +1 -1
  46. package/dist/types/types/index.d.ts +1 -1
  47. package/dist/types/types/schema.d.ts +26 -0
  48. package/package.json +5 -5
  49. package/src/builder/FormField.tsx +3 -3
  50. package/src/builder/SchemaEditor.tsx +24 -398
  51. package/src/builder/components/AddSchemaFields.tsx +74 -0
  52. package/src/builder/components/SchemaArrayForm.tsx +158 -0
  53. package/src/builder/components/SchemaField.tsx +432 -0
  54. package/src/form/Form.tsx +6 -9
  55. package/src/index.ts +6 -1
  56. package/src/input/ArrayInput.tsx +1 -0
  57. package/src/input/ColorInput.tsx +5 -2
  58. package/src/input/DateInput.tsx +2 -2
  59. package/src/input/File.tsx +1 -1
  60. package/src/input/Hidden.tsx +4 -3
  61. package/src/input/Input.tsx +1 -1
  62. package/src/input/Number.tsx +1 -1
  63. package/src/input/Password.tsx +1 -1
  64. package/src/input/RangeSlider.tsx +1 -1
  65. package/src/input/Search.tsx +1 -1
  66. package/src/input/Slider.tsx +1 -1
  67. package/src/input/Textarea.tsx +1 -1
  68. package/src/types/index.ts +1 -1
  69. package/src/types/schema.ts +30 -0
@@ -21,421 +21,47 @@
21
21
  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
22
  */
23
23
 
24
- import {
25
- Button,
26
- Collapsable,
27
- Content,
28
- CoreIcons,
29
- Footer,
30
- Modal,
31
- ToggleButtonGroup,
32
- useOverlayService,
33
- } from "@react-fabric/core";
24
+ import { Footer } from "@react-fabric/core";
34
25
  import { EMPTY_ARRAY } from "@react-fabric/utilities";
35
- import { Fragment, useCallback, useEffect, useRef, useState } from "react";
36
- import { Controller } from "../form/Controller";
26
+ import { useCallback, useEffect, useRef } from "react";
37
27
  import { Form, type FormRef } from "../form/Form";
38
- import { ArrayInput } from "../input/ArrayInput";
39
- import { Checkbox } from "../input/Checkbox";
40
- import { DateInput } from "../input/DateInput";
41
- import { Field } from "../input/Field";
42
- import { Input } from "../input/Input";
43
- import { Number } from "../input/Number";
44
- import { Select } from "../select/Select";
45
28
  import {
46
29
  DATA_TYPES,
47
- type DateSchema,
48
- type DefaultSchema,
49
30
  type FormSchema,
50
- type NumberSchema,
51
- type SchemaDef,
52
- type StringSchema,
53
- type ValueType,
31
+ type SchemaEditorProps,
54
32
  } from "../types/schema";
55
-
56
- interface Props {
57
- schemaDef: FormSchema;
58
- allowRemove?: boolean;
59
- acceptableTypes?: DATA_TYPES[];
60
-
61
- optionLists?: string[];
62
-
63
- onChange: (schema: FormSchema) => void;
64
- }
65
-
66
- const CUSTOM_LIST = "--CUSTOM--";
67
-
68
- const SchemaField = ({
69
- field,
70
- getModel,
71
- optionLists = EMPTY_ARRAY,
72
- allowRemove,
73
- onTypeChange,
74
- acceptableTypes,
75
- }: {
76
- field: string;
77
- getModel: () => KeyValue;
78
- onTypeChange: (val: KeyValue) => void;
79
- } & Omit<Props, "schemaDef" | "onChange">) => {
80
- const [type, setType] = useState<DATA_TYPES>();
81
- const [multiple, setMultiple] = useState(false);
82
- const [hasOptions, setHasOptions] = useState(false);
83
- const [customOptions, setCustomOptions] = useState(false);
84
-
85
- const [OptionModal, openOptionModal] = useOverlayService((props) => (
86
- <Modal {...props}>
87
- <Content>
88
- <ArrayInput name={`${field}.options`} onAdd={() => String("")}>
89
- <Controller>
90
- <Input />
91
- </Controller>
92
- </ArrayInput>
93
- </Content>
94
- <Footer
95
- flex
96
- justify="end"
97
- className="sticky bottom-0 border-t bg-base px-6 py-2"
98
- >
99
- <Button variant="link" onClick={props.onClose}>
100
- Close
101
- </Button>
102
- </Footer>
103
- </Modal>
104
- ));
105
-
106
- useEffect(() => {
107
- setTimeout(() => {
108
- const model = getModel();
109
- setType(model.datatype);
110
- setMultiple(model.multiple);
111
- setHasOptions(!!model.optionList);
112
- setCustomOptions(model.optionList === CUSTOM_LIST);
113
- }, 10);
114
- }, []);
115
-
116
- useEffect(() => {
117
- if (type) {
118
- const modelRef = getModel();
119
- let reset = {
120
- datatype: type,
121
- id: field,
122
- label: modelRef.label,
123
- defaultValue: modelRef.defaultValue,
124
- required: modelRef.required,
125
- multiple: type === DATA_TYPES.AVATAR ? false : modelRef.multiple,
126
- minItems: modelRef.minItems,
127
- maxItems: modelRef.maxItems,
128
- } as DefaultSchema & ValueType;
129
- if (type === DATA_TYPES.STRING) {
130
- reset = Object.assign(reset, {
131
- optionList: modelRef.optionList,
132
- options: modelRef.options,
133
- regex: modelRef.regex,
134
- } as StringSchema);
135
- } else if (type === DATA_TYPES.DATE) {
136
- reset = Object.assign(reset, {
137
- type: "date",
138
- } as DateSchema);
139
- } else if (type === DATA_TYPES.NUMBER || type === DATA_TYPES.RANGE) {
140
- reset = Object.assign(reset, {
141
- min: modelRef.min,
142
- max: modelRef.max,
143
- step: modelRef.step,
144
- } as NumberSchema);
145
- }
146
- if (type === DATA_TYPES.AVATAR) {
147
- setMultiple(false);
148
- }
149
- onTypeChange(reset);
150
- }
151
- }, [type]);
152
-
153
- return (
154
- <Collapsable key={field} open>
155
- <div className="flex flex-nowrap group/field">
156
- <span className="flex-1 truncate">{field}</span>
157
- {allowRemove && (
158
- <Button
159
- size="sm"
160
- color="danger"
161
- variant="link"
162
- aria-label="Delete"
163
- stopPropagation
164
- icon={CoreIcons.trash}
165
- className="invisible group-hover/field:visible"
166
- />
167
- )}
168
- </div>
169
- <div className="flex flex-col gap-1 pb-4">
170
- <Controller name={`${field}.datatype`}>
171
- <Select
172
- inline
173
- label="Type"
174
- placeholder="Data type"
175
- options={acceptableTypes}
176
- onChange={(val) => setType(val as unknown as DATA_TYPES)}
177
- />
178
- </Controller>
179
- <Controller name={`${field}.label`}>
180
- <Input
181
- inline
182
- label="Label"
183
- allowClear
184
- placeholder="Label..."
185
- decorateEndShowWhenEmpty
186
- decorateEnd={
187
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
188
- }
189
- />
190
- </Controller>
191
- {type === DATA_TYPES.STRING && (
192
- <Fragment>
193
- <Controller name={`${field}.regex`}>
194
- <Input
195
- inline
196
- label="Regex validation"
197
- allowClear
198
- placeholder="Regex value..."
199
- decorateEndShowWhenEmpty
200
- decorateEnd={
201
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
202
- }
203
- />
204
- </Controller>
205
- <Field inline label="Option list">
206
- <Controller name={`${field}.optionList`}>
207
- <Select
208
- allowClear
209
- options={[CUSTOM_LIST, ...optionLists]}
210
- onChange={(v) => setCustomOptions(v === CUSTOM_LIST)}
211
- />
212
- </Controller>
213
- {customOptions && (
214
- <Button
215
- icon={CoreIcons.list}
216
- aria-label="Custom options"
217
- onClick={() => {
218
- void openOptionModal();
219
- }}
220
- />
221
- )}
222
- </Field>
223
- {OptionModal}
224
- </Fragment>
225
- )}
226
- {type === DATA_TYPES.FILE && (
227
- <Fragment>
228
- <Controller name={`${field}.accept`}>
229
- <Input
230
- inline
231
- label="Accept types"
232
- allowClear
233
- placeholder="Accept value..."
234
- decorateEndShowWhenEmpty
235
- decorateEnd={
236
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
237
- }
238
- />
239
- </Controller>
240
- </Fragment>
241
- )}
242
- {[DATA_TYPES.NUMBER, DATA_TYPES.RANGE].includes(
243
- type as unknown as DATA_TYPES,
244
- ) && (
245
- <Fragment>
246
- <Controller name={`${field}.min`}>
247
- <Number
248
- inline
249
- label="Min value"
250
- allowClear
251
- placeholder="Minimum value..."
252
- decorateEndShowWhenEmpty
253
- decorateEnd={
254
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
255
- }
256
- />
257
- </Controller>
258
- <Controller name={`${field}.max`}>
259
- <Number
260
- inline
261
- label="Max value"
262
- allowClear
263
- placeholder="Maximum value..."
264
- decorateEndShowWhenEmpty
265
- decorateEnd={
266
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
267
- }
268
- />
269
- </Controller>
270
- <Controller name={`${field}.step`}>
271
- <Number
272
- inline
273
- label="Step value"
274
- allowClear
275
- placeholder="Step value..."
276
- decorateEndShowWhenEmpty
277
- decorateEnd={
278
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
279
- }
280
- />
281
- </Controller>
282
- </Fragment>
283
- )}
284
- {type === DATA_TYPES.DATE && (
285
- <Fragment>
286
- <Field inline label="Type" plain>
287
- <Controller name={`${field}.type`}>
288
- <ToggleButtonGroup value="" fullWidth className="flex-1">
289
- <Button className="flex-1" value="date">
290
- Date
291
- </Button>
292
- <Button className="flex-1" value="datetime">
293
- Date Time
294
- </Button>
295
- </ToggleButtonGroup>
296
- </Controller>
297
- </Field>
298
- <Controller name={`${field}.min`}>
299
- <DateInput
300
- inline
301
- label="Min value"
302
- allowClear
303
- placeholder="Minimum value..."
304
- decorateEndShowWhenEmpty
305
- decorateEnd={
306
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
307
- }
308
- />
309
- </Controller>
310
- <Controller name={`${field}.max`}>
311
- <DateInput
312
- inline
313
- label="Max value"
314
- allowClear
315
- placeholder="Maximum value..."
316
- decorateEndShowWhenEmpty
317
- decorateEnd={
318
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
319
- }
320
- />
321
- </Controller>
322
- </Fragment>
323
- )}
324
- <Field label=" " inline plain>
325
- <Controller name={`${field}.required`}>
326
- <Checkbox label="Required" />
327
- </Controller>
328
- {type !== DATA_TYPES.AVATAR && (
329
- <Controller name={`${field}.multiple`}>
330
- <Checkbox label="Multiple" onChange={setMultiple} />
331
- </Controller>
332
- )}
333
- {hasOptions && (
334
- <Controller name={`${field}.allowCustom`}>
335
- <Checkbox label="Allow custom value" />
336
- </Controller>
337
- )}
338
- </Field>
339
- {multiple && (
340
- <Fragment>
341
- <Controller name={`${field}.minItems`}>
342
- <Number
343
- inline
344
- label="Min items"
345
- allowClear
346
- placeholder="Minimum items..."
347
- decorateEndShowWhenEmpty
348
- decorateEnd={
349
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
350
- }
351
- />
352
- </Controller>
353
- <Controller name={`${field}.maxItems`}>
354
- <Number
355
- inline
356
- label="Max items"
357
- allowClear
358
- placeholder="Maximum items..."
359
- decorateEndShowWhenEmpty
360
- decorateEnd={
361
- <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
362
- }
363
- />
364
- </Controller>
365
- </Fragment>
366
- )}
367
- </div>
368
- </Collapsable>
369
- );
370
- };
33
+ import { SchemaArrayForm } from "./components/SchemaArrayForm";
371
34
 
372
35
  export const SchemaEditor = ({
373
36
  schemaDef,
374
- allowRemove,
37
+ dynamic,
375
38
  acceptableTypes,
376
39
  optionLists = EMPTY_ARRAY,
40
+ children,
377
41
  onChange,
378
- }: Props) => {
379
- const formRef = useRef<FormRef<KeyValue>>(null);
380
- const schemaRef = useRef<KeyValue>({});
381
- const [schema, setSchema] = useState<KeyValue<SchemaDef>>({});
382
- const [schemaFields, setSchemaFields] = useState<string[]>([]);
383
-
384
- useEffect(() => {
385
- const schemaMap = Object.fromEntries(
386
- schemaDef.map((schema) => [schema.id, schema]),
387
- );
388
-
389
- const schema = Object.fromEntries(
390
- Object.keys(schemaMap).map((field) => [
391
- field,
392
- schemaRef.current[field] ?? schemaMap[field],
393
- ]),
394
- );
395
- setSchema(schema);
396
- setSchemaFields(Object.keys(schema));
397
- }, [schemaDef]);
42
+ }: SchemaEditorProps) => {
43
+ const formRef = useRef<FormRef<{ schema: FormSchema }>>(null);
398
44
 
399
- const handleChange = useCallback((model: KeyValue<SchemaDef>) => {
400
- onChange?.(Object.values(model));
45
+ const handleChange = useCallback((model: { schema: FormSchema }) => {
46
+ onChange?.(model.schema);
401
47
  }, []);
402
48
 
403
- const handleTypeChange = useCallback((field: string, val: KeyValue) => {
404
- formRef.current?.setValue(field, val);
405
- }, []);
49
+ useEffect(() => {
50
+ formRef.current?.setValues({ schema: schemaDef });
51
+ }, [schemaDef]);
406
52
 
407
53
  return (
408
- <Form
409
- formRef={formRef}
410
- values={schema}
411
- defaultValues={schema}
412
- onSubmit={handleChange}
413
- >
414
- <Content className="divide-y">
415
- {schemaFields.map((field) => (
416
- <SchemaField
417
- key={field}
418
- field={field}
419
- allowRemove={allowRemove}
420
- optionLists={optionLists}
421
- getModel={() => formRef.current?.getValues()[field]}
422
- onTypeChange={(val: KeyValue) => handleTypeChange(field, val)}
423
- acceptableTypes={acceptableTypes ?? Object.values(DATA_TYPES)}
424
- />
425
- ))}
426
- </Content>
427
- <Footer
428
- flex
429
- justify="end"
430
- className="sticky bottom-0 border-t bg-base px-6 py-2"
431
- >
432
- <Button type="reset" variant="link">
433
- Reset
434
- </Button>
435
- <Button type="submit" variant="solid">
436
- Submit
437
- </Button>
438
- </Footer>
54
+ <Form formRef={formRef} onSubmit={handleChange}>
55
+ <SchemaArrayForm
56
+ dynamic={dynamic}
57
+ optionLists={optionLists}
58
+ acceptableTypes={acceptableTypes ?? Object.values(DATA_TYPES)}
59
+ />
60
+ {children && (
61
+ <Footer flex className="border-t bg-base px-6 py-2">
62
+ {children}
63
+ </Footer>
64
+ )}
439
65
  </Form>
440
66
  );
441
67
  };
@@ -0,0 +1,74 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2025 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import {
25
+ Button,
26
+ Content,
27
+ Footer,
28
+ Modal,
29
+ type ModalProps,
30
+ } from "@react-fabric/core";
31
+ import { yup } from "@react-fabric/utilities";
32
+ import { useCallback } from "react";
33
+ import { Controller } from "../../form/Controller";
34
+ import { Form } from "../../form/Form";
35
+ import { ArrayInput } from "../../input/ArrayInput";
36
+ import { Input } from "../../input/Input";
37
+
38
+ const fieldSchema = yup.object({
39
+ fields: yup.array(yup.string().trim().required()).required().min(1),
40
+ });
41
+
42
+ export const AddSchemaFields = (props: ModalProps) => {
43
+ const handleSubmit = useCallback((model: KeyValue) => {
44
+ props.onClose(
45
+ model.fields
46
+ .map((f: string) => f.split(",").map((ff) => ff.trim()))
47
+ .flat(2),
48
+ );
49
+ }, []);
50
+
51
+ return (
52
+ <Modal {...props}>
53
+ <Form
54
+ schema={fieldSchema}
55
+ defaultValues={{ fields: [" "] }}
56
+ onSubmit={handleSubmit}
57
+ >
58
+ <Content>
59
+ <ArrayInput minItems={1} name="fields" onAdd={() => String("")}>
60
+ <Controller>
61
+ <Input autoFocus />
62
+ </Controller>
63
+ </ArrayInput>
64
+ <p className="text-sm text-muted">
65
+ Provide list of fields or comma-separated value
66
+ </p>
67
+ </Content>
68
+ <Footer flex justify="end" className="px-2 py-1">
69
+ <Button type="submit">Add</Button>
70
+ </Footer>
71
+ </Form>
72
+ </Modal>
73
+ );
74
+ };
@@ -0,0 +1,158 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2025 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ import { DndContext, type DragEndEvent } from "@dnd-kit/core";
25
+ import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
26
+ import { SortableContext } from "@dnd-kit/sortable";
27
+ import {
28
+ Button,
29
+ Content,
30
+ CoreIcons,
31
+ Header,
32
+ useOverlayService,
33
+ } from "@react-fabric/core";
34
+ import { isArray } from "@react-fabric/utilities";
35
+ import { type PropsWithChildren, useCallback, useState } from "react";
36
+ import { useFieldArray, useFormContext } from "react-hook-form";
37
+ import { DATA_TYPES, type SchemaEditorProps } from "../../types/schema";
38
+ import { AddSchemaFields } from "./AddSchemaFields";
39
+ import { SchemaField } from "./SchemaField";
40
+
41
+ export const SchemaArrayForm = ({
42
+ dynamic,
43
+ acceptableTypes,
44
+ optionLists,
45
+ }: Partial<SchemaEditorProps>) => {
46
+ const form = useFormContext();
47
+ const [defaultOpen, setDefaultOpen] = useState(true);
48
+ const { fields, append, remove, update, move } = useFieldArray({
49
+ name: "schema",
50
+ control: form.control,
51
+ });
52
+
53
+ const handleTypeChange = useCallback((index: number, val: KeyValue) => {
54
+ update(index, val);
55
+ }, []);
56
+
57
+ const handleRemove = useCallback((index: number) => {
58
+ remove(index);
59
+ }, []);
60
+
61
+ const [AddModal, openAddfields] = useOverlayService(AddSchemaFields);
62
+ const handleAdd = useCallback(() => {
63
+ void openAddfields().then((fields) => {
64
+ if (isArray(fields)) {
65
+ const existing = form
66
+ .getValues()
67
+ .schema.map((field: KeyValue) => field.id);
68
+ fields.forEach((field) => {
69
+ if (!existing.includes(field)) {
70
+ append({
71
+ id: field,
72
+ datatype: DATA_TYPES.STRING,
73
+ label: "",
74
+ });
75
+ }
76
+ });
77
+ }
78
+ });
79
+ }, []);
80
+
81
+ const Wrapper = useCallback(
82
+ ({ children }: PropsWithChildren) => {
83
+ if (dynamic) {
84
+ // pass id list to dnd context
85
+ const idMap = fields.map((item) => item.id);
86
+ const handleDragEnd = (e: DragEndEvent) => {
87
+ if (e.over && e.active.id !== e.over.id) {
88
+ // find index of item and drop over
89
+ const active = idMap.indexOf(`${e.active.id}`);
90
+ const end = idMap.indexOf(`${e.over.id}`);
91
+ move(active, end);
92
+ }
93
+ };
94
+ return (
95
+ <DndContext
96
+ onDragEnd={handleDragEnd}
97
+ modifiers={[restrictToVerticalAxis]}
98
+ >
99
+ <SortableContext items={idMap}>{children}</SortableContext>
100
+ </DndContext>
101
+ );
102
+ }
103
+
104
+ return children;
105
+ },
106
+ [dynamic, fields],
107
+ );
108
+ // @ts-expect-error ignore
109
+ Wrapper.displayName = "SortableWrapper";
110
+
111
+ return (
112
+ <Wrapper>
113
+ <Header flex justify="end" className="gap-1 px-2">
114
+ {dynamic && (
115
+ <Button
116
+ size="sm"
117
+ variant="link"
118
+ icon={CoreIcons.insert}
119
+ aria-label="add field"
120
+ onClick={handleAdd}
121
+ />
122
+ )}
123
+ <Button
124
+ size="sm"
125
+ variant="link"
126
+ icon={CoreIcons.colapseAllVar}
127
+ aria-label="collapse all"
128
+ onClick={() => setDefaultOpen(false)}
129
+ />
130
+ <Button
131
+ size="sm"
132
+ variant="link"
133
+ icon={CoreIcons.expandAllVar}
134
+ aria-label="expand all"
135
+ onClick={() => setDefaultOpen(true)}
136
+ />
137
+ </Header>
138
+ <Content className="divide-y">
139
+ {fields.map((field, index) => (
140
+ <SchemaField
141
+ key={index}
142
+ defaultOpen={defaultOpen}
143
+ id={form.getValues().schema[index].id}
144
+ fieldId={field.id}
145
+ field={`schema.${index}`}
146
+ dynamic={dynamic}
147
+ optionLists={optionLists}
148
+ onRemove={() => handleRemove(index)}
149
+ getModel={() => form.getValues().schema[index]}
150
+ onTypeChange={(val: KeyValue) => handleTypeChange(index, val)}
151
+ acceptableTypes={acceptableTypes ?? Object.values(DATA_TYPES)}
152
+ />
153
+ ))}
154
+ </Content>
155
+ {AddModal}
156
+ </Wrapper>
157
+ );
158
+ };