@rjsf/utils 6.0.0-beta.20 → 6.0.0-beta.22

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 (63) hide show
  1. package/dist/index.cjs +202 -68
  2. package/dist/index.cjs.map +4 -4
  3. package/dist/utils.esm.js +202 -68
  4. package/dist/utils.esm.js.map +4 -4
  5. package/dist/utils.umd.js +175 -57
  6. package/lib/ErrorSchemaBuilder.d.ts +2 -2
  7. package/lib/createSchemaUtils.js +6 -4
  8. package/lib/createSchemaUtils.js.map +1 -1
  9. package/lib/enums.d.ts +6 -0
  10. package/lib/enums.js +6 -0
  11. package/lib/enums.js.map +1 -1
  12. package/lib/guessType.d.ts +1 -1
  13. package/lib/idGenerators.d.ts +8 -1
  14. package/lib/idGenerators.js +10 -1
  15. package/lib/idGenerators.js.map +1 -1
  16. package/lib/index.d.ts +9 -4
  17. package/lib/index.js +9 -4
  18. package/lib/index.js.map +1 -1
  19. package/lib/isFormDataAvailable.d.ts +7 -0
  20. package/lib/isFormDataAvailable.js +13 -0
  21. package/lib/isFormDataAvailable.js.map +1 -0
  22. package/lib/isRootSchema.d.ts +13 -0
  23. package/lib/isRootSchema.js +25 -0
  24. package/lib/isRootSchema.js.map +1 -0
  25. package/lib/nameGenerators.d.ts +13 -0
  26. package/lib/nameGenerators.js +30 -0
  27. package/lib/nameGenerators.js.map +1 -0
  28. package/lib/schema/getDefaultFormState.d.ts +8 -3
  29. package/lib/schema/getDefaultFormState.js +15 -6
  30. package/lib/schema/getDefaultFormState.js.map +1 -1
  31. package/lib/schema/retrieveSchema.d.ts +10 -5
  32. package/lib/schema/retrieveSchema.js +37 -14
  33. package/lib/schema/retrieveSchema.js.map +1 -1
  34. package/lib/shouldRenderOptionalField.d.ts +18 -0
  35. package/lib/shouldRenderOptionalField.js +47 -0
  36. package/lib/shouldRenderOptionalField.js.map +1 -0
  37. package/lib/toFieldPathId.d.ts +4 -2
  38. package/lib/toFieldPathId.js +10 -3
  39. package/lib/toFieldPathId.js.map +1 -1
  40. package/lib/tsconfig.tsbuildinfo +1 -1
  41. package/lib/types.d.ts +87 -43
  42. package/lib/useDeepCompareMemo.d.ts +8 -0
  43. package/lib/useDeepCompareMemo.js +17 -0
  44. package/lib/useDeepCompareMemo.js.map +1 -0
  45. package/lib/validationDataMerge.d.ts +2 -1
  46. package/lib/validationDataMerge.js +3 -2
  47. package/lib/validationDataMerge.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/ErrorSchemaBuilder.ts +2 -2
  50. package/src/createSchemaUtils.ts +6 -1
  51. package/src/enums.ts +6 -0
  52. package/src/idGenerators.ts +11 -1
  53. package/src/index.ts +15 -2
  54. package/src/isFormDataAvailable.ts +13 -0
  55. package/src/isRootSchema.ts +30 -0
  56. package/src/nameGenerators.ts +43 -0
  57. package/src/schema/getDefaultFormState.ts +20 -2
  58. package/src/schema/retrieveSchema.ts +39 -5
  59. package/src/shouldRenderOptionalField.ts +56 -0
  60. package/src/toFieldPathId.ts +12 -2
  61. package/src/types.ts +100 -47
  62. package/src/useDeepCompareMemo.ts +17 -0
  63. package/src/validationDataMerge.ts +7 -1
package/lib/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ButtonHTMLAttributes, ChangeEvent, ComponentType, HTMLAttributes, ReactElement, ReactNode, StyleHTMLAttributes } from 'react';
1
+ import type { ButtonHTMLAttributes, ChangeEvent, ComponentType, FocusEvent, HTMLAttributes, ReactElement, ReactNode, StyleHTMLAttributes } from 'react';
2
2
  import { JSONSchema7 } from 'json-schema';
3
3
  import { TranslatableString } from './enums.js';
4
4
  /** The representation of any generic object type, usually used as an intersection on other types to make them more
@@ -20,6 +20,8 @@ export type FormContextType = GenericObjectType;
20
20
  /** The interface for the test ID proxy objects that are returned by the `getTestId` utility function.
21
21
  */
22
22
  export type TestIdShape = Record<string, string>;
23
+ /** Function to generate HTML name attributes from path segments */
24
+ export type NameGeneratorFunction = (path: FieldPathList, idPrefix: string, isMultiValue?: boolean) => string;
23
25
  /** Experimental feature that specifies the Array `minItems` default form state behavior
24
26
  */
