Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
8a72d3a
export typeahead utils
Michele-Masciave Apr 11, 2025
f8dc2b0
integrate placeholder fix and changelog
Michele-Masciave Apr 16, 2025
a857384
adjust typescript
Michele-Masciave Apr 16, 2025
e1267ef
prepare-pr
Michele-Masciave Apr 28, 2025
12211f1
fixed
Michele-Masciave Apr 30, 2025
92e5c21
Merge branch 'main' of https://github.com/Michele-Masciave/react-hook…
Michele-Masciave Apr 30, 2025
a9347da
Merge branch 'neolution-ch:main' into main
Michele-Masciave May 7, 2025
2987413
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jun 3, 2025
acad69e
Merge branch 'main' of https://github.com/Michele-Masciave/react-hook…
Michele-Masciave Jun 13, 2025
de96e5c
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jun 18, 2025
fbfcc8e
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jun 25, 2025
b5c2533
Merge branch 'main' of https://github.com/Michele-Masciave/react-hook…
Michele-Masciave Jul 7, 2025
7843d38
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jul 16, 2025
6b81771
Merge branch 'neolution-ch:main' into main
Michele-Masciave Sep 26, 2025
743acf1
Merge branch 'neolution-ch:main' into main
Michele-Masciave Sep 29, 2025
022db3c
Merge branch 'neolution-ch:main' into main
Michele-Masciave Oct 1, 2025
bbd78a7
Merge branch 'neolution-ch:main' into main
Michele-Masciave Oct 21, 2025
5d28ea3
Merge branch 'neolution-ch:main' into main
Michele-Masciave Dec 3, 2025
3e9f9a7
Merge branch 'neolution-ch:main' into main
Michele-Masciave Dec 10, 2025
814c18e
Merge branch 'neolution-ch:main' into main
Michele-Masciave Dec 15, 2025
a2108d9
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jan 8, 2026
349cd68
Merge branch 'neolution-ch:main' into main
Michele-Masciave Jan 13, 2026
736a923
test
Michele-Masciave Jan 13, 2026
dac96ee
no watch test
Michele-Masciave Jan 13, 2026
ac6b4c8
try to isolate
Michele-Masciave Jan 13, 2026
0d752ec
try to memorize the form
Michele-Masciave Jan 13, 2026
1d590ea
ref
Michele-Masciave Jan 13, 2026
4d6414e
no use-controller
Michele-Masciave Jan 13, 2026
8601bfa
get rid of onChange
Michele-Masciave Jan 13, 2026
0d67085
try to remove on change to test
Michele-Masciave Jan 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const plugins = [
terser({
output: { comments: false },
compress: {
drop_console: true,
drop_console: false,
},
}),
];
Expand Down
41 changes: 36 additions & 5 deletions src/lib/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ReactNode } from "react";
import { ReactNode, useMemo } from "react";
import { DeepPartial, FieldValues, Resolver, SubmitHandler, useForm, UseFormReturn } from "react-hook-form";
import { jsonIsoDateReviver } from "./helpers/dateUtils";
import { FormContext, FormContextProps } from "./context/FormContext";
Expand Down Expand Up @@ -80,8 +80,41 @@ const Form = <T extends FieldValues>({
const formMethods = useForm<T>({ resolver, defaultValues: revivedDefaultValues });
const autoSubmitHandler = useAutoSubmit({ onSubmit, formMethods, autoSubmitConfig });

// Memoize the object passed to function children to avoid creating new reference each render
const formPropsForChildren = useMemo(
() => ({
...formMethods,
disabled,
requiredFields,
hideValidationMessages,
disableAriaAutocomplete,
}),
[formMethods, disabled, requiredFields, hideValidationMessages, disableAriaAutocomplete],
);

// Memoize context value to prevent unnecessary re-renders of context consumers
const contextValue = useMemo(
() => ({
requiredFields,
disabled,
hideValidationMessages,
disableAriaAutocomplete,
...formMethods,
}),
[formMethods, requiredFields, disabled, hideValidationMessages, disableAriaAutocomplete],
);

// Only recompute children if the props object changes
const resolvedChildren = useMemo(
() => (typeof children === "function" ? children(formPropsForChildren) : children),
[children, formPropsForChildren],
);

console.log("Rendering Form", { contextValue });
console.log("Rendering Form", { formPropsForChildren });

return (
<FormContext.Provider value={{ requiredFields, disabled, hideValidationMessages, disableAriaAutocomplete, ...formMethods }}>
<FormContext.Provider value={contextValue}>
<form
ref={(elem) => {
if (formRef) {
Expand All @@ -92,9 +125,7 @@ const Form = <T extends FieldValues>({
method="POST"
autoComplete={autoComplete}
>
{children instanceof Function
? children({ ...formMethods, disabled, requiredFields, hideValidationMessages, disableAriaAutocomplete })
: children}
{resolvedChildren}
</form>
</FormContext.Provider>
);
Expand Down
232 changes: 118 additions & 114 deletions src/lib/StaticTypeaheadInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable max-lines */
import { useEffect, useMemo, useState } from "react";
import { FieldValues, useController } from "react-hook-form";
import { FieldValues, Controller } from "react-hook-form";
import { useSafeNameId } from "src/lib/hooks/useSafeNameId";
import { CommonTypeaheadProps, StaticTypeaheadAutocompleteProps, TypeaheadOption, TypeaheadOptions } from "./types/Typeahead";
import { useFormContext } from "./context/FormContext";
Expand Down Expand Up @@ -29,8 +29,7 @@ interface StaticTypeaheadInputProps<T extends FieldValues> extends CommonTypeahe
autocompleteProps?: StaticTypeaheadAutocompleteProps;
}

// eslint-disable-next-line complexity
const StaticTypeaheadInput = <T extends FieldValues>(props: StaticTypeaheadInputProps<T>) => {
const AutoComplete = <T extends FieldValues>(props: StaticTypeaheadInputProps<T>) => {
const {
options,
multiple,
Expand Down Expand Up @@ -66,143 +65,148 @@ const StaticTypeaheadInput = <T extends FieldValues>(props: StaticTypeaheadInput
fixedOptions,
withFixedOptionsInValue = true,
innerRef,
name,
id,
} = props;

const [page, setPage] = useState(1);
const [loadMoreOptions, setLoadMoreOptions] = useState(limitResults !== undefined && limitResults < options.length);

const { name, id } = useSafeNameId(props.name ?? "", props.id);
const { control, disabled: formDisabled, getFieldState, clearErrors, watch } = useFormContext();
const {
field: { ref, ...field },
} = useController({
name,
control,
rules: {
validate: {
required: () => getFieldState(name)?.error?.message,
},
},
});
const { control, disabled: formDisabled, clearErrors } = useFormContext<T>();

const isDisabled = useMemo(() => formDisabled || disabled, [formDisabled, disabled]);
const paginatedOptions = useMemo(
() => (limitResults === undefined ? options : options.slice(0, page * limitResults)),
[limitResults, page, options],
);

const fieldValue = watch(name) as string | number | string[] | number[] | undefined;
const value = useMemo(
() =>
multiple
? getMultipleAutoCompleteValue(combineOptions(options, fixedOptions), fieldValue as string[] | number[] | undefined)
: getSingleAutoCompleteValue(options, fieldValue as string | number | undefined),
[fieldValue, multiple, options, fixedOptions],
);

validateFixedOptions(fixedOptions, multiple, autocompleteProps, withFixedOptionsInValue, value);
// Validate fixed options upfront
useEffect(() => {
validateFixedOptions(fixedOptions, multiple, autocompleteProps, withFixedOptionsInValue, []);
}, [fixedOptions, multiple, autocompleteProps, withFixedOptionsInValue]);

useEffect(() => {
if (limitResults !== undefined) {
setLoadMoreOptions(page * limitResults < options.length);
}
}, [options, page, limitResults]);

return (
<Controller
name={name}
control={control}
rules={{
validate: {
required: () => {
const fieldState = control.getFieldState(name);
return fieldState?.error?.message;
},
},
}}
render={({ field }) => {
const fieldValue = field.value;
const value = multiple
? getMultipleAutoCompleteValue(combineOptions(options, fixedOptions), fieldValue as string[] | number[] | undefined)
: getSingleAutoCompleteValue(options, fieldValue as string | number | undefined);

return (
<Autocomplete<TypeaheadOption, boolean, boolean, boolean>
{...autocompleteProps}
{...field}
id={id}
multiple={multiple}
groupBy={useGroupBy ? groupOptions : undefined}
options={useGroupBy ? sortOptionsByGroup(paginatedOptions) : paginatedOptions}
isOptionEqualToValue={
autocompleteProps?.isOptionEqualToValue ??
((option, value) => (typeof option === "string" ? option === value : option.value === (value as LabelValueOption).value))
}
getOptionKey={
autocompleteProps?.getOptionKey ??
((option: TypeaheadOption) => (typeof option === "string" ? option : `${option.label}-${option.value ?? ""}`))
}
disableCloseOnSelect={multiple}
value={resolveInputValue(multiple, fixedOptions, withFixedOptionsInValue, value)}
getOptionLabel={(option: TypeaheadOption) => (typeof option === "string" ? option : option.label)}
getOptionDisabled={(option) =>
getOptionDisabled?.(option) ||
(useGroupBy && isDisabledGroup(option)) ||
(typeof option === "string" ? false : (option.disabled ?? false))
}
disabled={isDisabled}
readOnly={readOnly}
selectOnFocus={markAllOnFocus}
style={inputGroupStyle}
className={className}
autoSelect={autoSelect}
autoHighlight={autoHighlight}
onClose={readOnly ? undefined : onClose}
onOpen={readOnly ? undefined : onOpen}
onBlur={() => {
if (onBlur) {
onBlur();
}
field.onBlur();
}}
onChange={(_, selectedValue) => {
const optionsArray = getOptionsFromValue(selectedValue, fixedOptions, withFixedOptionsInValue);
const values = convertAutoCompleteOptionsToStringArray(optionsArray);
const finalValue = multiple ? values : values[0];
clearErrors(field.name);
if (onChange) {
onChange(finalValue);
}
}}
onInputChange={(_e, value, reason) => {
onInputChange?.(value, reason);
}}
renderOption={highlightOptions ? renderHighlightedOptionFunction : undefined}
renderInput={(params) => (
<TypeaheadTextField
{...params}
isLoading={isLoading}
name={name}
label={label}
addonLeft={addonLeft}
addonRight={addonRight}
addonProps={{ isDisabled }}
style={style}
hideValidationMessage={hideValidationMessage}
useBootstrapStyle={useBootstrapStyle}
helpText={helpText}
placeholder={multiple && value.length > 0 ? undefined : placeholder}
paginationIcon={paginationIcon}
paginationText={paginationText}
variant={variant}
limitResults={limitResults}
loadMoreOptions={loadMoreOptions}
setPage={setPage}
inputRef={(elem) => {
if (innerRef) innerRef.current = elem as HTMLInputElement;
field.ref(elem);
}}
/>
)}
renderTags={createTagRenderer(fixedOptions, autocompleteProps)}
/>
);
}}
/>
);
};

const StaticTypeaheadInput = <T extends FieldValues>(props: StaticTypeaheadInputProps<T>) => {
const { label, useBootstrapStyle = false } = props;
const { name, id } = useSafeNameId(props.name ?? "", props.id);

return (
<FormGroupLayout
name={name}
label={useBootstrapStyle ? label : undefined}
labelStyle={useBootstrapStyle ? { color: "#8493A5", fontSize: 14 } : undefined}
layout="muiInput"
>
<Autocomplete<TypeaheadOption, boolean, boolean, boolean>
{...autocompleteProps}
{...field}
id={id}
multiple={multiple}
groupBy={useGroupBy ? groupOptions : undefined}
options={useGroupBy ? sortOptionsByGroup(paginatedOptions) : paginatedOptions}
isOptionEqualToValue={
autocompleteProps?.isOptionEqualToValue ??
((option, value) => (typeof option === "string" ? option === value : option.value === (value as LabelValueOption).value))
}
getOptionKey={
autocompleteProps?.getOptionKey ??
((option: TypeaheadOption) => (typeof option === "string" ? option : `${option.label}-${option.value ?? ""}`))
}
disableCloseOnSelect={multiple}
value={resolveInputValue(multiple, fixedOptions, withFixedOptionsInValue, value)}
getOptionLabel={(option: TypeaheadOption) => (typeof option === "string" ? option : option.label)}
getOptionDisabled={(option) =>
getOptionDisabled?.(option) ||
(useGroupBy && isDisabledGroup(option)) ||
(typeof option === "string" ? false : (option.disabled ?? false))
}
disabled={isDisabled}
readOnly={readOnly}
selectOnFocus={markAllOnFocus}
style={inputGroupStyle}
className={className}
autoSelect={autoSelect}
autoHighlight={autoHighlight}
onClose={readOnly ? undefined : onClose}
onOpen={readOnly ? undefined : onOpen}
onBlur={() => {
if (onBlur) {
onBlur();
}
field.onBlur();
}}
onChange={(_, value) => {
// value is typed as Autocomplete<Value> (aka TypeaheadOption) or an array of Autocomplete<Value> (aka TypeaheadOption[])
// however, the component is not intended to be used with mixed types
const optionsArray = getOptionsFromValue(value, fixedOptions, withFixedOptionsInValue);
const values = convertAutoCompleteOptionsToStringArray(optionsArray);
const finalValue = multiple ? values : values[0];
clearErrors(field.name);
if (onChange) {
onChange(finalValue);
}
field.onChange(finalValue);
}}
onInputChange={(_e, value, reason) => {
if (onInputChange) {
onInputChange(value, reason);
}
}}
renderOption={highlightOptions ? renderHighlightedOptionFunction : undefined}
renderInput={(params) => (
<TypeaheadTextField
isLoading={isLoading}
name={name}
label={label}
addonLeft={addonLeft}
addonRight={addonRight}
addonProps={{
isDisabled,
}}
style={style}
hideValidationMessage={hideValidationMessage}
useBootstrapStyle={useBootstrapStyle}
helpText={helpText}
placeholder={multiple && value.length > 0 ? undefined : placeholder}
paginationIcon={paginationIcon}
paginationText={paginationText}
variant={variant}
limitResults={limitResults}
loadMoreOptions={loadMoreOptions}
setPage={setPage}
{...params}
inputRef={(elem) => {
if (innerRef) {
innerRef.current = elem as HTMLInputElement;
}
ref(elem);
}}
/>
)}
renderTags={createTagRenderer(fixedOptions, autocompleteProps)}
/>
<AutoComplete<T> {...props} id={id} name={props.name} />
</FormGroupLayout>
);
};
Expand Down
Loading