@chris-c-brine/rhf-mui-kit 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/components/AutocompleteElementDisplay.d.ts +11 -0
- package/dist/components/AutocompleteElementDisplay.js +31 -0
- package/dist/components/ObjectDisplayElement.d.ts +79 -0
- package/dist/components/ObjectDisplayElement.js +191 -0
- package/dist/components/ValidationElement.d.ts +21 -0
- package/dist/components/ValidationElement.js +9 -0
- package/dist/components/index.d.ts +3 -0
- package/dist/components/index.js +3 -0
- package/dist/hooks/index.d.ts +2 -0
- package/dist/hooks/index.js +2 -0
- package/dist/hooks/useFormError.d.ts +11 -0
- package/dist/hooks/useFormError.js +17 -0
- package/dist/hooks/useOnMount.d.ts +6 -0
- package/dist/hooks/useOnMount.js +21 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +116 -7849
- package/dist/index.js.map +1 -1
- package/dist/utils.d.ts +3 -0
- package/dist/utils.js +11 -0
- package/package.json +12 -5
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ A specialized component library that extends React Hook Form with Material UI in
|
|
|
15
15
|
|
|
16
16
|
- **AutocompleteDisplayElement**: Enhanced autocomplete with view-only mode support
|
|
17
17
|
- **ObjectDisplayElement**: Autocomplete for complex objects with key/label extraction
|
|
18
|
-
- **
|
|
18
|
+
- **ValidationElement**: Hidden form field with validation support
|
|
19
19
|
|
|
20
20
|
## Hooks
|
|
21
21
|
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type AutocompleteElementProps } from "react-hook-form-mui";
|
|
2
|
+
import { type ChipTypeMap } from "@mui/material";
|
|
3
|
+
import type { FieldPath, FieldValues } from "react-hook-form";
|
|
4
|
+
import { type ElementType } from "react";
|
|
5
|
+
export type AutocompleteElementDisplayProps<TValue, Multiple extends boolean | undefined, DisableClearable extends boolean | undefined, FreeSolo extends boolean | undefined, ChipComponent extends ElementType = ChipTypeMap["defaultComponent"], TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>> = AutocompleteElementProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName> & Viewable;
|
|
6
|
+
export declare const AutocompleteElementDisplay: <TValue, Multiple extends boolean | undefined, DisableClearable extends boolean | undefined, FreeSolo extends boolean | undefined, ChipComponent extends ElementType = ChipTypeMap["defaultComponent"], TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>>({ viewOnly, disableUnderline, textFieldProps, autocompleteProps, ...props }: AutocompleteElementDisplayProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName>) => import("react/jsx-runtime").JSX.Element;
|
|
7
|
+
type Viewable = {
|
|
8
|
+
viewOnly?: boolean;
|
|
9
|
+
disableUnderline?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { AutocompleteElement } from "react-hook-form-mui";
|
|
3
|
+
import { useMemo } from "react";
|
|
4
|
+
import lodash from "lodash";
|
|
5
|
+
const { merge } = lodash;
|
|
6
|
+
export const AutocompleteElementDisplay = ({ viewOnly, disableUnderline, textFieldProps, autocompleteProps, ...props }) => {
|
|
7
|
+
const autocompleteAdjustedProps = useMemo(() => merge({
|
|
8
|
+
readOnly: viewOnly,
|
|
9
|
+
disableClearable: viewOnly,
|
|
10
|
+
disabled: viewOnly,
|
|
11
|
+
slotProps: {
|
|
12
|
+
input: { disableUnderline },
|
|
13
|
+
chip: {
|
|
14
|
+
disabled: false,
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
}, autocompleteProps, viewOnly
|
|
18
|
+
? {
|
|
19
|
+
sx: {
|
|
20
|
+
".MuiAutocomplete-endAdornment": {
|
|
21
|
+
display: "none",
|
|
22
|
+
},
|
|
23
|
+
".MuiAutocomplete-tag": {
|
|
24
|
+
opacity: "1 !important"
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
: {}), [autocompleteProps, viewOnly, disableUnderline]);
|
|
29
|
+
const textFieldAdjustedProps = useMemo(() => merge(viewOnly ? { variant: "standard" } : {}, textFieldProps), [viewOnly, textFieldProps]);
|
|
30
|
+
return (_jsx(AutocompleteElement, { ...props, autocompleteProps: autocompleteAdjustedProps, textFieldProps: textFieldAdjustedProps }));
|
|
31
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type ElementType, ReactNode } from "react";
|
|
2
|
+
import { type ChipProps, type ChipTypeMap } from "@mui/material";
|
|
3
|
+
import type { FieldPath, FieldValues } from "react-hook-form";
|
|
4
|
+
import { type AutocompleteElementDisplayProps } from "./AutocompleteElementDisplay";
|
|
5
|
+
/**
|
|
6
|
+
* Extends DisplayAutocompleteProps with additional properties for handling object values.
|
|
7
|
+
*
|
|
8
|
+
* @template TValue - The type of the option values
|
|
9
|
+
* @template Multiple - Boolean flag indicating if multiple selections are allowed
|
|
10
|
+
* @template DisableClearable - Boolean flag indicating if clearing the selection is disabled
|
|
11
|
+
* @template FreeSolo - Boolean flag indicating if free text input is allowed
|
|
12
|
+
* @template ChipComponent - The component type used for rendering chips in multiple selection mode
|
|
13
|
+
* @template TFieldValues - The type of the form values
|
|
14
|
+
* @template TName - The type of the field name
|
|
15
|
+
*/
|
|
16
|
+
export type DisplayObjectCompleteProps<TValue, Multiple extends boolean | undefined, DisableClearable extends boolean | undefined, FreeSolo extends boolean | undefined, ChipComponent extends ElementType = ChipTypeMap["defaultComponent"], TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>> = AutocompleteElementDisplayProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName> & {
|
|
17
|
+
/**
|
|
18
|
+
* Function to extract a unique key from an option value.
|
|
19
|
+
* Used for option comparison and deduplication.
|
|
20
|
+
*
|
|
21
|
+
* @param value - The option value or null
|
|
22
|
+
* @returns A unique string key for the value
|
|
23
|
+
*/
|
|
24
|
+
getItemKey: (value: TValue | null) => string;
|
|
25
|
+
/**
|
|
26
|
+
* Function to generate a display label for an option value.
|
|
27
|
+
* Can return any ReactNode for custom rendering.
|
|
28
|
+
*
|
|
29
|
+
* @param value - The option value or null
|
|
30
|
+
* @returns A ReactNode to display as the option label
|
|
31
|
+
*/
|
|
32
|
+
getItemLabel: (value: TValue | null) => ReactNode;
|
|
33
|
+
/**
|
|
34
|
+
* Function to convert a free text input string to a TValue object.
|
|
35
|
+
* Required when freeSolo is true to create new items from text input.
|
|
36
|
+
*
|
|
37
|
+
* @param value - The string value entered by the user
|
|
38
|
+
* @returns A new TValue object created from the string
|
|
39
|
+
*/
|
|
40
|
+
stringToNewItem?: (value: string) => TValue;
|
|
41
|
+
/**
|
|
42
|
+
* Whether the input allows free text entry.
|
|
43
|
+
* When true, users can enter values that are not in the options.
|
|
44
|
+
*/
|
|
45
|
+
freeSolo?: FreeSolo;
|
|
46
|
+
/**
|
|
47
|
+
* Optional function that returns additional chip props based on the value.
|
|
48
|
+
* This allows for customizing chip appearance and behavior based on the value it represents.
|
|
49
|
+
*
|
|
50
|
+
* @param value - The option value being rendered as a chip
|
|
51
|
+
* @returns Additional props to apply to the Chip component
|
|
52
|
+
*/
|
|
53
|
+
getChipProps?: (props: {
|
|
54
|
+
value: TValue;
|
|
55
|
+
index: number;
|
|
56
|
+
}) => Partial<ChipProps> | undefined;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* A form component that displays a searchable dropdown for selecting object values.
|
|
60
|
+
* Extends AutocompleteDisplayElement with object-specific functionality.
|
|
61
|
+
*
|
|
62
|
+
* Features:
|
|
63
|
+
* - Works with complex object values instead of just primitive types
|
|
64
|
+
* - Supports both single and multiple selection modes
|
|
65
|
+
* - Supports free-solo mode for creating new items from text input
|
|
66
|
+
* - Handles initial values that aren't in the default options
|
|
67
|
+
* - Deduplicates options based on item keys
|
|
68
|
+
*
|
|
69
|
+
* @template TValue - The type of the option values
|
|
70
|
+
* @template Multiple - Boolean flag indicating if multiple selections are allowed
|
|
71
|
+
* @template DisableClearable - Boolean flag indicating if clearing the selection is disabled
|
|
72
|
+
* @template FreeSolo - Boolean flag indicating if free text input is allowed
|
|
73
|
+
* @template ChipComponent - The component type used for rendering chips in multiple selection mode
|
|
74
|
+
* @template TFieldValues - The type of the form values
|
|
75
|
+
* @template TName - The type of the field name
|
|
76
|
+
*
|
|
77
|
+
* @returns A React component for selecting object values
|
|
78
|
+
*/
|
|
79
|
+
export declare const ObjectDisplayElement: <TValue, Multiple extends boolean | undefined, DisableClearable extends boolean | undefined, FreeSolo extends boolean | undefined, ChipComponent extends ElementType = ChipTypeMap["defaultComponent"], TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>>({ options, autocompleteProps, getItemKey, getItemLabel, getChipProps, stringToNewItem, name, freeSolo, control, ...props }: DisplayObjectCompleteProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName>) => import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createElement as _createElement } from "react";
|
|
3
|
+
import { useMemo, useState } from "react";
|
|
4
|
+
import { Checkbox, Chip, Typography } from "@mui/material";
|
|
5
|
+
import { AutocompleteElementDisplay, } from "./AutocompleteElementDisplay";
|
|
6
|
+
import { getAutocompleteRenderValue } from "../utils";
|
|
7
|
+
import { useController } from "react-hook-form-mui";
|
|
8
|
+
import { useOnMount } from "../hooks";
|
|
9
|
+
import lodash from "lodash";
|
|
10
|
+
const { omit } = lodash;
|
|
11
|
+
/**
|
|
12
|
+
* A form component that displays a searchable dropdown for selecting object values.
|
|
13
|
+
* Extends AutocompleteDisplayElement with object-specific functionality.
|
|
14
|
+
*
|
|
15
|
+
* Features:
|
|
16
|
+
* - Works with complex object values instead of just primitive types
|
|
17
|
+
* - Supports both single and multiple selection modes
|
|
18
|
+
* - Supports free-solo mode for creating new items from text input
|
|
19
|
+
* - Handles initial values that aren't in the default options
|
|
20
|
+
* - Deduplicates options based on item keys
|
|
21
|
+
*
|
|
22
|
+
* @template TValue - The type of the option values
|
|
23
|
+
* @template Multiple - Boolean flag indicating if multiple selections are allowed
|
|
24
|
+
* @template DisableClearable - Boolean flag indicating if clearing the selection is disabled
|
|
25
|
+
* @template FreeSolo - Boolean flag indicating if free text input is allowed
|
|
26
|
+
* @template ChipComponent - The component type used for rendering chips in multiple selection mode
|
|
27
|
+
* @template TFieldValues - The type of the form values
|
|
28
|
+
* @template TName - The type of the field name
|
|
29
|
+
*
|
|
30
|
+
* @returns A React component for selecting object values
|
|
31
|
+
*/
|
|
32
|
+
export const ObjectDisplayElement = ({ options, autocompleteProps, getItemKey, getItemLabel, getChipProps, stringToNewItem, name, freeSolo, control, ...props }) => {
|
|
33
|
+
/**
|
|
34
|
+
* Access to the form field controller
|
|
35
|
+
*/
|
|
36
|
+
const { field } = useController({ name, control });
|
|
37
|
+
/**
|
|
38
|
+
* State for the current text input in free-solo mode
|
|
39
|
+
*/
|
|
40
|
+
const [freeSoloValue, setFreeSoloValue] = useState("");
|
|
41
|
+
/**
|
|
42
|
+
* State for storing dynamically added options that aren't in the original options list
|
|
43
|
+
*/
|
|
44
|
+
const [newOptions, setNewOptions] = useState([]);
|
|
45
|
+
/**
|
|
46
|
+
* On component mount, handle initial field values that aren't in the options
|
|
47
|
+
* This is important for loading saved data that might reference items not in the current options
|
|
48
|
+
*/
|
|
49
|
+
useOnMount(() => {
|
|
50
|
+
if (!freeSolo || !field.value)
|
|
51
|
+
return;
|
|
52
|
+
// Handle both single and multiple selection modes
|
|
53
|
+
const fieldValues = Array.isArray(field.value) ? field.value : [field.value];
|
|
54
|
+
// Filter out values that are already in options
|
|
55
|
+
const newFieldOptions = fieldValues.filter((value) => {
|
|
56
|
+
// Skip string values as they're handled differently
|
|
57
|
+
if (typeof value === "string")
|
|
58
|
+
return false;
|
|
59
|
+
// Check if this value exists in options
|
|
60
|
+
return !options.some((option) => getItemKey(option) === getItemKey(value));
|
|
61
|
+
});
|
|
62
|
+
// Add new values to newOptions if any were found
|
|
63
|
+
if (newFieldOptions.length > 0)
|
|
64
|
+
setNewOptions(newFieldOptions);
|
|
65
|
+
});
|
|
66
|
+
/**
|
|
67
|
+
* Creates a new item from the current free-solo text input
|
|
68
|
+
* Returns undefined if:
|
|
69
|
+
* - Free-solo mode is disabled
|
|
70
|
+
* - No stringToNewItem converter is provided
|
|
71
|
+
* - Input is empty
|
|
72
|
+
* - An item with the same key already exists in options or newOptions
|
|
73
|
+
*
|
|
74
|
+
* @returns The new item created from the free-solo input, or undefined
|
|
75
|
+
*/
|
|
76
|
+
const freeSoloItem = useMemo(() => {
|
|
77
|
+
if (!freeSolo || !stringToNewItem || !freeSoloValue.length)
|
|
78
|
+
return undefined;
|
|
79
|
+
const item = stringToNewItem(freeSoloValue);
|
|
80
|
+
const itemKey = getItemKey(item);
|
|
81
|
+
if (options.some((option) => getItemKey(option) === itemKey))
|
|
82
|
+
return undefined;
|
|
83
|
+
if (newOptions.some((option) => getItemKey(option) === itemKey))
|
|
84
|
+
return undefined;
|
|
85
|
+
return item;
|
|
86
|
+
}, [stringToNewItem, freeSoloValue, newOptions, freeSolo, options, getItemKey]);
|
|
87
|
+
/**
|
|
88
|
+
* Creates a combined and deduplicated list of all available options
|
|
89
|
+
* Includes:
|
|
90
|
+
* - Original options from props
|
|
91
|
+
* - Dynamically added options from newOptions
|
|
92
|
+
* - Current free-solo item if it exists
|
|
93
|
+
*
|
|
94
|
+
* @returns Array of all available options with duplicates removed
|
|
95
|
+
*/
|
|
96
|
+
const allOptions = useMemo(() => {
|
|
97
|
+
if (!freeSolo)
|
|
98
|
+
return options;
|
|
99
|
+
// Combine all options and deduplicate by key
|
|
100
|
+
const combinedOptions = [...options, ...newOptions];
|
|
101
|
+
if (freeSoloItem)
|
|
102
|
+
combinedOptions.push(freeSoloItem);
|
|
103
|
+
// Deduplicate using getItemKey
|
|
104
|
+
const uniqueKeys = new Set();
|
|
105
|
+
return combinedOptions.filter((option) => {
|
|
106
|
+
const key = getItemKey(option);
|
|
107
|
+
if (uniqueKeys.has(key))
|
|
108
|
+
return false;
|
|
109
|
+
uniqueKeys.add(key);
|
|
110
|
+
return true;
|
|
111
|
+
});
|
|
112
|
+
}, [options, newOptions, freeSolo, freeSoloItem, getItemKey]);
|
|
113
|
+
// console.log({ allOptions });
|
|
114
|
+
return (_jsx(AutocompleteElementDisplay, { name: name, control: control, options: allOptions, ...props, autocompleteProps: {
|
|
115
|
+
/**
|
|
116
|
+
* Determines if two options should be considered equal
|
|
117
|
+
* Uses the getItemKey function to compare option values
|
|
118
|
+
*/
|
|
119
|
+
isOptionEqualToValue: (o, v) => getItemKey(o) === getItemKey(v),
|
|
120
|
+
/**
|
|
121
|
+
* Filters options based on the input value
|
|
122
|
+
* Checks if the option key contains the input value (case-insensitive)
|
|
123
|
+
*/
|
|
124
|
+
filterOptions: (options, { inputValue }) => options.filter((option) => getItemKey(option).toLowerCase().includes(inputValue.toLowerCase())),
|
|
125
|
+
freeSolo, // Allowed to enter own string value
|
|
126
|
+
autoComplete: true,
|
|
127
|
+
autoHighlight: true, // The first option is highlighted by default
|
|
128
|
+
openOnFocus: true, // Opens the menu when tabbed into
|
|
129
|
+
/**
|
|
130
|
+
* Custom rendering for each option in the dropdown list
|
|
131
|
+
* Displays a checkbox for multiple selection if showCheckbox is true
|
|
132
|
+
* Uses getItemLabel to render the option label
|
|
133
|
+
*/
|
|
134
|
+
renderOption: (liProps, option, { selected }) => (_createElement("li", { ...liProps, key: `${name}-option-${getItemKey(option)}` },
|
|
135
|
+
props?.showCheckbox && _jsx(Checkbox, { sx: { marginRight: 1 }, checked: selected }),
|
|
136
|
+
typeof option === "string" ? option : getItemLabel(option))),
|
|
137
|
+
/**
|
|
138
|
+
* Handles changes to the selected value(s)
|
|
139
|
+
* In free-solo mode, adds the new item to newOptions when selected
|
|
140
|
+
* Delegates to the original onChange handler if provided
|
|
141
|
+
*/
|
|
142
|
+
onChange: (event, value, reason, details) => {
|
|
143
|
+
if (freeSolo && freeSoloItem) {
|
|
144
|
+
if (stringToNewItem == undefined) {
|
|
145
|
+
throw new Error("Must implement stringToNewItem with freeSolo!");
|
|
146
|
+
}
|
|
147
|
+
setNewOptions((prev) => [...prev, freeSoloItem]);
|
|
148
|
+
setFreeSoloValue("");
|
|
149
|
+
}
|
|
150
|
+
autocompleteProps?.onChange?.(event, value, reason, details);
|
|
151
|
+
},
|
|
152
|
+
/**
|
|
153
|
+
* Handles changes to the input text
|
|
154
|
+
* Updates freeSoloValue state with the current input
|
|
155
|
+
* Delegates to the original onInputChange handler if provided
|
|
156
|
+
*/
|
|
157
|
+
onInputChange: (event, value, reason) => {
|
|
158
|
+
// event.preventDefault();
|
|
159
|
+
setFreeSoloValue(value);
|
|
160
|
+
// Call the original onInputChange if it exists
|
|
161
|
+
autocompleteProps?.onInputChange?.(event, value, reason);
|
|
162
|
+
},
|
|
163
|
+
/**
|
|
164
|
+
* Custom rendering for the selected value(s)
|
|
165
|
+
* For multiple selection, renders a Chip for each selected value
|
|
166
|
+
* For single selection, renders the value as text
|
|
167
|
+
* Uses getItemLabel to render the value labels
|
|
168
|
+
*/
|
|
169
|
+
renderValue: (value, getItemProps, ownerState) => {
|
|
170
|
+
const typedValue = getAutocompleteRenderValue(value, ownerState);
|
|
171
|
+
if (Array.isArray(typedValue)) {
|
|
172
|
+
return typedValue.map((v, index) => {
|
|
173
|
+
// @ts-expect-error a key is returned, and the linter doesn't pick this up
|
|
174
|
+
const { key, ...chipProps } = getItemProps({ index });
|
|
175
|
+
// const { key, ...rawChipProps } = getItemProps({ index });
|
|
176
|
+
// const chipProps = omit(rawChipProps, "onDelete");
|
|
177
|
+
const label = typeof v === "string" ? v : getItemLabel(v);
|
|
178
|
+
// Get additional chip props based on the value if the function is provided
|
|
179
|
+
const valueSpecificProps = typeof v !== "string" && getChipProps ? getChipProps({ value: v, index }) : {};
|
|
180
|
+
return (_jsx(Chip, { label: label, ...valueSpecificProps, ...chipProps }, `${name}-chip-${key}`));
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
// @ts-expect-error a key is returned, and the linter doesn't pick this up
|
|
184
|
+
// const { key, ...rawChipProps } = getItemProps({ index: 0 });
|
|
185
|
+
const { key, ...rawChipProps } = getItemProps({ index: 0 });
|
|
186
|
+
const itemProps = omit(rawChipProps, "onDelete");
|
|
187
|
+
return (_jsx(Typography, { component: "span", color: "text.primary", ...(props?.viewOnly ? omit(itemProps, "disabled") : itemProps), children: (typeof typedValue === "string") ? typedValue : getItemLabel(typedValue) }, `${name}-value-${key}`));
|
|
188
|
+
},
|
|
189
|
+
...autocompleteProps,
|
|
190
|
+
} }));
|
|
191
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { JSX } from "react";
|
|
2
|
+
import type { FormControlProps } from "@mui/material";
|
|
3
|
+
import { type RegisterOptions, type FieldValues, type Path } from "react-hook-form";
|
|
4
|
+
/**
|
|
5
|
+
* Props for the RHFHiddenInput component
|
|
6
|
+
*/
|
|
7
|
+
export interface ValidationElementProps<TFieldValues extends FieldValues> {
|
|
8
|
+
/**
|
|
9
|
+
* Name of the field in the form
|
|
10
|
+
*/
|
|
11
|
+
name: Path<TFieldValues>;
|
|
12
|
+
/**
|
|
13
|
+
* Optional validation rules
|
|
14
|
+
*/
|
|
15
|
+
rules: RegisterOptions<TFieldValues>;
|
|
16
|
+
/**
|
|
17
|
+
* Props to pass to the FormControl component
|
|
18
|
+
*/
|
|
19
|
+
formControlProps?: Omit<FormControlProps, "error">;
|
|
20
|
+
}
|
|
21
|
+
export declare const ValidationElement: <TFieldValues extends FieldValues = FieldValues>({ name, rules, formControlProps, }: ValidationElementProps<TFieldValues>) => JSX.Element;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { FormControl, FormHelperText } from "@mui/material";
|
|
3
|
+
import { useFormContext } from "react-hook-form";
|
|
4
|
+
import { useFormError } from "../hooks";
|
|
5
|
+
export const ValidationElement = ({ name, rules, formControlProps = {}, }) => {
|
|
6
|
+
const { register, formState: { errors }, } = useFormContext();
|
|
7
|
+
const { error, helperText } = useFormError(errors, name);
|
|
8
|
+
return (_jsxs(FormControl, { error: error, ...formControlProps, children: [_jsx("input", { type: "hidden", ...register(name, rules) }), error && _jsx(FormHelperText, { children: helperText })] }));
|
|
9
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { FieldErrors, FieldValues } from 'react-hook-form';
|
|
2
|
+
/**
|
|
3
|
+
* A hook to get the error message for a field from react-hook-form
|
|
4
|
+
* @param errors The errors object from react-hook-form
|
|
5
|
+
* @param name The name of the field (supports dot notation for nested fields)
|
|
6
|
+
* @returns An object with error and helperText properties
|
|
7
|
+
*/
|
|
8
|
+
export declare function useFormError<T extends FieldValues>(errors: FieldErrors<T>, name: string): {
|
|
9
|
+
error: boolean;
|
|
10
|
+
helperText: string;
|
|
11
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import lodash from 'lodash';
|
|
2
|
+
const { get } = lodash;
|
|
3
|
+
/**
|
|
4
|
+
* A hook to get the error message for a field from react-hook-form
|
|
5
|
+
* @param errors The errors object from react-hook-form
|
|
6
|
+
* @param name The name of the field (supports dot notation for nested fields)
|
|
7
|
+
* @returns An object with error and helperText properties
|
|
8
|
+
*/
|
|
9
|
+
export function useFormError(errors, name) {
|
|
10
|
+
// Get the error for the field, supporting nested paths with dot notation
|
|
11
|
+
const fieldError = get(errors, name);
|
|
12
|
+
// Return error state and helper text
|
|
13
|
+
return {
|
|
14
|
+
error: !!fieldError,
|
|
15
|
+
helperText: fieldError?.message || '',
|
|
16
|
+
};
|
|
17
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// src/hooks/useOnMount.ts
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
/**
|
|
4
|
+
* Runs a provided callback function once on the first component mount.
|
|
5
|
+
*
|
|
6
|
+
* @param callback - The function to run on first mount.
|
|
7
|
+
*/
|
|
8
|
+
export function useOnMount(callback) {
|
|
9
|
+
const hasMounted = useRef(false);
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
if (!hasMounted.current) {
|
|
12
|
+
callback();
|
|
13
|
+
hasMounted.current = true;
|
|
14
|
+
}
|
|
15
|
+
// Cleanup to prevent callback logic from running during cleanup
|
|
16
|
+
return () => {
|
|
17
|
+
hasMounted.current = true;
|
|
18
|
+
};
|
|
19
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
20
|
+
}, []);
|
|
21
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),$=require("react-hook-form-mui"),l=require("react"),M=require("lodash"),x=require("@mui/material"),G=require("react-hook-form"),{merge:q}=M,D=({viewOnly:e,disableUnderline:n,textFieldProps:t,autocompleteProps:a,...f})=>{const i=l.useMemo(()=>q({readOnly:e,disableClearable:e,disabled:e,slotProps:{input:{disableUnderline:n},chip:{disabled:!1}}},a,e?{sx:{".MuiAutocomplete-endAdornment":{display:"none"},".MuiAutocomplete-tag":{opacity:"1 !important"}}}:{}),[a,e,n]),c=l.useMemo(()=>q(e?{variant:"standard"}:{},t),[e,t]);return p.jsx($.AutocompleteElement,{...f,autocompleteProps:i,textFieldProps:c})};function J(e,n){return n.multiple,n?.freeSolo,e}const{get:L}=M;function P(e,n){const t=L(e,n);return{error:!!t,helperText:t?.message||""}}function S(e){const n=l.useRef(!1);l.useEffect(()=>(n.current||(e(),n.current=!0),()=>{n.current=!0}),[])}const{omit:g}=M,Q=({options:e,autocompleteProps:n,getItemKey:t,getItemLabel:a,getChipProps:f,stringToNewItem:i,name:c,freeSolo:d,control:F,...C})=>{const{field:j}=$.useController({name:c,control:F}),[E,b]=l.useState(""),[y,k]=l.useState([]);S(()=>{if(!d||!j.value)return;const r=(Array.isArray(j.value)?j.value:[j.value]).filter(s=>typeof s=="string"?!1:!e.some(u=>t(u)===t(s)));r.length>0&&k(r)});const h=l.useMemo(()=>{if(!d||!i||!E.length)return;const o=i(E),r=t(o);if(!e.some(s=>t(s)===r)&&!y.some(s=>t(s)===r))return o},[i,E,y,d,e,t]),H=l.useMemo(()=>{if(!d)return e;const o=[...e,...y];h&&o.push(h);const r=new Set;return o.filter(s=>{const u=t(s);return r.has(u)?!1:(r.add(u),!0)})},[e,y,d,h,t]);return p.jsx(D,{name:c,control:F,options:H,...C,autocompleteProps:{isOptionEqualToValue:(o,r)=>t(o)===t(r),filterOptions:(o,{inputValue:r})=>o.filter(s=>t(s).toLowerCase().includes(r.toLowerCase())),freeSolo:d,autoComplete:!0,autoHighlight:!0,openOnFocus:!0,renderOption:(o,r,{selected:s})=>l.createElement("li",{...o,key:`${c}-option-${t(r)}`},C?.showCheckbox&&p.jsx(x.Checkbox,{sx:{marginRight:1},checked:s}),typeof r=="string"?r:a(r)),onChange:(o,r,s,u)=>{if(d&&h){if(i==null)throw new Error("Must implement stringToNewItem with freeSolo!");k(A=>[...A,h]),b("")}n?.onChange?.(o,r,s,u)},onInputChange:(o,r,s)=>{b(r),n?.onInputChange?.(o,r,s)},renderValue:(o,r,s)=>{const u=J(o,s);if(Array.isArray(u))return u.map((m,V)=>{const{key:T,...w}=r({index:V}),z=typeof m=="string"?m:a(m),B=typeof m!="string"&&f?f({value:m,index:V}):{};return p.jsx(x.Chip,{label:z,...B,...w},`${c}-chip-${T}`)});const{key:A,...R}=r({index:0}),O=g(R,"onDelete");return p.jsx(x.Typography,{component:"span",color:"text.primary",...C?.viewOnly?g(O,"disabled"):O,children:typeof u=="string"?u:a(u)},`${c}-value-${A}`)},...n}})},W=({name:e,rules:n,formControlProps:t={}})=>{const{register:a,formState:{errors:f}}=G.useFormContext(),{error:i,helperText:c}=P(f,e);return p.jsxs(x.FormControl,{error:i,...t,children:[p.jsx("input",{type:"hidden",...a(e,n)}),i&&p.jsx(x.FormHelperText,{children:c})]})};exports.AutocompleteElementDisplay=D;exports.ObjectDisplayElement=Q;exports.ValidationElement=W;exports.useFormError=P;exports.useOnMount=S;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/components/AutocompleteElementDisplay.tsx","../src/utils.ts","../src/hooks/useFormError.ts","../src/hooks/useOnMount.ts","../src/components/ObjectDisplayElement.tsx","../src/components/ValidationElement.tsx"],"sourcesContent":["import { AutocompleteElement, type AutocompleteElementProps } from \"react-hook-form-mui\";\r\nimport { type ChipTypeMap } from \"@mui/material\";\r\nimport type { FieldPath, FieldValues } from \"react-hook-form\";\r\nimport { type ElementType, useMemo } from \"react\";\r\nimport lodash from \"lodash\";\r\nconst { merge } = lodash;\r\n\r\nexport type AutocompleteElementDisplayProps<\r\n TValue,\r\n Multiple extends boolean | undefined,\r\n DisableClearable extends boolean | undefined,\r\n FreeSolo extends boolean | undefined,\r\n ChipComponent extends ElementType = ChipTypeMap[\"defaultComponent\"],\r\n TFieldValues extends FieldValues = FieldValues,\r\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\r\n> = AutocompleteElementProps<\r\n TValue,\r\n Multiple,\r\n DisableClearable,\r\n FreeSolo,\r\n ChipComponent,\r\n TFieldValues,\r\n TName\r\n> &\r\n Viewable;\r\n\r\nexport const AutocompleteElementDisplay = <\r\n TValue,\r\n Multiple extends boolean | undefined,\r\n DisableClearable extends boolean | undefined,\r\n FreeSolo extends boolean | undefined,\r\n ChipComponent extends ElementType = ChipTypeMap[\"defaultComponent\"],\r\n TFieldValues extends FieldValues = FieldValues,\r\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\r\n>({\r\n viewOnly,\r\n disableUnderline,\r\n textFieldProps,\r\n autocompleteProps,\r\n ...props\r\n}: AutocompleteElementDisplayProps<\r\n TValue,\r\n Multiple,\r\n DisableClearable,\r\n FreeSolo,\r\n ChipComponent,\r\n TFieldValues,\r\n TName\r\n>) => {\r\n const autocompleteAdjustedProps: AutocompleteElementDisplayProps<\r\n TValue,\r\n Multiple,\r\n DisableClearable,\r\n FreeSolo,\r\n ChipComponent,\r\n TFieldValues,\r\n TName\r\n >['autocompleteProps'] = useMemo(\r\n () =>\r\n merge(\r\n {\r\n readOnly: viewOnly,\r\n disableClearable: viewOnly,\r\n disabled: viewOnly,\r\n slotProps: {\r\n input: { disableUnderline },\r\n chip: {\r\n disabled: false,\r\n },\r\n },\r\n },\r\n autocompleteProps,\r\n viewOnly\r\n ? {\r\n sx: {\r\n \".MuiAutocomplete-endAdornment\": {\r\n display: \"none\",\r\n },\r\n \".MuiAutocomplete-tag\": {\r\n opacity: \"1 !important\"\r\n },\r\n },\r\n }\r\n : {},\r\n ),\r\n [autocompleteProps, viewOnly, disableUnderline],\r\n );\r\n\r\n const textFieldAdjustedProps = useMemo(\r\n () => merge(viewOnly ? { variant: \"standard\" } : {}, textFieldProps),\r\n [viewOnly, textFieldProps],\r\n );\r\n\r\n return (\r\n <AutocompleteElement\r\n {...props}\r\n autocompleteProps={autocompleteAdjustedProps}\r\n textFieldProps={textFieldAdjustedProps}\r\n />\r\n );\r\n};\r\n\r\ntype Viewable = {\r\n viewOnly?: boolean;\r\n disableUnderline?: boolean;\r\n};\r\n","import type { AutocompleteOwnerState, AutocompleteRenderValue, ChipTypeMap } from \"@mui/material\";\r\nimport type { ElementType } from \"react\";\r\n\r\nexport function getAutocompleteRenderValue<\r\n TValue,\r\n Multiple extends boolean | undefined,\r\n DisableClearable extends boolean | undefined,\r\n FreeSolo extends boolean | undefined,\r\n ChipComponent extends ElementType = ChipTypeMap['defaultComponent']\r\n>(value: AutocompleteRenderValue<TValue, Multiple, FreeSolo>, ownerState: AutocompleteOwnerState<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent>) {\r\n if (ownerState.multiple) {\r\n if(ownerState?.freeSolo) return value as Array<TValue | string>;\r\n return value as TValue[];\r\n } else if (ownerState?.freeSolo) {\r\n return value as NonNullable<TValue | string>;\r\n }\r\n return value as NonNullable<TValue>;\r\n}","import { FieldError, FieldErrors, FieldValues } from 'react-hook-form';\r\nimport lodash from 'lodash';\r\nconst { get } = lodash;\r\n\r\n/**\r\n * A hook to get the error message for a field from react-hook-form\r\n * @param errors The errors object from react-hook-form\r\n * @param name The name of the field (supports dot notation for nested fields)\r\n * @returns An object with error and helperText properties\r\n */\r\nexport function useFormError<T extends FieldValues>(\r\n errors: FieldErrors<T>,\r\n name: string\r\n): { error: boolean; helperText: string } {\r\n // Get the error for the field, supporting nested paths with dot notation\r\n const fieldError = get(errors, name) as FieldError | undefined;\r\n\r\n // Return error state and helper text\r\n return {\r\n error: !!fieldError,\r\n helperText: fieldError?.message || '',\r\n };\r\n}\r\n","// src/hooks/useOnMount.ts\r\nimport { useEffect, useRef } from \"react\";\r\n\r\n/**\r\n * Runs a provided callback function once on the first component mount.\r\n *\r\n * @param callback - The function to run on first mount.\r\n */\r\nexport function useOnMount(callback: () => void): void {\r\n const hasMounted = useRef(false);\r\n\r\n useEffect(() => {\r\n if (!hasMounted.current) {\r\n callback();\r\n hasMounted.current = true;\r\n }\r\n\r\n // Cleanup to prevent callback logic from running during cleanup\r\n return () => {\r\n hasMounted.current = true;\r\n };\r\n \r\n // eslint-disable-next-line react-hooks/exhaustive-deps\r\n }, []);\r\n}\r\n\r\n","import { type ElementType, ReactNode, useMemo, useState } from \"react\";\nimport { Checkbox, Chip, Typography, type ChipProps, type ChipTypeMap } from \"@mui/material\";\nimport type { FieldPath, FieldValues } from \"react-hook-form\";\nimport {\n AutocompleteElementDisplay,\n type AutocompleteElementDisplayProps,\n} from \"./AutocompleteElementDisplay\";\nimport { getAutocompleteRenderValue } from \"../utils\";\nimport { useController } from \"react-hook-form-mui\";\nimport { useOnMount } from \"../hooks\";\nimport lodash from \"lodash\";\nconst { omit } = lodash;\n\n/**\n * Extends DisplayAutocompleteProps with additional properties for handling object values.\n *\n * @template TValue - The type of the option values\n * @template Multiple - Boolean flag indicating if multiple selections are allowed\n * @template DisableClearable - Boolean flag indicating if clearing the selection is disabled\n * @template FreeSolo - Boolean flag indicating if free text input is allowed\n * @template ChipComponent - The component type used for rendering chips in multiple selection mode\n * @template TFieldValues - The type of the form values\n * @template TName - The type of the field name\n */\nexport type DisplayObjectCompleteProps<\n TValue,\n Multiple extends boolean | undefined,\n DisableClearable extends boolean | undefined,\n FreeSolo extends boolean | undefined,\n ChipComponent extends ElementType = ChipTypeMap[\"defaultComponent\"],\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n> = AutocompleteElementDisplayProps<\n TValue,\n Multiple,\n DisableClearable,\n FreeSolo,\n ChipComponent,\n TFieldValues,\n TName\n> & {\n /**\n * Function to extract a unique key from an option value.\n * Used for option comparison and deduplication.\n *\n * @param value - The option value or null\n * @returns A unique string key for the value\n */\n getItemKey: (value: TValue | null) => string;\n\n /**\n * Function to generate a display label for an option value.\n * Can return any ReactNode for custom rendering.\n *\n * @param value - The option value or null\n * @returns A ReactNode to display as the option label\n */\n getItemLabel: (value: TValue | null) => ReactNode;\n\n /**\n * Function to convert a free text input string to a TValue object.\n * Required when freeSolo is true to create new items from text input.\n *\n * @param value - The string value entered by the user\n * @returns A new TValue object created from the string\n */\n stringToNewItem?: (value: string) => TValue;\n\n /**\n * Whether the input allows free text entry.\n * When true, users can enter values that are not in the options.\n */\n freeSolo?: FreeSolo;\n\n /**\n * Optional function that returns additional chip props based on the value.\n * This allows for customizing chip appearance and behavior based on the value it represents.\n *\n * @param value - The option value being rendered as a chip\n * @returns Additional props to apply to the Chip component\n */\n getChipProps?: (props: { value: TValue; index: number }) => Partial<ChipProps> | undefined;\n};\n\n/**\n * A form component that displays a searchable dropdown for selecting object values.\n * Extends AutocompleteDisplayElement with object-specific functionality.\n *\n * Features:\n * - Works with complex object values instead of just primitive types\n * - Supports both single and multiple selection modes\n * - Supports free-solo mode for creating new items from text input\n * - Handles initial values that aren't in the default options\n * - Deduplicates options based on item keys\n *\n * @template TValue - The type of the option values\n * @template Multiple - Boolean flag indicating if multiple selections are allowed\n * @template DisableClearable - Boolean flag indicating if clearing the selection is disabled\n * @template FreeSolo - Boolean flag indicating if free text input is allowed\n * @template ChipComponent - The component type used for rendering chips in multiple selection mode\n * @template TFieldValues - The type of the form values\n * @template TName - The type of the field name\n *\n * @returns A React component for selecting object values\n */\nexport const ObjectDisplayElement = <\n TValue,\n Multiple extends boolean | undefined,\n DisableClearable extends boolean | undefined,\n FreeSolo extends boolean | undefined,\n ChipComponent extends ElementType = ChipTypeMap[\"defaultComponent\"],\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n>({\n options,\n autocompleteProps,\n getItemKey,\n getItemLabel,\n getChipProps,\n stringToNewItem,\n name,\n freeSolo,\n control,\n ...props\n}: DisplayObjectCompleteProps<\n TValue,\n Multiple,\n DisableClearable,\n FreeSolo,\n ChipComponent,\n TFieldValues,\n TName\n>) => {\n /**\n * Access to the form field controller\n */\n const { field } = useController({ name, control });\n\n /**\n * State for the current text input in free-solo mode\n */\n const [freeSoloValue, setFreeSoloValue] = useState(\"\");\n\n /**\n * State for storing dynamically added options that aren't in the original options list\n */\n const [newOptions, setNewOptions] = useState<TValue[]>([]);\n\n /**\n * On component mount, handle initial field values that aren't in the options\n * This is important for loading saved data that might reference items not in the current options\n */\n useOnMount(() => {\n if (!freeSolo || !field.value) return;\n\n // Handle both single and multiple selection modes\n const fieldValues: TValue[] = Array.isArray(field.value) ? field.value : [field.value];\n\n // Filter out values that are already in options\n const newFieldOptions = fieldValues.filter((value) => {\n // Skip string values as they're handled differently\n if (typeof value === \"string\") return false;\n\n // Check if this value exists in options\n return !options.some((option) => getItemKey(option) === getItemKey(value));\n });\n\n // Add new values to newOptions if any were found\n if (newFieldOptions.length > 0) setNewOptions(newFieldOptions);\n });\n\n /**\n * Creates a new item from the current free-solo text input\n * Returns undefined if:\n * - Free-solo mode is disabled\n * - No stringToNewItem converter is provided\n * - Input is empty\n * - An item with the same key already exists in options or newOptions\n *\n * @returns The new item created from the free-solo input, or undefined\n */\n const freeSoloItem = useMemo(() => {\n if (!freeSolo || !stringToNewItem || !freeSoloValue.length) return undefined;\n const item = stringToNewItem(freeSoloValue);\n const itemKey = getItemKey(item);\n if (options.some((option) => getItemKey(option) === itemKey)) return undefined;\n if (newOptions.some((option) => getItemKey(option) === itemKey)) return undefined;\n return item;\n }, [stringToNewItem, freeSoloValue, newOptions, freeSolo, options, getItemKey]);\n\n /**\n * Creates a combined and deduplicated list of all available options\n * Includes:\n * - Original options from props\n * - Dynamically added options from newOptions\n * - Current free-solo item if it exists\n *\n * @returns Array of all available options with duplicates removed\n */\n const allOptions = useMemo(() => {\n if (!freeSolo) return options;\n\n // Combine all options and deduplicate by key\n const combinedOptions = [...options, ...newOptions];\n if (freeSoloItem) combinedOptions.push(freeSoloItem);\n\n // Deduplicate using getItemKey\n const uniqueKeys = new Set();\n return combinedOptions.filter((option) => {\n const key = getItemKey(option);\n if (uniqueKeys.has(key)) return false;\n uniqueKeys.add(key);\n return true;\n });\n }, [options, newOptions, freeSolo, freeSoloItem, getItemKey]);\n\n // console.log({ allOptions });\n\n return (\n <AutocompleteElementDisplay\n name={name}\n control={control}\n options={allOptions}\n {...props}\n autocompleteProps={{\n /**\n * Determines if two options should be considered equal\n * Uses the getItemKey function to compare option values\n */\n isOptionEqualToValue: (o, v) => getItemKey(o) === getItemKey(v),\n\n /**\n * Filters options based on the input value\n * Checks if the option key contains the input value (case-insensitive)\n */\n filterOptions: (options, { inputValue }) =>\n options.filter((option) =>\n getItemKey(option).toLowerCase().includes(inputValue.toLowerCase()),\n ),\n freeSolo, // Allowed to enter own string value\n autoComplete: true,\n autoHighlight: true, // The first option is highlighted by default\n openOnFocus: true, // Opens the menu when tabbed into\n\n /**\n * Custom rendering for each option in the dropdown list\n * Displays a checkbox for multiple selection if showCheckbox is true\n * Uses getItemLabel to render the option label\n */\n renderOption: (liProps, option, { selected }) => (\n <li {...liProps} key={`${name}-option-${getItemKey(option)}`}>\n {props?.showCheckbox && <Checkbox sx={{ marginRight: 1 }} checked={selected} />}\n {typeof option === \"string\" ? option : getItemLabel(option)}\n </li>\n ),\n\n /**\n * Handles changes to the selected value(s)\n * In free-solo mode, adds the new item to newOptions when selected\n * Delegates to the original onChange handler if provided\n */\n onChange: (event, value, reason, details) => {\n if (freeSolo && freeSoloItem) {\n if (stringToNewItem == undefined) {\n throw new Error(\"Must implement stringToNewItem with freeSolo!\");\n }\n setNewOptions((prev) => [...prev, freeSoloItem]);\n setFreeSoloValue(\"\");\n }\n\n autocompleteProps?.onChange?.(event, value, reason, details);\n },\n\n /**\n * Handles changes to the input text\n * Updates freeSoloValue state with the current input\n * Delegates to the original onInputChange handler if provided\n */\n onInputChange: (event, value, reason) => {\n // event.preventDefault();\n setFreeSoloValue(value);\n\n // Call the original onInputChange if it exists\n autocompleteProps?.onInputChange?.(event, value, reason);\n },\n\n /**\n * Custom rendering for the selected value(s)\n * For multiple selection, renders a Chip for each selected value\n * For single selection, renders the value as text\n * Uses getItemLabel to render the value labels\n */\n renderValue: (value, getItemProps, ownerState) => {\n const typedValue = getAutocompleteRenderValue(value, ownerState);\n\n if (Array.isArray(typedValue)) {\n return typedValue.map((v, index) => {\n // @ts-expect-error a key is returned, and the linter doesn't pick this up\n const { key, ...chipProps } = getItemProps({ index });\n // const { key, ...rawChipProps } = getItemProps({ index });\n // const chipProps = omit(rawChipProps, \"onDelete\");\n\n const label = typeof v === \"string\" ? v : getItemLabel(v);\n\n // Get additional chip props based on the value if the function is provided\n const valueSpecificProps =\n typeof v !== \"string\" && getChipProps ? getChipProps({ value: v, index }) : {};\n return (\n <Chip\n key={`${name}-chip-${key}`}\n label={label}\n {...valueSpecificProps}\n {...chipProps}\n />\n );\n });\n }\n\n // @ts-expect-error a key is returned, and the linter doesn't pick this up\n // const { key, ...rawChipProps } = getItemProps({ index: 0 });\n const { key, ...rawChipProps } = getItemProps({ index: 0 });\n const itemProps = omit(rawChipProps, \"onDelete\");\n return (\n <Typography\n component={\"span\"}\n key={`${name}-value-${key}`}\n color={\"text.primary\"}\n {...(props?.viewOnly ? omit(itemProps, \"disabled\") : itemProps)}\n >\n {(typeof typedValue === \"string\") ? typedValue : getItemLabel(typedValue as NonNullable<TValue>)}\n </Typography>\n );\n },\n ...autocompleteProps,\n }}\n />\n );\n};\n","import type { JSX } from \"react\";\r\nimport { FormControl, FormHelperText } from \"@mui/material\";\r\nimport type { FormControlProps } from \"@mui/material\";\r\nimport { useFormContext, type RegisterOptions, type FieldValues, type Path } from \"react-hook-form\";\r\nimport { useFormError } from \"../hooks\";\r\n\r\n/**\r\n * Props for the RHFHiddenInput component\r\n */\r\nexport interface ValidationElementProps<TFieldValues extends FieldValues> {\r\n /**\r\n * Name of the field in the form\r\n */\r\n name: Path<TFieldValues>;\r\n /**\r\n * Optional validation rules\r\n */\r\n rules: RegisterOptions<TFieldValues>;\r\n /**\r\n * Props to pass to the FormControl component\r\n */\r\n formControlProps?: Omit<FormControlProps, \"error\">;\r\n}\r\n\r\nexport const ValidationElement = <TFieldValues extends FieldValues = FieldValues>({\r\n name,\r\n rules,\r\n formControlProps = {},\r\n}: ValidationElementProps<TFieldValues>): JSX.Element => {\r\n const {\r\n register,\r\n formState: { errors },\r\n } = useFormContext<TFieldValues>();\r\n\r\n const { error, helperText } = useFormError(errors, name);\r\n\r\n return (\r\n <FormControl error={error} {...formControlProps}>\r\n <input type=\"hidden\" {...register(name, rules)} />\r\n {error && <FormHelperText>{helperText}</FormHelperText>}\r\n </FormControl>\r\n );\r\n};\r\n"],"names":["merge","lodash","AutocompleteElementDisplay","viewOnly","disableUnderline","textFieldProps","autocompleteProps","props","autocompleteAdjustedProps","useMemo","textFieldAdjustedProps","jsx","AutocompleteElement","getAutocompleteRenderValue","value","ownerState","get","useFormError","errors","name","fieldError","useOnMount","callback","hasMounted","useRef","useEffect","omit","ObjectDisplayElement","options","getItemKey","getItemLabel","getChipProps","stringToNewItem","freeSolo","control","field","useController","freeSoloValue","setFreeSoloValue","useState","newOptions","setNewOptions","newFieldOptions","option","freeSoloItem","item","itemKey","allOptions","combinedOptions","uniqueKeys","key","v","inputValue","liProps","selected","createElement","Checkbox","event","reason","details","prev","getItemProps","typedValue","index","chipProps","label","valueSpecificProps","Chip","rawChipProps","itemProps","Typography","ValidationElement","rules","formControlProps","register","useFormContext","error","helperText","jsxs","FormControl","FormHelperText"],"mappings":"qPAKM,CAAE,MAAAA,GAAUC,EAqBLC,EAA6B,CAQxC,CACA,SAAAC,EACA,iBAAAC,EACA,eAAAC,EACA,kBAAAC,EACA,GAAGC,CACL,IAQM,CACJ,MAAMC,EAQmBC,EAAAA,QACvB,IACET,EACE,CACE,SAAUG,EACV,iBAAkBA,EAClB,SAAUA,EACV,UAAW,CACT,MAAO,CAAE,iBAAAC,CAAA,EACT,KAAM,CACJ,SAAU,EAAA,CACZ,CACF,EAEFE,EACAH,EACI,CACE,GAAI,CACF,gCAAiC,CAC/B,QAAS,MAAA,EAEX,uBAAwB,CACtB,QAAS,cAAA,CACX,CACF,EAEF,CAAA,CAAC,EAET,CAACG,EAAmBH,EAAUC,CAAgB,CAAA,EAG1CM,EAAyBD,EAAAA,QAC7B,IAAMT,EAAMG,EAAW,CAAE,QAAS,UAAA,EAAe,CAAA,EAAIE,CAAc,EACnE,CAACF,EAAUE,CAAc,CAAA,EAG3B,OACEM,EAAAA,IAACC,EAAAA,oBAAA,CACE,GAAGL,EACJ,kBAAmBC,EACnB,eAAgBE,CAAA,CAAA,CAGtB,ECjGO,SAASG,EAMdC,EAA4DC,EAAiG,CAC7J,OAAIA,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