@chris-c-brine/rhf-mui-kit 0.2.0 → 0.4.0

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.
@@ -1 +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/ObjectElementDisplay.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 AutocompleteElementDisplayProps 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 ObjectElementDisplayProps<\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 AutocompleteElementDisplay 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 ObjectElementDisplay = <\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}: ObjectElementDisplayProps<\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\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 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","ObjectElementDisplay","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,EAAW,SACVA,GAAY,SAAiBD,CAMpC,CCfA,KAAM,CAAE,IAAAE,GAAQf,EAQT,SAASgB,EACdC,EACAC,EACwC,CAExC,MAAMC,EAAaJ,EAAIE,EAAQC,CAAI,EAGnC,MAAO,CACL,MAAO,CAAC,CAACC,EACT,WAAYA,GAAY,SAAW,EAAA,CAEvC,CCdO,SAASC,EAAWC,EAA4B,CACrD,MAAMC,EAAaC,EAAAA,OAAO,EAAK,EAE/BC,EAAAA,UAAU,KACHF,EAAW,UACdD,EA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AAO,EAClByD,iBAAA,EAEE,CAAE,MAAAC,EAAO,WAAAC,CAAA,EAAe5D,EAAaC,EAAQC,CAAI,EAEvD,OACE2D,EAAAA,KAACC,EAAAA,YAAA,CAAY,MAAAH,EAAe,GAAGH,EAC7B,SAAA,CAAA9D,MAAC,SAAM,KAAK,SAAU,GAAG+D,EAASvD,EAAMqD,CAAK,EAAG,EAC/CI,GAASjE,EAAAA,IAACqE,EAAAA,eAAA,CAAgB,SAAAH,CAAA,CAAW,CAAA,EACxC,CAEJ"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/utils.ts","../src/components/AutocompleteElementDisplay.tsx","../src/components/ObjectElementDisplay.tsx","../src/components/TextElementDisplay.tsx","../src/hooks/useFormError.ts","../src/hooks/useOnMount.ts","../src/components/ValidationElement.tsx"],"sourcesContent":["import type {\r\n AutocompleteOwnerState,\r\n AutocompleteRenderValue,\r\n AutocompleteValue,\r\n ChipTypeMap,\r\n TextFieldProps,\r\n} from \"@mui/material\";\r\nimport { ElementType } from \"react\";\r\n\r\nimport lodash from \"lodash\";\r\n\r\nconst { merge } = lodash;\r\n\r\nexport function getAutocompleteTypedValue<\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>(\r\n value:\r\n | AutocompleteRenderValue<TValue, Multiple, FreeSolo>\r\n | AutocompleteValue<TValue, Multiple, DisableClearable, FreeSolo>,\r\n ownerState?: AutocompleteOwnerState<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent>,\r\n) {\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}\r\n\r\n// Apply view-only properties directly to the TextFieldElement props\r\nexport const getTextElementDisplayProps = <PropType>(\r\n props: PropType,\r\n viewOnly = false,\r\n disableUnderline = false,\r\n) =>\r\n merge<PropType, Partial<TextFieldProps>>(\r\n props,\r\n viewOnly\r\n ? {\r\n disabled: true,\r\n variant: \"standard\",\r\n sx: {\r\n \"& .MuiAutocomplete-endAdornment\": {\r\n display: \"none\",\r\n },\r\n // Hide the underline without using slotProps.input.disableUnderline which clears out chips\r\n ...(disableUnderline && {\r\n \"& .MuiInput-underline:before\": { borderBottom: \"none\" },\r\n \"& .MuiInput-underline:after\": { borderBottom: \"none\" },\r\n \"& .MuiInput-underline:hover:not(.Mui-disabled):before\": { borderBottom: \"none\" },\r\n }),\r\n },\r\n }\r\n : {},\r\n ) as PropType;\r\n\r\nexport function isNonNullableString(value: any): value is NonNullable<string> {\r\n return value != null && typeof value === 'string';\r\n}","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\nimport { getTextElementDisplayProps } from \"../utils\";\r\n\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 viewOnly?: boolean;\r\n disableUnderline?: boolean;\r\n}\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 = undefined as boolean | undefined,\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 AutocompleteElementDisplayProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName>[\"autocompleteProps\"],\r\n AutocompleteElementDisplayProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName>[\"autocompleteProps\"],\r\n AutocompleteElementDisplayProps<TValue, Multiple, DisableClearable, FreeSolo, ChipComponent, TFieldValues, TName>[\"autocompleteProps\"]\r\n >(\r\n {\r\n readOnly: viewOnly,\r\n disableClearable: autocompleteProps?.disableClearable || viewOnly as DisableClearable,\r\n disabled: viewOnly,\r\n\r\n },\r\n autocompleteProps,\r\n viewOnly\r\n ? {\r\n sx: {\r\n \".MuiAutocomplete-tag\": {\r\n opacity: \"1 !important\",\r\n },\r\n },\r\n }\r\n : {},\r\n ),\r\n [autocompleteProps, viewOnly],\r\n );\r\n\r\n const textFieldAdjustedProps= useMemo(\r\n () => getTextElementDisplayProps(textFieldProps, viewOnly, disableUnderline),\r\n [textFieldProps, viewOnly, disableUnderline],\r\n );\r\n\r\n return (\r\n <AutocompleteElement\r\n autocompleteProps={autocompleteAdjustedProps}\r\n textFieldProps={textFieldAdjustedProps}\r\n {...props}\r\n />\r\n );\r\n};\r\n\r\n\r\n","import { type ElementType, useMemo, useState, useEffect } from \"react\";\nimport {\n Checkbox,\n Chip,\n ListItem,\n type ChipProps,\n type ChipTypeMap,\n type ListItemProps,\n} from \"@mui/material\";\nimport type { FieldPath, FieldValues } from \"react-hook-form\";\nimport {\n AutocompleteElementDisplay,\n type AutocompleteElementDisplayProps,\n} from \"./AutocompleteElementDisplay\";\nimport { getAutocompleteTypedValue, isNonNullableString } from \"../utils\";\nimport { useController } from \"react-hook-form-mui\";\nimport { merge } from \"lodash\";\n\n/**\n * Interface for special \"add option\" objects used in freeSolo mode\n * These objects represent a new item that can be created from user input\n */\ninterface AddOptionType {\n __isAddOption: true;\n inputValue: string;\n\n [key: string]: any; // Allow for additional properties from stringToNewItem\n}\n\n/**\n * Extends AutocompleteElementDisplayProps 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 ObjectElementDisplayProps<\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 string to display as the option label\n */\n getItemLabel: (value: TValue | null) => string;\n\n /**\n * Function to get additional props for an option list item.\n * Used for customizing the rendering of the option.\n *\n * @param value - The option value or null\n * @returns Additional props to apply to the list item\n */\n getOptionProps?: (value: TValue | null) => ListItemProps;\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 * Optional function to transform the value before it's updated in the form.\n * This allows for custom processing or enrichment of the selected value.\n *\n * @param value - The value that would normally be sent to the form\n * @returns The transformed value to be stored in the form\n */\n transformValue?: Multiple extends true\n ? (value: TValue[]) => TFieldValues\n : (value: TValue | null) => TFieldValues | null;\n};\n\n/**\n * A form component that displays a searchable dropdown for selecting object values.\n * Extends AutocompleteElementDisplay 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 ObjectElementDisplay = <\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 transformValue,\n name,\n freeSolo,\n control,\n getOptionProps,\n ...props\n}: ObjectElementDisplayProps<\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 storing dynamically added options that aren't in the original options list\n * Includes both default values and values added during freeSolo mode\n */\n const [newOptions, setNewOptions] = useState<TValue[]>(() => {\n if (!field.value) return [];\n\n // Convert field value to array for consistent handling\n const fieldValues: TValue[] = Array.isArray(field.value) ? field.value : [field.value];\n\n // Keep only object values that don't exist in the options array\n return fieldValues.filter(\n (value) =>\n typeof value !== \"string\" &&\n !options.some((option) => getItemKey(option) === getItemKey(value)),\n );\n });\n\n /**\n * Update newOptions when field.value changes\n * This ensures that any new values added to the field after rendering\n * are properly included in newOptions and displayed\n */\n useEffect(() => {\n if (!field.value) return;\n\n const fieldValues: TValue[] = Array.isArray(field.value) ? field.value : [field.value];\n const newFieldOptions = fieldValues.filter(\n (value) =>\n typeof value !== \"string\" &&\n ![...options, ...newOptions].some((option) => getItemKey(option) === getItemKey(value)),\n );\n\n // Only update newOptions if there are new values to add\n if (newFieldOptions.length > 0) {\n setNewOptions((prevOptions) => [...prevOptions, ...newFieldOptions]);\n }\n }, [field.value, options, newOptions, getItemKey]);\n\n /**\n * Combined list of all available options (original + dynamically added)\n */\n const allOptions = useMemo(() => [...options, ...newOptions], [options, newOptions]);\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 or label contains the input value (case-insensitive)\n * For freeSolo mode, adds a special \"Add [value]\" option when there's no exact match\n */\n filterOptions: (options, { inputValue }) => {\n if (!inputValue) return options;\n\n const searchValue = inputValue.toLowerCase();\n\n // Filter options that match the input value (by key or label)\n const filteredOptions = options.filter((option) => {\n const key = getItemKey(option).toLowerCase();\n const label = String(getItemLabel(option)).toLowerCase();\n return key.includes(searchValue) || label.includes(searchValue);\n });\n\n // For freeSolo mode, add \"Add [value]\" option if no exact match exists\n if (freeSolo && stringToNewItem && inputValue.length > 0) {\n const hasExactMatch = filteredOptions.some(\n (option) => String(getItemLabel(option)).toLowerCase() === searchValue,\n );\n\n if (!hasExactMatch) {\n // Create a special option with a __isAddOption flag\n const addOption: AddOptionType = {\n __isAddOption: true,\n inputValue,\n ...stringToNewItem(inputValue), // Include properties for type compatibility\n };\n\n return [addOption as unknown as TValue, ...filteredOptions];\n }\n }\n\n return filteredOptions;\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 * Handles both regular options and special \"Add\" options in freeSolo mode\n */\n renderOption: (liProps, option, { selected }, ownerState) => {\n const itemProps = merge(liProps, getOptionProps?.(option) ?? {});\n\n // Handles the special \"Add\" option in freeSolo mode\n if (\n ownerState?.freeSolo &&\n typeof option === \"object\" &&\n option !== null &&\n \"__isAddOption\" in option\n ) {\n const inputValue = (option as unknown as AddOptionType).inputValue;\n return (\n <ListItem {...itemProps} key={`${name}-add-option-${inputValue}`}>\n Add: '{inputValue}'\n </ListItem>\n );\n }\n\n // Handle regular option\n return (\n <ListItem {...itemProps} key={`${name}-option-${getItemKey(option)}`}>\n {(props?.showCheckbox && ownerState?.multiple) && (\n <Checkbox sx={{ marginRight: 1 }} checked={selected} />\n )}\n {typeof option === \"string\" ? option : getItemLabel(option)}\n </ListItem>\n );\n },\n\n onChange: (event, value, reason, details) => {\n /**\n * Helper function to apply transformValue if provided, otherwise return the original value\n */\n const applyTransform = (val: any) => {\n return transformValue && val !== null\n ? field.onChange(transformValue(val))\n : field.onChange(val);\n };\n\n /**\n * Helper function to add a new item to newOptions if it doesn't exist already\n */\n const addToNewOptions = (item: TValue) => {\n const itemKey = getItemKey(item);\n const itemExists = [...options, ...newOptions].some(\n (option) => getItemKey(option) === itemKey,\n );\n\n if (!itemExists) {\n setNewOptions((prev) => [...prev, item]);\n }\n };\n\n /**\n * Helper function to extract input value from string or AddOption\n */\n const getInputValue = (item: any): string | null => {\n if (typeof item === \"string\" && item.length > 0) {\n return item;\n }\n if (typeof item === \"object\" && item !== null && \"__isAddOption\" in item) {\n return (item as unknown as AddOptionType).inputValue;\n }\n return null;\n };\n\n // Handle freeSolo mode with stringToNewItem function\n if (freeSolo && stringToNewItem) {\n // Handle special add option selection or string input\n const inputValue = getInputValue(value);\n\n if (inputValue) {\n const newItem = stringToNewItem(inputValue);\n\n if (props.multiple) {\n // For multiple selection, add the new item to the current values\n const currentValues = Array.isArray(field.value) ? field.value : [];\n const newValues = [...currentValues, newItem];\n applyTransform(newValues);\n } else {\n // For single selection, just use the new item\n applyTransform(newItem);\n }\n\n addToNewOptions(newItem);\n return;\n }\n\n // Handle array values (multiple selection)\n if (Array.isArray(value) && props.multiple) {\n // Convert any string values to objects and handle special add options\n const newValues =\n value?.map((item) => {\n const inputVal = getInputValue(item);\n return inputVal ? stringToNewItem(inputVal) : item;\n }) ?? [];\n\n applyTransform(newValues);\n\n // Add any new items to newOptions\n const allOptionsKeys = [...options, ...newOptions].map((option) =>\n getItemKey(option),\n );\n const newItems = newValues.filter(\n (item) => typeof item !== \"string\" && !allOptionsKeys.includes(getItemKey(item)),\n );\n\n if (newItems.length > 0) {\n setNewOptions((prev) => [...prev, ...newItems]);\n }\n return;\n }\n }\n\n // Default behavior for non-freeSolo cases\n if (transformValue && value !== null) {\n applyTransform(value as TValue | TValue[]);\n } else {\n autocompleteProps?.onChange?.(event, value, reason, details);\n }\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 = getAutocompleteTypedValue(value, ownerState);\n\n // Handle array values (multiple selection)\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\n // Get the label - use string directly or extract from object\n const label = typeof v === \"string\" ? v : getItemLabel(v);\n\n // Get additional chip props if available\n const valueSpecificProps =\n typeof v !== \"string\" && getChipProps ? getChipProps({ value: v, index }) : {};\n\n return (\n <Chip\n key={`${name}-chip-${key}`}\n {...valueSpecificProps}\n {...chipProps}\n label={label}\n />\n );\n });\n }\n\n // Handles single value - return string or extracted label\n return isNonNullableString(typedValue)\n ? typedValue\n : typedValue\n ? getItemLabel(typedValue as NonNullable<TValue>)\n : \"\";\n },\n ...autocompleteProps,\n }}\n />\n );\n};\n","import { TextFieldElement, type TextFieldElementProps } from \"react-hook-form-mui\";\nimport { type FieldPath, type FieldValues } from \"react-hook-form\";\nimport { useMemo } from \"react\";\nimport { getTextElementDisplayProps } from \"../utils\";\n\nexport type TextElementDisplayProps<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>\n> = TextFieldElementProps<TFieldValues, TName> & Viewable;\n\n/**\n * A form component that displays a text field with view-only capabilities.\n * Extends TextFieldElement with view-only functionality.\n *\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 text input with view-only support\n */\nexport const TextElementDisplay = <\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n>({\n viewOnly,\n disableUnderline,\n ...props\n}: TextElementDisplayProps<TFieldValues, TName>) => {\n\n const adjustedProps = useMemo(\n () => getTextElementDisplayProps(props, viewOnly, disableUnderline),\n [props, viewOnly, disableUnderline],\n );\n\n return <TextFieldElement {...adjustedProps} />;\n};\n\ntype Viewable = {\n viewOnly?: boolean;\n disableUnderline?: boolean;\n};\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 { 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","getAutocompleteTypedValue","value","ownerState","getTextElementDisplayProps","props","viewOnly","disableUnderline","isNonNullableString","AutocompleteElementDisplay","textFieldProps","autocompleteProps","autocompleteAdjustedProps","useMemo","textFieldAdjustedProps","jsx","AutocompleteElement","ObjectElementDisplay","options","getItemKey","getItemLabel","getChipProps","stringToNewItem","transformValue","name","freeSolo","control","getOptionProps","field","useController","newOptions","setNewOptions","useState","option","useEffect","newFieldOptions","prevOptions","allOptions","o","v","inputValue","searchValue","filteredOptions","key","label","liProps","selected","itemProps","createElement","ListItem","Checkbox","event","reason","details","applyTransform","val","addToNewOptions","item","itemKey","prev","getInputValue","newItem","newValues","inputVal","allOptionsKeys","newItems","getItemProps","typedValue","index","chipProps","valueSpecificProps","Chip","TextElementDisplay","adjustedProps","TextFieldElement","get","useFormError","errors","fieldError","useOnMount","callback","hasMounted","useRef","ValidationElement","rules","formControlProps","register","useFormContext","error","helperText","jsxs","FormControl","FormHelperText"],"mappings":"qPAWM,CAAA,MAAEA,GAAUC,EAEX,SAASC,EAOdC,EAGAC,EACA,CACA,OAAIA,GAAY,SACVA,GAAY,SAAiBD,CAMrC,CAGO,MAAME,EAA6B,CACxCC,EACAC,EAAW,GACXC,EAAmB,KAEnBR,EACEM,EACAC,EACI,CACE,SAAU,GACV,QAAS,WACT,GAAI,CACF,kCAAmC,CACjC,QAAS,MAAA,EAGX,GAAIC,GAAoB,CACtB,+BAAg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AC,EACA,UAAW,CAAE,OAAAT,CAAA,CAAO,EAClBU,iBAAA,EAEE,CAAE,MAAAC,EAAO,WAAAC,CAAA,EAAeb,EAAaC,EAAQrD,CAAI,EAEvD,OACEkE,EAAAA,KAACC,EAAAA,YAAA,CAAY,MAAAH,EAAe,GAAGH,EAC7B,SAAA,CAAAtE,MAAC,SAAM,KAAK,SAAU,GAAGuE,EAAS9D,EAAM4D,CAAK,EAAG,EAC/CI,GAASzE,EAAAA,IAAC6E,EAAAA,eAAA,CAAgB,SAAAH,CAAA,CAAW,CAAA,EACxC,CAEJ"}
package/dist/index.js CHANGED
@@ -1,126 +1,129 @@
1
- import { jsx as p, jsxs as H } from "react/jsx-runtime";
2
- import { AutocompleteElement as S, useController as z } from "react-hook-form-mui";
3
- import { useMemo as x, useRef as B, useEffect as G, useState as $, createElement as J } from "react";
4
- import V from "lodash";
5
- import { Chip as L, Typography as Q, Checkbox as W, FormControl as X, FormHelperText as Y } from "@mui/material";
6
- import { useFormContext as Z } from "react-hook-form";
7
- const { merge: g } = V, _ = ({
8
- viewOnly: r,
9
- disableUnderline: o,
1
+ import { jsx as x, jsxs as H } from "react/jsx-runtime";
2
+ import { AutocompleteElement as R, useController as q, TextFieldElement as L } from "react-hook-form-mui";
3
+ import { useMemo as O, useState as z, useEffect as P, createElement as T, useRef as G } from "react";
4
+ import F, { merge as J } from "lodash";
5
+ import { Chip as N, ListItem as _, Checkbox as Q, FormControl as W, FormHelperText as X } from "@mui/material";
6
+ import { useFormContext as Y } from "react-hook-form";
7
+ const { merge: Z } = F;
8
+ function w(e, n) {
9
+ return n?.multiple, n?.freeSolo, e;
10
+ }
11
+ const D = (e, n = !1, t = !1) => Z(
12
+ e,
13
+ n ? {
14
+ disabled: !0,
15
+ variant: "standard",
16
+ sx: {
17
+ "& .MuiAutocomplete-endAdornment": {
18
+ display: "none"
19
+ },
20
+ // Hide the underline without using slotProps.input.disableUnderline which clears out chips
21
+ ...t && {
22
+ "& .MuiInput-underline:before": { borderBottom: "none" },
23
+ "& .MuiInput-underline:after": { borderBottom: "none" },
24
+ "& .MuiInput-underline:hover:not(.Mui-disabled):before": { borderBottom: "none" }
25
+ }
26
+ }
27
+ } : {}
28
+ );
29
+ function U(e) {
30
+ return e != null && typeof e == "string";
31
+ }
32
+ const { merge: v } = F, K = ({
33
+ viewOnly: e = void 0,
34
+ disableUnderline: n,
10
35
  textFieldProps: t,
11
- autocompleteProps: c,
12
- ...f
36
+ autocompleteProps: i,
37
+ ...y
13
38
  }) => {
14
- const u = x(
15
- () => g(
39
+ const d = O(
40
+ () => v(
16
41
  {
17
- readOnly: r,
18
- disableClearable: r,
19
- disabled: r,
20
- slotProps: {
21
- input: { disableUnderline: o },
22
- chip: {
23
- disabled: !1
24
- }
25
- }
42
+ readOnly: e,
43
+ disableClearable: i?.disableClearable || e,
44
+ disabled: e
26
45
  },
27
- c,
28
- r ? {
46
+ i,
47
+ e ? {
29
48
  sx: {
30
- ".MuiAutocomplete-endAdornment": {
31
- display: "none"
32
- },
33
49
  ".MuiAutocomplete-tag": {
34
50
  opacity: "1 !important"
35
51
  }
36
52
  }
37
53
  } : {}
38
54
  ),
39
- [c, r, o]
40
- ), l = x(
41
- () => g(r ? { variant: "standard" } : {}, t),
42
- [r, t]
55
+ [i, e]
56
+ ), A = O(
57
+ () => D(t, e, n),
58
+ [t, e, n]
43
59
  );
44
- return /* @__PURE__ */ p(
45
- S,
60
+ return /* @__PURE__ */ x(
61
+ R,
46
62
  {
47
- ...f,
48
- autocompleteProps: u,
49
- textFieldProps: l
63
+ autocompleteProps: d,
64
+ textFieldProps: A,
65
+ ...y
50
66
  }
51
67
  );
52
- };
53
- function N(r, o) {
54
- return o.multiple, o?.freeSolo, r;
55
- }
56
- const { get: U } = V;
57
- function v(r, o) {
58
- const t = U(r, o);
59
- return {
60
- error: !!t,
61
- helperText: t?.message || ""
62
- };
63
- }
64
- function K(r) {
65
- const o = B(!1);
66
- G(() => (o.current || (r(), o.current = !0), () => {
67
- o.current = !0;
68
- }), []);
69
- }
70
- const { omit: j } = V, sr = ({
71
- options: r,
72
- autocompleteProps: o,
68
+ }, le = ({
69
+ options: e,
70
+ autocompleteProps: n,
73
71
  getItemKey: t,
74
- getItemLabel: c,
75
- getChipProps: f,
76
- stringToNewItem: u,
77
- name: l,
78
- freeSolo: a,
79
- control: k,
80
- ...A
72
+ getItemLabel: i,
73
+ getChipProps: y,
74
+ stringToNewItem: d,
75
+ transformValue: A,
76
+ name: b,
77
+ freeSolo: M,
78
+ control: $,
79
+ getOptionProps: S,
80
+ ...V
81
81
  }) => {
82
- const { field: m } = z({ name: l, control: k }), [y, F] = $(""), [C, b] = $([]);
83
- K(() => {
84
- if (!a || !m.value) return;
85
- const e = (Array.isArray(m.value) ? m.value : [m.value]).filter((s) => typeof s == "string" ? !1 : !r.some((i) => t(i) === t(s)));
86
- e.length > 0 && b(e);
87
- });
88
- const d = x(() => {
89
- if (!a || !u || !y.length) return;
90
- const n = u(y), e = t(n);
91
- if (!r.some((s) => t(s) === e) && !C.some((s) => t(s) === e))
92
- return n;
93
- }, [u, y, C, a, r, t]), P = x(() => {
94
- if (!a) return r;
95
- const n = [...r, ...C];
96
- d && n.push(d);
97
- const e = /* @__PURE__ */ new Set();
98
- return n.filter((s) => {
99
- const i = t(s);
100
- return e.has(i) ? !1 : (e.add(i), !0);
101
- });
102
- }, [r, C, a, d, t]);
103
- return /* @__PURE__ */ p(
104
- _,
82
+ const { field: c } = q({ name: b, control: $ }), [C, j] = z(() => c.value ? (Array.isArray(c.value) ? c.value : [c.value]).filter(
83
+ (r) => typeof r != "string" && !e.some((l) => t(l) === t(r))
84
+ ) : []);
85
+ P(() => {
86
+ if (!c.value) return;
87
+ const r = (Array.isArray(c.value) ? c.value : [c.value]).filter(
88
+ (l) => typeof l != "string" && ![...e, ...C].some((s) => t(s) === t(l))
89
+ );
90
+ r.length > 0 && j((l) => [...l, ...r]);
91
+ }, [c.value, e, C, t]);
92
+ const B = O(() => [...e, ...C], [e, C]);
93
+ return /* @__PURE__ */ x(
94
+ K,
105
95
  {
106
- name: l,
107
- control: k,
108
- options: P,
109
- ...A,
96
+ name: b,
97
+ control: $,
98
+ options: B,
99
+ ...V,
110
100
  autocompleteProps: {
111
101
  /**
112
102
  * Determines if two options should be considered equal
113
103
  * Uses the getItemKey function to compare option values
114
104
  */
115
- isOptionEqualToValue: (n, e) => t(n) === t(e),
105
+ isOptionEqualToValue: (a, r) => t(a) === t(r),
116
106
  /**
117
107
  * Filters options based on the input value
118
- * Checks if the option key contains the input value (case-insensitive)
108
+ * Checks if the option key or label contains the input value (case-insensitive)
109
+ * For freeSolo mode, adds a special "Add [value]" option when there's no exact match
119
110
  */
120
- filterOptions: (n, { inputValue: e }) => n.filter(
121
- (s) => t(s).toLowerCase().includes(e.toLowerCase())
122
- ),
123
- freeSolo: a,
111
+ filterOptions: (a, { inputValue: r }) => {
112
+ if (!r) return a;
113
+ const l = r.toLowerCase(), s = a.filter((u) => {
114
+ const f = t(u).toLowerCase(), E = String(i(u)).toLowerCase();
115
+ return f.includes(l) || E.includes(l);
116
+ });
117
+ return M && d && r.length > 0 && !s.some(
118
+ (f) => String(i(f)).toLowerCase() === l
119
+ ) ? [{
120
+ __isAddOption: !0,
121
+ inputValue: r,
122
+ ...d(r)
123
+ // Include properties for type compatibility
124
+ }, ...s] : s;
125
+ },
126
+ freeSolo: M,
124
127
  // Allowed to enter own string value
125
128
  autoComplete: !0,
126
129
  autoHighlight: !0,
@@ -129,30 +132,51 @@ const { omit: j } = V, sr = ({
129
132
  // Opens the menu when tabbed into
130
133
  /**
131
134
  * Custom rendering for each option in the dropdown list
132
- * Displays a checkbox for multiple selection if showCheckbox is true
133
- * Uses getItemLabel to render the option label
135
+ * Handles both regular options and special "Add" options in freeSolo mode
134
136
  */
135
- renderOption: (n, e, { selected: s }) => /* @__PURE__ */ J("li", { ...n, key: `${l}-option-${t(e)}` }, A?.showCheckbox && /* @__PURE__ */ p(W, { sx: { marginRight: 1 }, checked: s }), typeof e == "string" ? e : c(e)),
136
- /**
137
- * Handles changes to the selected value(s)
138
- * In free-solo mode, adds the new item to newOptions when selected
139
- * Delegates to the original onChange handler if provided
140
- */
141
- onChange: (n, e, s, i) => {
142
- if (a && d) {
143
- if (u == null)
144
- throw new Error("Must implement stringToNewItem with freeSolo!");
145
- b((E) => [...E, d]), F("");
137
+ renderOption: (a, r, { selected: l }, s) => {
138
+ const u = J(a, S?.(r) ?? {});
139
+ if (s?.freeSolo && typeof r == "object" && r !== null && "__isAddOption" in r) {
140
+ const f = r.inputValue;
141
+ return /* @__PURE__ */ T(_, { ...u, key: `${b}-add-option-${f}` }, "Add: '", f, "'");
146
142
  }
147
- o?.onChange?.(n, e, s, i);
143
+ return /* @__PURE__ */ T(_, { ...u, key: `${b}-option-${t(r)}` }, V?.showCheckbox && s?.multiple && /* @__PURE__ */ x(Q, { sx: { marginRight: 1 }, checked: l }), typeof r == "string" ? r : i(r));
148
144
  },
149
- /**
150
- * Handles changes to the input text
151
- * Updates freeSoloValue state with the current input
152
- * Delegates to the original onInputChange handler if provided
153
- */
154
- onInputChange: (n, e, s) => {
155
- F(e), o?.onInputChange?.(n, e, s);
145
+ onChange: (a, r, l, s) => {
146
+ const u = (o) => A && o !== null ? c.onChange(A(o)) : c.onChange(o), f = (o) => {
147
+ const p = t(o);
148
+ [...e, ...C].some(
149
+ (m) => t(m) === p
150
+ ) || j((m) => [...m, o]);
151
+ }, E = (o) => typeof o == "string" && o.length > 0 ? o : typeof o == "object" && o !== null && "__isAddOption" in o ? o.inputValue : null;
152
+ if (M && d) {
153
+ const o = E(r);
154
+ if (o) {
155
+ const p = d(o);
156
+ if (V.multiple) {
157
+ const m = [...Array.isArray(c.value) ? c.value : [], p];
158
+ u(m);
159
+ } else
160
+ u(p);
161
+ f(p);
162
+ return;
163
+ }
164
+ if (Array.isArray(r) && V.multiple) {
165
+ const p = r?.map((h) => {
166
+ const k = E(h);
167
+ return k ? d(k) : h;
168
+ }) ?? [];
169
+ u(p);
170
+ const g = [...e, ...C].map(
171
+ (h) => t(h)
172
+ ), m = p.filter(
173
+ (h) => typeof h != "string" && !g.includes(t(h))
174
+ );
175
+ m.length > 0 && j((h) => [...h, ...m]);
176
+ return;
177
+ }
178
+ }
179
+ A && r !== null ? u(r) : n?.onChange?.(a, r, l, s);
156
180
  },
157
181
  /**
158
182
  * Custom rendering for the selected value(s)
@@ -160,56 +184,69 @@ const { omit: j } = V, sr = ({
160
184
  * For single selection, renders the value as text
161
185
  * Uses getItemLabel to render the value labels
162
186
  */
163
- renderValue: (n, e, s) => {
164
- const i = N(n, s);
165
- if (Array.isArray(i))
166
- return i.map((h, M) => {
167
- const { key: R, ...T } = e({ index: M }), q = typeof h == "string" ? h : c(h), w = typeof h != "string" && f ? f({ value: h, index: M }) : {};
168
- return /* @__PURE__ */ p(
169
- L,
170
- {
171
- label: q,
172
- ...w,
173
- ...T
174
- },
175
- `${l}-chip-${R}`
176
- );
177
- });
178
- const { key: E, ...D } = e({ index: 0 }), O = j(D, "onDelete");
179
- return /* @__PURE__ */ p(
180
- Q,
181
- {
182
- component: "span",
183
- color: "text.primary",
184
- ...A?.viewOnly ? j(O, "disabled") : O,
185
- children: typeof i == "string" ? i : c(i)
186
- },
187
- `${l}-value-${E}`
188
- );
187
+ renderValue: (a, r, l) => {
188
+ const s = w(a, l);
189
+ return Array.isArray(s) ? s.map((u, f) => {
190
+ const { key: E, ...o } = r({ index: f }), p = typeof u == "string" ? u : i(u), g = typeof u != "string" && y ? y({ value: u, index: f }) : {};
191
+ return /* @__PURE__ */ x(
192
+ N,
193
+ {
194
+ ...g,
195
+ ...o,
196
+ label: p
197
+ },
198
+ `${b}-chip-${E}`
199
+ );
200
+ }) : U(s) ? s : s ? i(s) : "";
189
201
  },
190
- ...o
202
+ ...n
191
203
  }
192
204
  }
193
205
  );
194
- }, ir = ({
195
- name: r,
196
- rules: o,
206
+ }, ie = ({
207
+ viewOnly: e,
208
+ disableUnderline: n,
209
+ ...t
210
+ }) => {
211
+ const i = O(
212
+ () => D(t, e, n),
213
+ [t, e, n]
214
+ );
215
+ return /* @__PURE__ */ x(L, { ...i });
216
+ }, { get: I } = F;
217
+ function ee(e, n) {
218
+ const t = I(e, n);
219
+ return {
220
+ error: !!t,
221
+ helperText: t?.message || ""
222
+ };
223
+ }
224
+ function ce(e) {
225
+ const n = G(!1);
226
+ P(() => (n.current || (e(), n.current = !0), () => {
227
+ n.current = !0;
228
+ }), []);
229
+ }
230
+ const ae = ({
231
+ name: e,
232
+ rules: n,
197
233
  formControlProps: t = {}
198
234
  }) => {
199
235
  const {
200
- register: c,
201
- formState: { errors: f }
202
- } = Z(), { error: u, helperText: l } = v(f, r);
203
- return /* @__PURE__ */ H(X, { error: u, ...t, children: [
204
- /* @__PURE__ */ p("input", { type: "hidden", ...c(r, o) }),
205
- u && /* @__PURE__ */ p(Y, { children: l })
236
+ register: i,
237
+ formState: { errors: y }
238
+ } = Y(), { error: d, helperText: A } = ee(y, e);
239
+ return /* @__PURE__ */ H(W, { error: d, ...t, children: [
240
+ /* @__PURE__ */ x("input", { type: "hidden", ...i(e, n) }),
241
+ d && /* @__PURE__ */ x(X, { children: A })
206
242
  ] });
207
243
  };
208
244
  export {
209
- _ as AutocompleteElementDisplay,
210
- sr as ObjectElementDisplay,
211
- ir as ValidationElement,
212
- v as useFormError,
213
- K as useOnMount
245
+ K as AutocompleteElementDisplay,
246
+ le as ObjectElementDisplay,
247
+ ie as TextElementDisplay,
248
+ ae as ValidationElement,
249
+ ee as useFormError,
250
+ ce as useOnMount
214
251
  };
215
252
  //# sourceMappingURL=index.js.map