25
27
  export type Experimental_ArrayMinItems = {
@@ -149,6 +151,8 @@ export type FieldPathId = {
149
151
  $id: string;
150
152
  /** The path for a field */
151
153
  path: FieldPathList;
154
+ /** The optional HTML name attribute for a field, generated by nameGenerator if provided */
155
+ name?: string;
152
156
  };
153
157
  /** Type describing a name used for a field in the `PathSchema` */
154
158
  export type FieldPath = {
@@ -265,9 +269,9 @@ export type TemplatesType<T = any, S extends StrictRJSFSchema = RJSFSchema, F ex
265
269
  /** The template to use while rendering the description for an array field */
266
270
  ArrayFieldDescriptionTemplate: ComponentType<ArrayFieldDescriptionProps<T, S, F>>;
267
271
  /** The template to use while rendering the buttons for an item in an array field */
268
- ArrayFieldItemButtonsTemplate: ComponentType<ArrayFieldItemButtonsTemplateType<T, S, F>>;
272
+ ArrayFieldItemButtonsTemplate: ComponentType<ArrayFieldItemButtonsTemplateProps<T, S, F>>;
269
273
  /** The template to use while rendering an item in an array field */
270
- ArrayFieldItemTemplate: ComponentType<ArrayFieldItemTemplateType<T, S, F>>;
274
+ ArrayFieldItemTemplate: ComponentType<ArrayFieldItemTemplateProps<T, S, F>>;
271
275
  /** The template to use while rendering the title for an array field */
272
276
  ArrayFieldTitleTemplate: ComponentType<ArrayFieldTitleProps<T, S, F>>;
273
277
  /** The template to use while rendering the standard html input */
@@ -288,6 +292,8 @@ export type TemplatesType<T = any, S extends StrictRJSFSchema = RJSFSchema, F ex
288
292
  MultiSchemaFieldTemplate: ComponentType<MultiSchemaFieldTemplateProps<T, S, F>>;
289
293
  /** The template to use while rendering an object */
290
294
  ObjectFieldTemplate: ComponentType<ObjectFieldTemplateProps<T, S, F>>;
295
+ /** The template to use while rendering the Optional Data field controls */
296
+ OptionalDataControlsTemplate: ComponentType<OptionalDataControlsTemplateProps<T, S, F>>;
291
297
  /** The template to use for rendering the title of a field */
292
298
  TitleFieldTemplate: ComponentType<TitleFieldProps<T, S, F>>;
293
299
  /** The template to use for rendering information about an unsupported field type in the schema */
@@ -337,6 +343,10 @@ export type GlobalUISchemaOptions = GenericObjectType & {
337
343
  /** Enables the displaying of description text that contains markdown
338
344
  */
339
345
  enableMarkdownInDescription?: boolean;
346
+ /** Enables the rendering of the Optional Data Field UI for specific types of schemas, either `object`, `array` or
347
+ * both. To disable the Optional Data Field UI for a specific field, provide an empty array within the UI schema.
348
+ */
349
+ enableOptionalDataFieldForType?: ('object' | 'array')[];
340
350
  };
341
351
  /** The set of options from the `Form` that will be available on the `Registry` for use in everywhere the `registry` is
342
352
  * available.
@@ -352,6 +362,11 @@ export type GlobalFormOptions = {
352
362
  readonly idSeparator: string;
353
363
  /** The component update strategy used by the Form and its fields for performance optimization */
354
364
  readonly experimental_componentUpdateStrategy?: 'customDeep' | 'shallow' | 'always';
365
+ /** Optional function to generate custom HTML name attributes for form elements. Receives the field path segments
366
+ * and element type (object or array), and returns a custom name string. This allows backends like PHP/Rails
367
+ * (`root[tasks][0][title]`) or Django (`root__tasks-0__title`) to receive form data in their expected format.
368
+ */
369
+ readonly nameGenerator?: NameGeneratorFunction;
355
370
  };
356
371
  /** The object containing the registered core, theme and custom fields and widgets as well as the root schema, form
357
372
  * context, schema utils and templates.
@@ -466,10 +481,15 @@ export type FieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema,
466
481
  formData?: T;
467
482
  /** The value change event handler; Can be called with a new value to change the value for this field */
468
483
  onChange: FieldProps<T, S, F>['onChange'];
469
- /** The key change event handler; Called when the key associated with a field is changed for an additionalProperty */
470
- onKeyChange: (value: string) => () => void;
471
- /** The property drop/removal event handler; Called when a field is removed in an additionalProperty context */
472
- onDropPropertyClick: (value: string) => () => void;
484
+ /** Callback used to handle the changing of an additional property key's name with the new value
485
+ */
486
+ onKeyRename: (newKey: string) => void;
487
+ /** Callback used to handle the changing of an additional property key's name when the input is blurred. The event's
488
+ * target's value will be used as the new value. Its a wrapper callback around `onKeyRename`
489
+ */
490
+ onKeyRenameBlur: (event: FocusEvent<HTMLInputElement>) => void;
491
+ /** Callback used to handle the removal of the additionalProperty */
492
+ onRemoveProperty: () => void;
473
493
  };
474
494
  /** The properties that are passed to the `UnsupportedFieldTemplate` implementation */
475
495
  export type UnsupportedFieldProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
@@ -486,6 +506,8 @@ export type TitleFieldProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F
486
506
  title: string;
487
507
  /** A boolean value stating if the field is required */
488
508
  required?: boolean;
509
+ /** Add optional data control */
510
+ optionalDataControl?: ReactNode;
489
511
  };
