@react-fabric/form 1.0.0-beta.34 → 1.0.0-beta.36

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,435 @@
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(
172
+ (type: DATA_TYPES) => {
173
+ if (type) {
174
+ const modelRef = getModel();
175
+ let reset = {
176
+ datatype: type,
177
+ id,
178
+ label: modelRef.label,
179
+ defaultValue: modelRef.defaultValue,
180
+ required: modelRef.required,
181
+ multiple: type === DATA_TYPES.AVATAR ? false : modelRef.multiple,
182
+ minItems: modelRef.minItems,
183
+ maxItems: modelRef.maxItems,
184
+ } as DefaultSchema & ValueType;
185
+ if (type === DATA_TYPES.STRING) {
186
+ reset = Object.assign(reset, {
187
+ optionList: modelRef.optionList,
188
+ options: modelRef.options,
189
+ regex: modelRef.regex,
190
+ } as StringSchema);
191
+ } else if (type === DATA_TYPES.DATE) {
192
+ reset = Object.assign(reset, {
193
+ type: "date",
194
+ } as DateSchema);
195
+ } else if (type === DATA_TYPES.NUMBER || type === DATA_TYPES.RANGE) {
196
+ reset = Object.assign(reset, {
197
+ min: modelRef.min,
198
+ max: modelRef.max,
199
+ step: modelRef.step,
200
+ } as NumberSchema);
201
+ }
202
+ if (type === DATA_TYPES.AVATAR) {
203
+ setMultiple(false);
204
+ }
205
+ onTypeChange(reset);
206
+ setType(type);
207
+ }
208
+ },
209
+ [id],
210
+ );
211
+
212
+ return (
213
+ <SortableItem id={fieldId} className="flex flex-nowrap gap-1 group/field">
214
+ <Collapsable key={fieldId} open={defaultOpen} className="flex-1">
215
+ <div className="flex flex-nowrap items-center">
216
+ <span className="flex-1 truncate">{id}</span>
217
+ {dynamic && (
218
+ <Button
219
+ size="sm"
220
+ color="danger"
221
+ variant="link"
222
+ aria-label="Delete"
223
+ stopPropagation
224
+ icon={CoreIcons.trash}
225
+ onClick={onRemove}
226
+ className="invisible group-hover/field:visible"
227
+ />
228
+ )}
229
+ </div>
230
+ <div className="flex flex-col gap-1 pb-4">
231
+ <Controller name={`${field}.id`}>
232
+ <HiddenInput hiddenValue={id} />
233
+ </Controller>
234
+ <Controller name={`${field}.datatype`}>
235
+ <Select
236
+ inline
237
+ label="Type"
238
+ placeholder="Data type"
239
+ options={acceptableTypes}
240
+ onChange={(val) => handleTypeChange(val as unknown as DATA_TYPES)}
241
+ />
242
+ </Controller>
243
+ <Controller name={`${field}.label`}>
244
+ <Input
245
+ inline
246
+ label="Label"
247
+ allowClear
248
+ placeholder="Label..."
249
+ decorateEndShowWhenEmpty
250
+ decorateEnd={
251
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
252
+ }
253
+ />
254
+ </Controller>
255
+ {type === DATA_TYPES.STRING && (
256
+ <Fragment>
257
+ <Controller name={`${field}.regex`}>
258
+ <Input
259
+ inline
260
+ label="Regex validation"
261
+ allowClear
262
+ placeholder="Regex value..."
263
+ decorateEndShowWhenEmpty
264
+ decorateEnd={
265
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
266
+ }
267
+ />
268
+ </Controller>
269
+ <Field inline label="Option list">
270
+ <Controller name={`${field}.optionList`}>
271
+ <Select
272
+ allowClear
273
+ options={[SCHEMA_CUSTOM_LIST, ...optionLists]}
274
+ onChange={(v) => setCustomOptions(v === SCHEMA_CUSTOM_LIST)}
275
+ />
276
+ </Controller>
277
+ {customOptions && (
278
+ <Button
279
+ icon={CoreIcons.list}
280
+ aria-label="Custom options"
281
+ onClick={() => {
282
+ void openOptionModal({ title: `${id} Options` });
283
+ }}
284
+ />
285
+ )}
286
+ </Field>
287
+ {OptionModal}
288
+ </Fragment>
289
+ )}
290
+ {type === DATA_TYPES.FILE && (
291
+ <Fragment>
292
+ <Controller name={`${field}.accept`}>
293
+ <Input
294
+ inline
295
+ label="Accept types"
296
+ allowClear
297
+ placeholder="Accept value..."
298
+ decorateEndShowWhenEmpty
299
+ decorateEnd={
300
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
301
+ }
302
+ />
303
+ </Controller>
304
+ </Fragment>
305
+ )}
306
+ {[DATA_TYPES.NUMBER, DATA_TYPES.RANGE].includes(
307
+ type as unknown as DATA_TYPES,
308
+ ) && (
309
+ <Fragment>
310
+ <Controller name={`${field}.min`}>
311
+ <Number
312
+ inline
313
+ label="Min value"
314
+ allowClear
315
+ placeholder="Minimum value..."
316
+ decorateEndShowWhenEmpty
317
+ decorateEnd={
318
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
319
+ }
320
+ />
321
+ </Controller>
322
+ <Controller name={`${field}.max`}>
323
+ <Number
324
+ inline
325
+ label="Max value"
326
+ allowClear
327
+ placeholder="Maximum value..."
328
+ decorateEndShowWhenEmpty
329
+ decorateEnd={
330
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
331
+ }
332
+ />
333
+ </Controller>
334
+ <Controller name={`${field}.step`}>
335
+ <Number
336
+ inline
337
+ label="Step value"
338
+ allowClear
339
+ placeholder="Step value..."
340
+ decorateEndShowWhenEmpty
341
+ decorateEnd={
342
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
343
+ }
344
+ />
345
+ </Controller>
346
+ </Fragment>
347
+ )}
348
+ {type === DATA_TYPES.DATE && (
349
+ <Fragment>
350
+ <Field inline label="Type" plain>
351
+ <Controller name={`${field}.type`}>
352
+ <ToggleButtonGroup value="" fullWidth className="flex-1">
353
+ <Button className="flex-1" value="date">
354
+ Date
355
+ </Button>
356
+ <Button className="flex-1" value="datetime">
357
+ Date Time
358
+ </Button>
359
+ </ToggleButtonGroup>
360
+ </Controller>
361
+ </Field>
362
+ <Controller name={`${field}.min`}>
363
+ <DateInput
364
+ inline
365
+ label="Min value"
366
+ allowClear
367
+ placeholder="Minimum value..."
368
+ decorateEndShowWhenEmpty
369
+ decorateEnd={
370
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
371
+ }
372
+ />
373
+ </Controller>
374
+ <Controller name={`${field}.max`}>
375
+ <DateInput
376
+ inline
377
+ label="Max value"
378
+ allowClear
379
+ placeholder="Maximum value..."
380
+ decorateEndShowWhenEmpty
381
+ decorateEnd={
382
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
383
+ }
384
+ />
385
+ </Controller>
386
+ </Fragment>
387
+ )}
388
+ <Field label=" " inline plain>
389
+ <Controller name={`${field}.required`}>
390
+ <Checkbox label="Required" />
391
+ </Controller>
392
+ {type !== DATA_TYPES.AVATAR && (
393
+ <Controller name={`${field}.multiple`}>
394
+ <Checkbox label="Multiple" onChange={setMultiple} />
395
+ </Controller>
396
+ )}
397
+ {hasOptions && (
398
+ <Controller name={`${field}.allowCustom`}>
399
+ <Checkbox label="Allow custom value" />
400
+ </Controller>
401
+ )}
402
+ </Field>
403
+ {multiple && (
404
+ <Fragment>
405
+ <Controller name={`${field}.minItems`}>
406
+ <Number
407
+ inline
408
+ label="Min items"
409
+ allowClear
410
+ placeholder="Minimum items..."
411
+ decorateEndShowWhenEmpty
412
+ decorateEnd={
413
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
414
+ }
415
+ />
416
+ </Controller>
417
+ <Controller name={`${field}.maxItems`}>
418
+ <Number
419
+ inline
420
+ label="Max items"
421
+ allowClear
422
+ placeholder="Maximum items..."
423
+ decorateEndShowWhenEmpty
424
+ decorateEnd={
425
+ <span className="text-sm text-muted/50 px-1">OPTIONAL</span>
426
+ }
427
+ />
428
+ </Controller>
429
+ </Fragment>
430
+ )}
431
+ </div>
432
+ </Collapsable>
433
+ </SortableItem>
434
+ );
435
+ };
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,31 @@ 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
+ onSubmit?: (schema: FormSchema) => void;
155
+ }