@react-fabric/form 1.0.0-beta.34 → 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.
@@ -0,0 +1,432 @@
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 { useSortable } from "@dnd-kit/sortable";
25
+ import { CSS } from "@dnd-kit/utilities";
26
+ import {
27
+ Button,
28
+ Collapsable,
29
+ Content,
30
+ CoreIcons,
31
+ Footer,
32
+ Modal,
33
+ type ModalProps,
34
+ ToggleButtonGroup,
35
+ useOverlayService,
36
+ } from "@react-fabric/core";
37
+ import { EMPTY_ARRAY } from "@react-fabric/utilities";
38
+ import classNames from "classnames";
39
+ import {
40
+ Fragment,
41
+ type PropsWithChildren,
42
+ useCallback,
43
+ useEffect,
44
+ useState,
45
+ } from "react";
46
+ import { Controller } from "../../form/Controller";
47
+ import { ArrayInput } from "../../input/ArrayInput";
48
+ import { Checkbox } from "../../input/Checkbox";
49
+ import { DateInput } from "../../input/DateInput";
50
+ import { Field } from "../../input/Field";
51
+ import { HiddenInput } from "../../input/Hidden";
52
+ import { Input } from "../../input/Input";
53
+ import { Number } from "../../input/Number";
54
+ import { Select } from "../../select/Select";
55
+ import {
56
+ DATA_TYPES,
57
+ type DateSchema,
58
+ type DefaultSchema,
59
+ type NumberSchema,
60
+ SCHEMA_CUSTOM_LIST,
61
+ type SchemaEditorProps,
62
+ type StringSchema,
63
+ type ValueType,
64
+ } from "../../types/schema";
65
+
66
+ export const SchemaField = ({
67
+ id,
68
+ field,
69
+ fieldId,
70
+ getModel,
71
+ onRemove,
72
+ defaultOpen = true,
73
+ optionLists = EMPTY_ARRAY,
74
+ dynamic,
75
+ onTypeChange,
76
+ acceptableTypes,
77
+ }: {
78
+ id: string;
79
+ field: string;
80
+ fieldId: string;
81
+ defaultOpen?: boolean;
82
+ onRemove: () => void;
83
+ getModel: () => KeyValue;
84
+ onTypeChange: (val: KeyValue) => void;
85
+ } & Omit<SchemaEditorProps, "schemaDef" | "onChange">) => {
86
+ const [type, setType] = useState<DATA_TYPES>();
87
+ const [multiple, setMultiple] = useState(false);
88
+ const [hasOptions, setHasOptions] = useState(false);
89
+ const [customOptions, setCustomOptions] = useState(false);
90
+
91
+ const SortableItem = useCallback(
92
+ ({
93
+ id,
94
+ children,
95
+ className,
96
+ }: PropsWithChildren<{ id: AnyObject; className: string }>) => {
97
+ if (dynamic) {
98
+ const {
99
+ attributes,
100
+ listeners,
101
+ setNodeRef,
102
+ transform,
103
+ transition,
104
+ isDragging,
105
+ } = useSortable({ id });
106
+ return (
107
+ <div
108
+ className={className}
109
+ ref={setNodeRef}
110
+ style={{
111
+ transform: CSS.Transform.toString(transform),
112
+ transition,
113
+ }}
114
+ >
115
+ <div
116
+ className={classNames(
117
+ "invisible group-hover/field:visible my-2 w-4",
118
+ isDragging ? "cursor-grabbing" : "cursor-grab",
119
+ )}
120
+ {...attributes}
121
+ {...listeners}
122
+ style={{
123
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='4' width='4'%3E%3Ccircle cx='2' cy='2' r='1' fill='%238888' /%3E%3C/svg%3E ")`,
124
+ }}
125
+ />
126
+ {children}
127
+ </div>
128
+ );
129
+ }
130
+
131
+ return <div className={className}>{children}</div>;
132
+ },
133
+ [dynamic],
134
+ );
135
+ // @ts-expect-error ignore
136
+ SortableItem.displayName = "SortableItem";
137
+
138
+ const [OptionModal, openOptionModal] = useOverlayService(
139
+ (props: ModalProps) => (
140
+ <Modal {...props}>
141
+ <Content>
142
+ <ArrayInput name={`${field}.options`} onAdd={() => String("")}>
143
+ <Controller>
144
+ <Input />
145
+ </Controller>
146
+ </ArrayInput>
147
+ </Content>
148
+ <Footer
149
+ flex
150
+ justify="end"
151
+ className="sticky bottom-0 border-t bg-base px-6 py-2"
152
+ >
153
+ <Button variant="link" onClick={props.onClose}>
154
+ Close
155
+ </Button>
156
+ </Footer>
157
+ </Modal>
158
+ ),
159
+ );
160
+
161
+ useEffect(() => {
162
+ setTimeout(() => {
163
+ const model = getModel();
164
+ setType(model.datatype);
165
+ setMultiple(model.multiple);
166
+ setHasOptions(!!model.optionList);
167
+ setCustomOptions(model.optionList === SCHEMA_CUSTOM_LIST);
168
+ }, 10);
169
+ }, []);
170
+
171
+ const handleTypeChange = useCallback((type: DATA_TYPES) => {
172
+ if (type) {
173
+ const modelRef = getModel();
174
+ let reset = {
175
+ datatype: type,
176
+ id: field,
177
+ label: modelRef.label,
178
+ defaultValue: modelRef.defaultValue,
179
+ required: modelRef.required,
180
+ multiple: type === DATA_TYPES.AVATAR ? false : modelRef.multiple,
181
+ minItems: modelRef.minItems,
182
+ maxItems: modelRef.maxItems,
183
+ } as DefaultSchema & ValueType;
184
+ if (type === DATA_TYPES.STRING) {
185
+ reset = Object.assign(reset, {
186
+ optionList: modelRef.optionList,
187
+ options: modelRef.options,
188
+ regex: modelRef.regex,
189
+ } as StringSchema);
190
+ } else if (type === DATA_TYPES.DATE) {
191
+ reset = Object.assign(reset, {
192
+ type: "date",
193
+ } as DateSchema);
194
+ } else if (type === DATA_TYPES.NUMBER || type === DATA_TYPES.RANGE) {
195
+ reset = Object.assign(reset, {
196
+ min: modelRef.min,
197
+ max: modelRef.max,
198
+ step: modelRef.step,
199
+ } as NumberSchema);
200
+ }
201
+ if (type === DATA_TYPES.AVATAR) {
202
+ setMultiple(false);
203
+ }
204
+ onTypeChange(reset);
205
+ setType(type);
206
+ }
207
+ }, []);
208
+
209
+ return (
210
+ <SortableItem id={fieldId} className="flex flex-nowrap gap-1 group/field">
211
+ <Collapsable key={fieldId} open={defaultOpen} className="flex-1">
212
+ <div className="flex flex-nowrap items-center">
213
+ <span className="flex-1 truncate">{id}</span>
214
+ {dynamic && (
215
+ <Button
216
+ size="sm"
217
+ color="danger"
218
+ variant="link"
219
+ aria-label="Delete"
220
+ stopPropagation
221
+ icon={CoreIcons.trash}
222
+ onClick={onRemove}
223
+ className="invisible group-hover/field:visible"
224
+ />
225
+ )}
226
+ </div>
227
+ <div className="flex flex-col gap-1 pb-4">
228
+ <Controller name={`${field}.id`}>
229
+ <HiddenInput hiddenValue={id} />
230
+ </Controller>
231
+ <Controller name={`${field}.datatype`}>
232
+ <Select
233
+ inline
234
+ label="Type"
235
+ placeholder="Data type"
236
+ options={acceptableTypes}
237
+ onChange={(val) => handleTypeChange(val as unknown as DATA_TYPES)}
238
+ />
239
+ </Controller>
240
+ <Controller name={`${field}.label`}>
241
+ <Input
242
+ inline
243
+ label="Label"
244
+ allowClear
245
+ placeholder="Label..."
246
+ decorateEndShowWhenEmpty
247
+ decorateEnd={
248
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
249
+ }
250
+ />
251
+ </Controller>
252
+ {type === DATA_TYPES.STRING && (
253
+ <Fragment>
254
+ <Controller name={`${field}.regex`}>
255
+ <Input
256
+ inline
257
+ label="Regex validation"
258
+ allowClear
259
+ placeholder="Regex value..."
260
+ decorateEndShowWhenEmpty
261
+ decorateEnd={
262
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
263
+ }
264
+ />
265
+ </Controller>
266
+ <Field inline label="Option list">
267
+ <Controller name={`${field}.optionList`}>
268
+ <Select
269
+ allowClear
270
+ options={[SCHEMA_CUSTOM_LIST, ...optionLists]}
271
+ onChange={(v) => setCustomOptions(v === SCHEMA_CUSTOM_LIST)}
272
+ />
273
+ </Controller>
274
+ {customOptions && (
275
+ <Button
276
+ icon={CoreIcons.list}
277
+ aria-label="Custom options"
278
+ onClick={() => {
279
+ void openOptionModal();
280
+ }}
281
+ />
282
+ )}
283
+ </Field>
284
+ {OptionModal}
285
+ </Fragment>
286
+ )}
287
+ {type === DATA_TYPES.FILE && (
288
+ <Fragment>
289
+ <Controller name={`${field}.accept`}>
290
+ <Input
291
+ inline
292
+ label="Accept types"
293
+ allowClear
294
+ placeholder="Accept value..."
295
+ decorateEndShowWhenEmpty
296
+ decorateEnd={
297
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
298
+ }
299
+ />
300
+ </Controller>
301
+ </Fragment>
302
+ )}
303
+ {[DATA_TYPES.NUMBER, DATA_TYPES.RANGE].includes(
304
+ type as unknown as DATA_TYPES,
305
+ ) && (
306
+ <Fragment>
307
+ <Controller name={`${field}.min`}>
308
+ <Number
309
+ inline
310
+ label="Min value"
311
+ allowClear
312
+ placeholder="Minimum value..."
313
+ decorateEndShowWhenEmpty
314
+ decorateEnd={
315
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
316
+ }
317
+ />
318
+ </Controller>
319
+ <Controller name={`${field}.max`}>
320
+ <Number
321
+ inline
322
+ label="Max value"
323
+ allowClear
324
+ placeholder="Maximum value..."
325
+ decorateEndShowWhenEmpty
326
+ decorateEnd={
327
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
328
+ }
329
+ />
330
+ </Controller>
331
+ <Controller name={`${field}.step`}>
332
+ <Number
333
+ inline
334
+ label="Step value"
335
+ allowClear
336
+ placeholder="Step value..."
337
+ decorateEndShowWhenEmpty
338
+ decorateEnd={
339
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
340
+ }
341
+ />
342
+ </Controller>
343
+ </Fragment>
344
+ )}
345
+ {type === DATA_TYPES.DATE && (
346
+ <Fragment>
347
+ <Field inline label="Type" plain>
348
+ <Controller name={`${field}.type`}>
349
+ <ToggleButtonGroup value="" fullWidth className="flex-1">
350
+ <Button className="flex-1" value="date">
351
+ Date
352
+ </Button>
353
+ <Button className="flex-1" value="datetime">
354
+ Date Time
355
+ </Button>
356
+ </ToggleButtonGroup>
357
+ </Controller>
358
+ </Field>
359
+ <Controller name={`${field}.min`}>
360
+ <DateInput
361
+ inline
362
+ label="Min value"
363
+ allowClear
364
+ placeholder="Minimum value..."
365
+ decorateEndShowWhenEmpty
366
+ decorateEnd={
367
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
368
+ }
369
+ />
370
+ </Controller>
371
+ <Controller name={`${field}.max`}>
372
+ <DateInput
373
+ inline
374
+ label="Max value"
375
+ allowClear
376
+ placeholder="Maximum value..."
377
+ decorateEndShowWhenEmpty
378
+ decorateEnd={
379
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
380
+ }
381
+ />
382
+ </Controller>
383
+ </Fragment>
384
+ )}
385
+ <Field label=" " inline plain>
386
+ <Controller name={`${field}.required`}>
387
+ <Checkbox label="Required" />
388
+ </Controller>
389
+ {type !== DATA_TYPES.AVATAR && (
390
+ <Controller name={`${field}.multiple`}>
391
+ <Checkbox label="Multiple" onChange={setMultiple} />
392
+ </Controller>
393
+ )}
394
+ {hasOptions && (
395
+ <Controller name={`${field}.allowCustom`}>
396
+ <Checkbox label="Allow custom value" />
397
+ </Controller>
398
+ )}
399
+ </Field>
400
+ {multiple && (
401
+ <Fragment>
402
+ <Controller name={`${field}.minItems`}>
403
+ <Number
404
+ inline
405
+ label="Min items"
406
+ allowClear
407
+ placeholder="Minimum items..."
408
+ decorateEndShowWhenEmpty
409
+ decorateEnd={
410
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
411
+ }
412
+ />
413
+ </Controller>
414
+ <Controller name={`${field}.maxItems`}>
415
+ <Number
416
+ inline
417
+ label="Max items"
418
+ allowClear
419
+ placeholder="Maximum items..."
420
+ decorateEndShowWhenEmpty
421
+ decorateEnd={
422
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
423
+ }
424
+ />
425
+ </Controller>
426
+ </Fragment>
427
+ )}
428
+ </div>
429
+ </Collapsable>
430
+ </SortableItem>
431
+ );
432
+ };
package/src/form/Form.tsx CHANGED
@@ -47,7 +47,6 @@ export interface FormRef<K extends KeyValue> {
47
47
  submit: () => void;
48
48
  validate: () => Promise<boolean>;
49
49
  getValues: () => K;
50
- removeField: (field: string) => void;
51
50
  setValue: (key: keyof K, value: AnyObject) => void;
52
51
  setValues: (values: K) => void;
53
52
  }