490
512
  /** The properties that are passed to a `DescriptionFieldTemplate` implementation */
491
513
  export type DescriptionFieldProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
@@ -500,6 +522,8 @@ export type ArrayFieldTitleProps<T = any, S extends StrictRJSFSchema = RJSFSchem
500
522
  title?: string;
501
523
  /** The FieldPathId of the field in the hierarchy */
502
524
  fieldPathId: FieldPathId;
525
+ /** Add optional data control */
526
+ optionalDataControl?: ReactNode;
503
527
  };
504
528
  /** The properties that are passed to a `ArrayFieldDescriptionTemplate` implementation */
505
529
  export type ArrayFieldDescriptionProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = Omit<DescriptionFieldProps<T, S, F>, 'id' | 'description'> & {
@@ -509,7 +533,7 @@ export type ArrayFieldDescriptionProps<T = any, S extends StrictRJSFSchema = RJS
509
533
  fieldPathId: FieldPathId;
510
534
  };
511
535
  /** The properties of the buttons to render for each element in the ArrayFieldTemplateProps.items array */
512
- export type ArrayFieldItemButtonsTemplateType<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
536
+ export type ArrayFieldItemButtonsTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
513
537
  /** The FieldPathId of the item for which buttons are being rendered */
514
538
  fieldPathId: FieldPathId;
515
539
  /** The className string */
@@ -532,23 +556,25 @@ export type ArrayFieldItemButtonsTemplateType<T = any, S extends StrictRJSFSchem
532
556
  index: number;
533
557
  /** A number stating the total number `items` in the array */
534
558
  totalItems: number;
535
- /** Returns a function that adds a new item at `index` */
536
- onAddIndexClick: (index: number) => (event?: any) => void;
537
- /** Returns a function that copies the item at `index` into the position at `index + 1` */
538
- onCopyIndexClick: (index: number) => (event?: any) => void;
539
- /** Returns a function that removes the item at `index` */
540
- onDropIndexClick: (index: number) => (event?: any) => void;
541
- /** Returns a function that swaps the items at `index` with `newIndex` */
542
- onReorderClick: (index: number, newIndex: number) => (event?: any) => void;
559
+ /** Callback function that adds a new item below this item */
560
+ onAddItem: (event?: any) => void;
561
+ /** Callback function that copies this item below itself */
562
+ onCopyItem: (event?: any) => void;
563
+ /** Callback function that moves the item up one spot in the list */
564
+ onMoveUpItem: (event?: any) => void;
565
+ /** Callback function that moves the item down one spot in the list */
566
+ onMoveDownItem: (event?: any) => void;
567
+ /** Callback function that removes the item from the list */
568
+ onRemoveItem: (event?: any) => void;
543
569
  /** A boolean value stating if the array item is read-only */
544
570
  readonly?: boolean;
545
571
  };
546
- /** The properties of each element in the ArrayFieldTemplateProps.items array */
547
- export type ArrayFieldItemTemplateType<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
572
+ /** The properties used to render the ArrayFieldItemTemplate */
573
+ export type ArrayFieldItemTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
548
574
  /** The html for the item's content */
549
575
  children: ReactNode;
550
576
  /** The props to pass to the `ArrayFieldItemButtonTemplate` */
551
- buttonsProps: ArrayFieldItemButtonsTemplateType<T, S, F>;
577
+ buttonsProps: ArrayFieldItemButtonsTemplateProps<T, S, F>;
552
578
  /** The className string */
553
579
  className: string;
554
580
  /** A boolean value stating if the array item is disabled */
@@ -562,26 +588,20 @@ export type ArrayFieldItemTemplateType<T = any, S extends StrictRJSFSchema = RJS
562
588
  /** A boolean value stating if the array item is read-only */
563
589
  readonly?: boolean;
564
590
  /** A stable, unique key for the array item */
565
- key: string;
591
+ itemKey: string;
592
+ /** The UI schema of the array item's parent array field used for
593
+ * customization in some themes
594
+ */
595
+ parentUiSchema?: UiSchema<T, S, F>;
566
596
  };
567
- /**
568
- * @deprecated - Use `ArrayFieldItemTemplateType` instead
569
- */
570
- export type ArrayFieldTemplateItemType<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = ArrayFieldItemTemplateType<T, S, F>;
571
- /** The properties that are passed to an `ArrayFieldTemplate` implementation */
572
- export type ArrayFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
573
- /** A boolean value stating whether new elements can be added to the array */
574
- canAdd?: boolean;
597
+ /** The common properties of the two container templates: `ArrayFieldTemplateProps` and `ObjectFieldTemplateProps` */
598
+ export type ContainerFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
575
599
  /** The className string */
576
600
  className?: string;
577
601
  /** A boolean value stating if the array is disabled */
578
602
  disabled?: boolean;
579
603
  /** The FieldPathId of the field in the hierarchy */
580
604
  fieldPathId: FieldPathId;
581
- /** An array of objects representing the items in the array */
582
- items: ArrayFieldItemTemplateType<T, S, F>[];
583
- /** A function that adds a new item to the array */
584
- onAddClick: (event?: any) => void;
585
605
  /** A boolean value stating if the array is read-only */
586
606
  readonly?: boolean;
587
607
  /** A boolean value stating if the array is required */
@@ -592,8 +612,19 @@ export type ArrayFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSc
592
612
  title: string;
593
613
  /** The formData for this array */
594
614
  formData?: T;
595
- /** The tree of errors for this field and its children */
615
+ /** The optional validation errors in the form of an `ErrorSchema` */
596
616
  errorSchema?: ErrorSchema<T>;
617
+ /** The optional data control node to render within the ObjectFieldTemplate that controls */
618
+ optionalDataControl?: ReactNode;
619
+ };
620
+ /** The properties that are passed to an `ArrayFieldTemplate` implementation */
621
+ export type ArrayFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = ContainerFieldTemplateProps<T, S, F> & {
622
+ /** A boolean value stating whether new elements can be added to the array */
623
+ canAdd?: boolean;
624
+ /** An array of React elements representing the items in the array */
625
+ items: ReactElement[];
626
+ /** A function that adds a new item to the end of the array */
627
+ onAddClick: (event?: any) => void;
597
628
  /** An array of strings listing all generated error messages from encountered errors for this widget */
598
629
  rawErrors?: string[];
599
630
  };
@@ -611,17 +642,15 @@ export type ObjectFieldTemplatePropertyType = {
611
642
  hidden: boolean;
612
643
  };
613
644
  /** The properties that are passed to an ObjectFieldTemplate implementation */
614
- export type ObjectFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
615
- /** A string value containing the title for the object */
616
- title: string;
645
+ export type ObjectFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = ContainerFieldTemplateProps<T, S, F> & {
617
646
  /** A string value containing the description for the object */
618
647
  description?: string | ReactElement;
619
- /** A boolean value stating if the object is disabled */
620
- disabled?: boolean;
621
648
  /** An array of objects representing the properties in the object */
622
649
  properties: ObjectFieldTemplatePropertyType[];
623
- /** Returns a function that adds a new property to the object (to be used with additionalProperties) */
624
- onAddClick: (schema: S) => () => void;
650
+ /** Callback to use in order to add an new additionalProperty to the object field (to be used with
651
+ * additionalProperties and patternProperties)
652
+ */
653
+ onAddProperty: () => void;
625
654
  /** A boolean value stating if the object is read-only */
626
655
  readonly?: boolean;
627
656
  /** A boolean value stating if the object is required */
@@ -635,11 +664,22 @@ export type ObjectFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFS
635
664
  /** The form data for the object */
636
665
  formData?: T;
637
666
  };
667
+ /** The properties that are passed to a OptionalDataControlsTemplate implementation */
668
+ export type OptionalDataControlsTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
669
+ /** The generated id for this Optional Data Control instance */
670
+ id: string;
671
+ /** The label to use for the Optional Data Control */
672
+ label: string;
673
+ /** Optional callback to call when clicking on the Optional Data Control to add data */
674
+ onRemoveClick?: () => void;
675
+ /** Optional callback to call when clicking on the Optional Data Control to remove data */
676
+ onAddClick?: () => void;
677
+ };
638
678
  /** The properties that are passed to a WrapIfAdditionalTemplate implementation */
639
679
  export type WrapIfAdditionalTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = RJSFBaseProps<T, S, F> & {
640
680
  /** The field or widget component instance for this field row */
641
681
  children: ReactNode;
642
- } & Pick<FieldTemplateProps<T, S, F>, 'id' | 'classNames' | 'hideError' | 'rawErrors' | 'style' | 'label' | 'required' | 'readonly' | 'disabled' | 'schema' | 'uiSchema' | 'onKeyChange' | 'onDropPropertyClick' | 'registry'>;
682
+ } & Pick<FieldTemplateProps<T, S, F>, 'id' | 'classNames' | 'hideError' | 'rawErrors' | 'style' | 'label' | 'required' | 'readonly' | 'disabled' | 'schema' | 'uiSchema' | 'onKeyRename' | 'onKeyRenameBlur' | 'onRemoveProperty' | 'registry'>;
643
683
  /** The properties that are passed to a MultiSchemaFieldTemplate implementation */
644
684
  export interface MultiSchemaFieldTemplateProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> extends RJSFBaseProps<T, S, F> {
645
685
  /** The rendered widget used to select a schema option */
@@ -694,6 +734,8 @@ export interface WidgetProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F
694
734
  multiple?: boolean;
695
735
  /** An array of strings listing all generated error messages from encountered errors for this widget */
696
736
  rawErrors?: string[];
737
+ /** The optional custom HTML name attribute generated by the nameGenerator function, if provided */
738
+ htmlName?: string;
697
739
  }
698
740
  /** The definition of a React-based Widget component */
699
741
  export type Widget<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> = ComponentType<WidgetProps<T, S, F>>;
@@ -965,9 +1007,10 @@ export interface SchemaUtilsType<T = any, S extends StrictRJSFSchema = RJSFSchem
965
1007
  * @param [includeUndefinedValues=false] - Optional flag, if true, cause undefined values to be added as defaults.
966
1008
  * If "excludeObjectChildren", cause undefined values for this object and pass `includeUndefinedValues` as
967
1009
  * false when computing defaults for any nested object properties.
1010
+ * @param initialDefaultsGenerated - Indicates whether or not initial defaults have been generated
968
1011
  * @returns - The resulting `formData` with all the defaults provided
969
1012
  */