@@ -86,7 +85,6 @@ export const Form = <K extends KeyValue>({
86
85
  const ref = useRef<HTMLFormElement>(null);
87
86
  const form = useForm<K>({
88
87
  shouldFocusError: true,
89
- shouldUnregister: true,
90
88
  resolver: schema && (yupResolver(schema) as AnyObject),
91
89
  defaultValues: defaultValues as DefaultValues<K>,
92
90
  });
@@ -121,8 +119,6 @@ export const Form = <K extends KeyValue>({
121
119
  validate: async () => await form.trigger(),
122
120
  getValues: () => form.getValues(),
123
121
  setValues: (v) => setTimeout(() => form.reset(v), 50),
124
- removeField: (field: AnyObject) =>
125
- form.unregister(field, { keepDefaultValue: false, keepValue: false }),
126
122
  setValue: (k, v) =>
127
123
  setTimeout(
128
124
  () =>
@@ -154,7 +150,10 @@ export const Form = <K extends KeyValue>({
154
150
  <form
155
151
  ref={ref}
156
152
  onReset={() => handleReset(defaultValues)}
157
- onSubmit={form.handleSubmit(onSubmit, onInvalid) as AnyObject}
153
+ onSubmit={(e) => {
154
+ e.stopPropagation();
155
+ void form.handleSubmit(onSubmit, onInvalid)(e);
156
+ }}
158
157
  data-loading={form.formState.isSubmitting}
159
158
  className="contents"
160
159
  autoComplete="off"
package/src/index.ts CHANGED
@@ -31,7 +31,12 @@ export { SchemaEditor } from "./builder/SchemaEditor";
31
31
  export { useFileUploader } from "./hooks/useFileUploader";
32
32
  export { useFormBuilder } from "./hooks/useFormBuilder";
33
33
 
34
- export { DATA_TYPES, type FormSchema, type SchemaDef } from "./types/schema";
34
+ export {
35
+ DATA_TYPES,
36
+ SCHEMA_CUSTOM_LIST,
37
+ type FormSchema,
38
+ type SchemaDef,
39
+ } from "./types/schema";
35
40
 
36
41
  export { ArrayInput } from "./input/ArrayInput";
37
42
  export { Checkbox } from "./input/Checkbox";
@@ -48,6 +48,7 @@ import classes from "./ArrayInput.module.css";
48
48
 
49
49
  import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
50
50
  import { CSS } from "@dnd-kit/utilities";
51
+
51
52
  export interface ArrayInputProps {
52
53
  /**
53
54
  * input label
@@ -21,6 +21,7 @@
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 { type Elements } from "@react-fabric/core/dist/types/types";
24
25
  import { type DateLike } from "@react-fabric/date";
25
26
 
26
27
  export enum DATA_TYPES {
@@ -36,6 +37,8 @@ export enum DATA_TYPES {
36
37
  SCHEMA = "schema",
37
38
  }
38
39
 
40
+ export const SCHEMA_CUSTOM_LIST = "--CUSTOM--";
41
+
39
42
  interface SingleValue {
40
43
  multiple?: false;
41
44
  minItems?: never;
@@ -122,3 +125,30 @@ export interface ChildSchema extends BaseSchema {
122
125
 
123
126
  export type SchemaDef = SchemaType | (ChildSchema & ValueType);
124
127
  export type FormSchema = SchemaDef[];
128
+
129
+ export interface SchemaEditorProps {
130
+ /**
131
+ * default form schema
132
+ */
133
+ schemaDef: FormSchema;
134
+ /**
135
+ * is dynamic schema (allow add/remove)
136
+ */
137
+ dynamic?: boolean;
138
+ /**
139
+ * acceptable list of data types
140
+ */
141
+ acceptableTypes?: DATA_TYPES[];
142
+
143
+ /**
144
+ * available option lists in application
145
+ */
146
+ optionLists?: string[];
147
+
148
+ /**
149
+ * footer actions
150
+ */
151
+ children?: Elements<JSX.Element> | Array<Elements<JSX.Element>>;
152
+
153
+ onChange: (schema: FormSchema) => void;
154
+ }