970
- getDefaultFormState(schema: S, formData?: T, includeUndefinedValues?: boolean | 'excludeObjectChildren'): T | T[] | undefined;
1013
+ getDefaultFormState(schema: S, formData?: T, includeUndefinedValues?: boolean | 'excludeObjectChildren', initialDefaultsGenerated?: boolean): T | T[] | undefined;
971
1014
  /** Determines whether the combination of `schema` and `uiSchema` properties indicates that the label for the `schema`
972
1015
  * should be displayed in a UI.
973
1016
  *
@@ -1037,9 +1080,10 @@ export interface SchemaUtilsType<T = any, S extends StrictRJSFSchema = RJSFSchem
1037
1080
  *
1038
1081
  * @param schema - The schema for which retrieving a schema is desired
1039
1082
  * @param [formData] - The current formData, if any, to assist retrieving a schema
1083
+ * @param [resolveAnyOfOrOneOfRefs] - Optional flag indicating whether to resolved refs in anyOf/oneOf lists
1040
1084
  * @returns - The schema having its conditions, additional properties, references and dependencies resolved
1041
1085
  */
1042
- retrieveSchema(schema: S, formData?: T): S;
1086
+ retrieveSchema(schema: S, formData?: T, resolveAnyOfOrOneOfRefs?: boolean): S;
1043
1087
  /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the
1044
1088
  * new schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the
1045
1089
  * nature of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the
@@ -0,0 +1,8 @@
1
+ /** Hook that stores and returns a `T` value. If `newValue` is the same as the stored one, then the stored one is
2
+ * returned to avoid having a component rerender due it being a different object. Otherwise, the `newValue` is stored
3
+ * and returned.
4
+ *
5
+ * @param newValue - The potential new `T` value
6
+ * @returns - The latest stored `T` value
7
+ */
8
+ export default function useDeepCompareMemo<T = unknown>(newValue: T): T;
@@ -0,0 +1,17 @@
1
+ import { useRef } from 'react';
2
+ import isEqual from 'lodash-es/isEqual.js';
3
+ /** Hook that stores and returns a `T` value. If `newValue` is the same as the stored one, then the stored one is
4
+ * returned to avoid having a component rerender due it being a different object. Otherwise, the `newValue` is stored
5
+ * and returned.
6
+ *
7
+ * @param newValue - The potential new `T` value
8
+ * @returns - The latest stored `T` value
9
+ */
10
+ export default function useDeepCompareMemo(newValue) {
11
+ const valueRef = useRef(newValue);
12
+ if (!isEqual(newValue, valueRef.current)) {
13
+ valueRef.current = newValue;
14
+ }
15
+ return valueRef.current;
16
+ }
17
+ //# sourceMappingURL=useDeepCompareMemo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDeepCompareMemo.js","sourceRoot":"","sources":["../src/useDeepCompareMemo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAc,QAAW;IACjE,MAAM,QAAQ,GAAG,MAAM,CAAI,QAAQ,CAAC,CAAC;IACrC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACzC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC9B,CAAC;IACD,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAC"}
@@ -6,6 +6,7 @@ import { ErrorSchema, ValidationData } from './types.js';
6
6
  *
7
7
  * @param validationData - The current `ValidationData` into which to merge the additional errors
8
8
  * @param [additionalErrorSchema] - The optional additional set of errors in an `ErrorSchema`
9
+ * @param [preventDuplicates=false] - Optional flag, if true, will call `mergeObjects()` with `preventDuplicates`
9
10
  * @returns - The `validationData` with the additional errors from `additionalErrorSchema` merged into it, if provided.
10
11
  */
11
- export default function validationDataMerge<T = any>(validationData: ValidationData<T>, additionalErrorSchema?: ErrorSchema<T>): ValidationData<T>;
12
+ export default function validationDataMerge<T = any>(validationData: ValidationData<T>, additionalErrorSchema?: ErrorSchema<T>, preventDuplicates?: boolean): ValidationData<T>;
@@ -8,9 +8,10 @@ import toErrorList from './toErrorList.js';
8
8
  *
9
9
  * @param validationData - The current `ValidationData` into which to merge the additional errors
10
10
  * @param [additionalErrorSchema] - The optional additional set of errors in an `ErrorSchema`
11
+ * @param [preventDuplicates=false] - Optional flag, if true, will call `mergeObjects()` with `preventDuplicates`
11
12
  * @returns - The `validationData` with the additional errors from `additionalErrorSchema` merged into it, if provided.
12
13
  */
13
- export default function validationDataMerge(validationData, additionalErrorSchema) {
14
+ export default function validationDataMerge(validationData, additionalErrorSchema, preventDuplicates = false) {
14
15
  if (!additionalErrorSchema) {
15
16
  return validationData;
16
17
  }
@@ -18,7 +19,7 @@ export default function validationDataMerge(validationData, additionalErrorSchem
18
19
  let errors = toErrorList(additionalErrorSchema);
19
20
  let errorSchema = additionalErrorSchema;
20
21
  if (!isEmpty(oldErrorSchema)) {
21
- errorSchema = mergeObjects(oldErrorSchema, additionalErrorSchema, true);
22
+ errorSchema = mergeObjects(oldErrorSchema, additionalErrorSchema, preventDuplicates ? 'preventDuplicates' : true);
22
23
  errors = [...oldErrors].concat(errors);
23
24
  }
24
25
  return { errorSchema, errors };
@@ -1 +1 @@
1
- {"version":3,"file":"validationDataMerge.js","sourceRoot":"","sources":["../src/validationDataMerge.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAErC,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAC1C,OAAO,WAAW,MAAM,eAAe,CAAC;AAGxC;;;;;;;;GAQG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CACzC,cAAiC,EACjC,qBAAsC;IAEtC,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC3B,OAAO,cAAc,CAAC;IACxB,CAAC;IACD,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,cAAc,CAAC;IAC1E,IAAI,MAAM,GAAG,WAAW,CAAC,qBAAqB,CAAC,CAAC;IAChD,IAAI,WAAW,GAAG,qBAAqB,CAAC;IACxC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC;QAC7B,WAAW,GAAG,YAAY,CAAC,cAAc,EAAE,qBAAqB,EAAE,IAAI,CAAmB,CAAC;QAC1F,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC;AACjC,CAAC"}
1
+ {"version":3,"file":"validationDataMerge.js","sourceRoot":"","sources":["../src/validationDataMerge.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,gBAAgB,CAAC;AAErC,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAC1C,OAAO,WAAW,MAAM,eAAe,CAAC;AAGxC;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CACzC,cAAiC,EACjC,qBAAsC,EACtC,iBAAiB,GAAG,KAAK;IAEzB,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC3B,OAAO,cAAc,CAAC;IACxB,CAAC;IACD,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,cAAc,CAAC;IAC1E,IAAI,MAAM,GAAG,WAAW,CAAC,qBAAqB,CAAC,CAAC;IAChD,IAAI,WAAW,GAAG,qBAAqB,CAAC;IACxC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC;QAC7B,WAAW,GAAG,YAAY,CACxB,cAAc,EACd,qBAAqB,EACrB,iBAAiB,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,IAAI,CAC7B,CAAC;QACpB,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC;AACjC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rjsf/utils",
3
- "version": "6.0.0-beta.20",
3
+ "version": "6.0.0-beta.22",
4
4
  "main": "dist/index.js",
5
5
  "module": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
@@ -3,13 +3,13 @@ import get from 'lodash/get';
3
3
  import set from 'lodash/set';
4
4
  import setWith from 'lodash/setWith';
5
5
 
6
- import { ErrorSchema } from './types';
6
+ import { ErrorSchema, FieldPathList } from './types';
7
7
  import { ERRORS_KEY } from './constants';
8
8
 
9
9
  /** Represents the type of the path which can be a string of dotted path values or a list of string or numbers where
10
10
  * numbers represent array indexes/
11
11
  */
12
- export type PathType = string | (string | number)[];
12
+ export type PathType = string | FieldPathList;
13
13
 
14
14
  /** The `ErrorSchemaBuilder<T>` is used to build an `ErrorSchema<T>` since the definition of the `ErrorSchema` type is
15
15
  * designed for reading information rather than writing it. Use this class to add, replace or clear errors in an error
@@ -165,12 +165,14 @@ class SchemaUtils<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends Fo
165
165
  * @param [includeUndefinedValues=false] - Optional flag, if true, cause undefined values to be added as defaults.
166
166
  * If "excludeObjectChildren", pass `includeUndefinedValues` as false when computing defaults for any nested
167
167
  * object properties.
168
+ * @param initialDefaultsGenerated - Indicates whether or not initial defaults have been generated
168
169
  * @returns - The resulting `formData` with all the defaults provided
169
170
  */
170
171
  getDefaultFormState(
171
172
  schema: S,
172
173
  formData?: T,
173
174
  includeUndefinedValues: boolean | 'excludeObjectChildren' = false,
175
+ initialDefaultsGenerated?: boolean,
174
176
  ): T | T[] | undefined {
175
177
  return getDefaultFormState<T, S, F>(
176
178
  this.validator,
@@ -180,6 +182,7 @@ class SchemaUtils<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends Fo
180
182
  includeUndefinedValues,
181
183
  this.experimental_defaultFormStateBehavior,
182
184
  this.experimental_customMergeAllOf,
185
+ initialDefaultsGenerated,
183
186
  );
184
187
  }
185
188
 
@@ -301,15 +304,17 @@ class SchemaUtils<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends Fo
301
304
  *
302
305
  * @param schema - The schema for which retrieving a schema is desired
303
306
  * @param [rawFormData] - The current formData, if any, to assist retrieving a schema
307
+ * @param [resolveAnyOfOrOneOfRefs] - Optional flag indicating whether to resolved refs in anyOf/oneOf lists
304
308
  * @returns - The schema having its conditions, additional properties, references and dependencies resolved
305
309
  */
306
- retrieveSchema(schema: S, rawFormData?: T) {
310
+ retrieveSchema(schema: S, rawFormData?: T, resolveAnyOfOrOneOfRefs?: boolean) {
307
311
  return retrieveSchema<T, S, F>(
308
312
  this.validator,
309
313
  schema,
310
314
  this.rootSchema,
311
315
  rawFormData,
312
316
  this.experimental_customMergeAllOf,
317
+ resolveAnyOfOrOneOfRefs,
313
318
  );
314
319
  }
315
320
 
package/src/enums.ts CHANGED
@@ -45,6 +45,12 @@ export enum TranslatableString {
45
45
  DecrementAriaLabel = 'Decrease value by 1',
46
46
  /** Increment button aria label, used by UpDownWidget */
47
47
  IncrementAriaLabel = 'Increase value by 1',
48
+ /** The label for the Add button in for an optional object field */
49
+ OptionalObjectAdd = 'Add data for optional field',
50
+ /** The label for the Remove button in for an optional object field */
51
+ OptionalObjectRemove = 'Remove data for optional field',
52
+ /** The label for when displaying a non-editable form with missing optional field data */
53
+ OptionalObjectEmptyMsg = 'No data for optional field',
48
54
  // Strings with replaceable parameters
49
55
  /** Unknown field type reason, where %1 will be replaced with the type as provided by SchemaField */
50
56
  UnknownFieldType = 'Unknown field type %1',
@@ -82,10 +82,20 @@ export function optionId(id: string, optionIndex: number) {
82
82
 
83
83
  /** Return a consistent `id` for the `btn` button element
84
84
  *
85
- * @param id - Either simple string id or an FieldPathId from which to extract it
85
+ * @param id - The id of the parent component for the option
86
86
  * @param btn - The button type for which to generate the id
87
87
  * @returns - The consistent id for the button from the given `id` and `btn` type
88
88
  */
89
89
  export function buttonId(id: FieldPathId | string, btn: 'add' | 'copy' | 'moveDown' | 'moveUp' | 'remove') {
90
90
  return idGenerator(id, btn);
91
91
  }
92
+
93
+ /** Return a consistent `id` for the optional data controls `element`
94
+ *
95
+ * @param id - The id of the parent component for the option
96
+ * @param element - The element type for which to generate the id
97
+ * @returns - The consistent id for the optional data controls element from the given `id` and `element` type
98
+ */
99
+ export function optionalControlsId(id: FieldPathId | string, element: 'Add' | 'Msg' | 'Remove') {
100
+ return idGenerator(id, `optional${element}`);
101
+ }
package/src/index.ts CHANGED
@@ -15,9 +15,11 @@ import enumOptionsSelectValue from './enumOptionsSelectValue';
15
15
  import enumOptionsValueForIndex from './enumOptionsValueForIndex';
16
16
  import ErrorSchemaBuilder from './ErrorSchemaBuilder';
17
17
  import findSchemaDefinition from './findSchemaDefinition';
18
+ import getChangedFields from './getChangedFields';
18
19
  import getDateElementProps, { type DateElementFormat } from './getDateElementProps';
19
20
  import getDiscriminatorFieldFromSchema from './getDiscriminatorFieldFromSchema';
20
21
  import getInputProps from './getInputProps';
22
+ import getOptionMatchingSimpleDiscriminator from './getOptionMatchingSimpleDiscriminator';
21
23
  import getSchemaType from './getSchemaType';
22
24
  import getSubmitButtonOptions from './getSubmitButtonOptions';
23
25
  import getTemplate from './getTemplate';
@@ -34,13 +36,16 @@ import {
34
36
  errorId,
35
37
  examplesId,
36
38
  helpId,
39
+ optionalControlsId,
37
40
  optionId,
38
41
  titleId,
39
42
  } from './idGenerators';
40
43
  import isConstant from './isConstant';
41
44
  import isCustomWidget from './isCustomWidget';
42
45
  import isFixedItems from './isFixedItems';
46
+ import isFormDataAvailable from './isFormDataAvailable';
43
47
  import isObject from './isObject';
48
+ import isRootSchema from './isRootSchema';
44
49
  import labelValue from './labelValue';
45
50
  import localToUTC from './localToUTC';
46
51
  import lookupFromFormContext from './lookupFromFormContext';
@@ -55,17 +60,18 @@ import rangeSpec from './rangeSpec';
55
60
  import replaceStringParameters from './replaceStringParameters';
56
61
  import schemaRequiresTrueValue from './schemaRequiresTrueValue';
57
62
  import shouldRender from './shouldRender';
63
+ import shouldRenderOptionalField from './shouldRenderOptionalField';
58
64
  import toConstant from './toConstant';
59
65
  import toDateString from './toDateString';
60
66
  import toErrorList from './toErrorList';
61
67
  import toErrorSchema from './toErrorSchema';
62
68
  import toFieldPathId from './toFieldPathId';
63
69
  import unwrapErrorHandler from './unwrapErrorHandler';
70
+ import useDeepCompareMemo from './useDeepCompareMemo';
64
71
  import utcToLocal from './utcToLocal';
65
72
  import validationDataMerge from './validationDataMerge';
66
73
  import withIdRefPrefix from './withIdRefPrefix';
67
- import getOptionMatchingSimpleDiscriminator from './getOptionMatchingSimpleDiscriminator';
68
- import getChangedFields from './getChangedFields';
74
+ import { bracketNameGenerator, dotNotationNameGenerator } from './nameGenerators';
69
75
 
70
76
  export * from './types';
71
77
  export * from './enums';
@@ -117,13 +123,16 @@ export {
117
123
  isConstant,
118
124
  isCustomWidget,
119
125
  isFixedItems,
126
+ isFormDataAvailable,
120
127
  isObject,
128
+ isRootSchema,
121
129
  labelValue,
122
130
  localToUTC,
123
131
  lookupFromFormContext,
124
132
  mergeDefaultsWithFormData,
125
133
  mergeObjects,
126
134
  mergeSchemas,
135
+ optionalControlsId,
127
136
  optionId,
128
137
  optionsList,
129
138
  orderProperties,
@@ -134,6 +143,7 @@ export {
134
143
  schemaRequiresTrueValue,
135
144
  shallowEquals,
136
145
  shouldRender,
146
+ shouldRenderOptionalField,
137
147
  sortedJSONStringify,
138
148
  titleId,
139
149
  toConstant,
@@ -142,9 +152,12 @@ export {
142
152
  toErrorSchema,
143
153
  toFieldPathId,
144
154
  unwrapErrorHandler,
155
+ useDeepCompareMemo,
145
156
  utcToLocal,
146
157
  validationDataMerge,
147
158
  withIdRefPrefix,
159
+ bracketNameGenerator,
160
+ dotNotationNameGenerator,
148
161
  };
149
162
 
150
163
  export type { ComponentUpdateStrategy } from './shouldRender';
@@ -0,0 +1,13 @@
1
+ import isNil from 'lodash/isNil';
2
+ import isEmpty from 'lodash/isEmpty';
3
+ import isObject from 'lodash/isObject';
4
+
5
+ /** Determines whether the given `formData` represents valid form data, such as a primitive type, an array, or a
6
+ * non-empty object.
7
+ *
8
+ * @param formData - The data to check
9
+ * @returns - True if `formData` is not undefined, null, a primitive type or an array or an empty object
10
+ */
11
+ export default function isFormDataAvailable<T = any>(formData?: T): boolean {
12
+ return !isNil(formData) && (!isObject(formData) || Array.isArray(formData) || !isEmpty(formData));
13
+ }
@@ -0,0 +1,30 @@
1
+ import isEqual from 'lodash/isEqual';
2
+
3
+ import { FormContextType, Registry, RJSFSchema, StrictRJSFSchema } from './types';
4
+ import { REF_KEY } from './constants';
5
+
6
+ /** Helper to check whether a JSON schema object is the root schema. The schema is a root schema with root `properties`
7
+ * key or a root `$ref` key. If the `schemaToCompare` has a root `oneOf` property, the function will
8
+ * return false. Else if `schemaToCompare` and `rootSchema` are the same object or equal, the function will return
9
+ * `true`. Else if the `rootSchema` has a $ref, it will be resolved using `schemaUtils.resolveSchema` utility. If the
10
+ * resolved schema matches the `schemaToCompare` the function will return `true`. Otherwise, it will return false.
11
+ *
12
+ * @param registry - The `Registry` used to get the `rootSchema` and `schemaUtils`
13
+ * @param schemaToCompare - The JSON schema object to check. If `schemaToCompare` is an root schema, the
14
+ * function will return true.
15
+ * @returns - Flag indicating whether the `schemaToCompare` is the root schema
16
+ */
17
+ export default function isRootSchema<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(
18
+ registry: Registry<T, S, F>,
19
+ schemaToCompare: S,
20
+ ): boolean {
21
+ const { rootSchema, schemaUtils } = registry;
22
+ if (isEqual(schemaToCompare, rootSchema)) {
23
+ return true;
24
+ }
25
+ if (REF_KEY in rootSchema) {
26
+ const resolvedSchema = schemaUtils.retrieveSchema(rootSchema);
27
+ return isEqual(schemaToCompare, resolvedSchema);
28
+ }
29
+ return false;
30
+ }
@@ -0,0 +1,43 @@
1
+ import { NameGeneratorFunction, FieldPathList } from './types';
2
+
3
+ /**
4
+ * Generates bracketed names
5
+ * Example: root[tasks][0][title]
6
+ * For multi-value fields (checkboxes, multi-select): root[hobbies][]
7
+ */
8
+ export const bracketNameGenerator: NameGeneratorFunction = (
9
+ path: FieldPathList,
10
+ idPrefix: string,
11
+ isMultiValue?: boolean,
12
+ ): string => {
13
+ if (!path || path.length === 0) {
14
+ return idPrefix;
15
+ }
16
+
17
+ const baseName = path.reduce<string>((acc, pathUnit, index) => {
18
+ if (index === 0) {
19
+ return `${idPrefix}[${String(pathUnit)}]`;
20
+ }
21
+ return `${acc}[${String(pathUnit)}]`;
22
+ }, '');
23
+
24
+ // For multi-value fields, append [] to allow multiple values with the same name
25
+ return isMultiValue ? `${baseName}[]` : baseName;
26
+ };
27
+
28
+ /**
29
+ * Generates dot-notation names
30
+ * Example: root.tasks.0.title
31
+ * Multi-value fields are handled the same as single-value fields in dot notation
32
+ */
33
+ export const dotNotationNameGenerator: NameGeneratorFunction = (
34
+ path: FieldPathList,
35
+ idPrefix: string,
36
+ _isMultiValue?: boolean,
37
+ ): string => {
38
+ if (!path || path.length === 0) {
39
+ return idPrefix;
40
+ }
41
+
42
+ return `${idPrefix}.${path.map(String).join('.')}`;
43
+ };