Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
145 changes: 1 addition & 144 deletions plugin-hrm-form/src/components/common/forms/formGenerators.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,11 @@ import React from 'react';
import { RegisterOptions, useFormContext } from 'react-hook-form';
import { get, pick } from 'lodash';
import { Template } from '@twilio/flex-ui';
import { FormInputType, FormItemDefinition, InputOption, MixedOrBool, SelectOption } from 'hrm-form-definitions';
import { FormInputType, FormItemDefinition, InputOption, MixedOrBool } from 'hrm-form-definitions';
import SearchIcon from '@material-ui/icons/Search';

import {
Box,
DependentSelectLabel,
FormCheckbox,
FormCheckBoxWrapper,
FormDateInput,
Expand All @@ -40,11 +39,8 @@ import {
FormListboxMultiselectOptionLabel,
FormListboxMultiselectOptionsContainer,
FormMixedCheckbox,
FormOption,
FormRadioInput,
FormSearchInput,
FormSelect,
FormSelectWrapper,
FormTimeInput,
Row,
SearchIconContainer,
Expand All @@ -70,29 +66,6 @@ export const RequiredAsterisk = () => (
const getRules = (field: FormItemDefinition): RegisterOptions =>
pick(field, ['max', 'maxLength', 'min', 'minLength', 'pattern', 'required', 'validate']);

const bindCreateSelectOptions = (path: string) => (o: SelectOption, selected: boolean) => (
<FormOption key={`${path}-${o.label}-${o.value}`} value={o.value} isEmptyValue={o.value === ''} selected={selected}>
{getTemplateStrings()[o.label] ?? o.label}
</FormOption>
);

const generateSelectOptions = (path: string, options: SelectOption[], currentValue: string): JSX.Element[] => {
const createSelectOptions = bindCreateSelectOptions(path);
const optionElements: JSX.Element[] = [];

// Need to select specifically first matching value, which is why we don't just use .map
let foundValue = false;
options.forEach(option => {
if (!foundValue && option.value === currentValue) {
foundValue = true;
optionElements.push(createSelectOptions(option, true));
} else {
optionElements.push(createSelectOptions(option, false));
}
});
return optionElements;
};

/**
* Helper function used to calclulate the element that should be focused for FormInputType.ListboxMultiselect type inputs
*/
Expand Down Expand Up @@ -462,122 +435,6 @@ export const getInputType = (parents: string[], updateCallback: () => void, cust
}}
</ConnectForm>
);
case FormInputType.Select:
return (
<ConnectForm key={path}>
{({ errors, register }) => {
const error = get(errors, path);
return (
<FormLabel htmlFor={path}>
<Row>
<Box marginBottom="8px">
{labelTextComponent}
{rules.required && <RequiredAsterisk />}
</Box>
</Row>
<FormSelectWrapper>
<FormSelect
id={path}
data-testid={path}
name={path}
error={Boolean(error)}
aria-invalid={Boolean(error)}
aria-describedby={`${path}-error`}
onChange={updateCallback}
ref={ref => {
if (htmlElRef) {
htmlElRef.current = ref;
}
register(rules)(ref);
}}
disabled={!isEnabled}
>
{generateSelectOptions(path, def.options, initialValue)}
</FormSelect>
</FormSelectWrapper>
{error && (
<FormError>
<Template id={`${path}-error`} code={error.message} />
</FormError>
)}
</FormLabel>
);
}}
</ConnectForm>
);
case FormInputType.DependentSelect:
return (
<ConnectForm key={path}>
{({ errors, register, watch, setValue }) => {
const isMounted = React.useRef(false); // mutable value to avoid reseting the state in the first render. This preserves the "intialValue" provided
const prevDependeeValue = React.useRef(undefined); // mutable value to store previous dependeeValue

const dependeePath = [...parents, def.dependsOn].join('.');
const dependeeValue = watch(dependeePath);

React.useEffect(() => {
if (isMounted.current && prevDependeeValue.current && dependeeValue !== prevDependeeValue.current) {
setValue(path, def.defaultOption, { shouldValidate: true });
} else isMounted.current = true;

prevDependeeValue.current = dependeeValue;
}, [setValue, dependeeValue]);

const error = get(errors, path);
const hasOptions = Boolean(dependeeValue && def.options[dependeeValue]);
const shouldInitialize = initialValue && !isMounted.current;

const validate = (data: any) =>
hasOptions && def.required && data === def.defaultOption.value ? 'RequiredFieldError' : null;

// eslint-disable-next-line no-nested-ternary
const options: SelectOption[] = hasOptions
? [def.defaultOption, ...def.options[dependeeValue]]
: shouldInitialize
? [def.defaultOption, { label: initialValue, value: initialValue }]
: [def.defaultOption];

const disabled = !hasOptions && !shouldInitialize;

return (
<DependentSelectLabel htmlFor={path} disabled={disabled}>
<Row>
<Box marginBottom="8px">
{labelTextComponent}
{hasOptions && rules.required && <RequiredAsterisk />}
</Box>
</Row>
<FormSelectWrapper>
<FormSelect
id={path}
data-testid={path}
name={path}
error={Boolean(error)}
aria-invalid={Boolean(error)}
aria-describedby={`${path}-error`}
onChange={updateCallback}
ref={ref => {
if (htmlElRef) {
htmlElRef.current = ref;
}

register({ validate })(ref);
}}
disabled={!isEnabled || disabled}
>
{generateSelectOptions(path, options, initialValue)}
</FormSelect>
</FormSelectWrapper>
{error && (
<FormError>
<Template id={`${path}-error`} code={error.message} />
</FormError>
)}
</DependentSelectLabel>
);
}}
</ConnectForm>
);
case FormInputType.CopyTo:
case FormInputType.Checkbox:
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import React from 'react';
import { Template } from '@twilio/flex-ui';
import { get } from 'lodash';
import { useFormContext } from 'react-hook-form';
import { SelectOption } from 'hrm-form-definitions';

import { DependentFormSelectProps } from '../types';
import { generateSelectOptions } from './generateSelectOptions';
import { FormSelectUI } from './FormSelectUI';

const DependentFormSelect: React.FC<DependentFormSelectProps> = ({
inputId,
label,
initialValue,
registerOptions,
updateCallback,
htmlElRef,
isEnabled,
dependentOptions,
defaultOption,
dependsOn,
}) => {
// TODO factor out into a custom hook to make easier sharing this chunk of code
const { errors, register, watch, setValue } = useFormContext();
const error = get(errors, inputId);
const labelTextComponent = React.useMemo(() => <Template code={`${label}`} className=".fullstory-unmask" />, [label]);
const errorId = `${inputId}-error`;
const errorTextComponent = React.useMemo(() => (error ? <Template id={errorId} code={error.message} /> : null), [
error,
errorId,
]);

const parents = inputId.split('.').slice(0, -1);
const dependeePath = [...parents, dependsOn].join('.');
const dependeeValue = watch(dependeePath);
const isMounted = React.useRef(false);
const hasOptions = Boolean(dependeeValue && dependentOptions[dependeeValue]);
const shouldInitialize = initialValue && !isMounted.current;

const required = Boolean(registerOptions.required);
const refFunction = React.useCallback(
ref => {
if (htmlElRef && ref) {
htmlElRef.current = ref;
}

register({
...registerOptions,
validate: (data: any) => (hasOptions && required && data === defaultOption.value ? 'RequiredFieldError' : null),
})(ref);
},
[defaultOption.value, hasOptions, htmlElRef, register, registerOptions, required],
);
// ====== //

const defaultValue = initialValue.toString();
// mutable value to avoid reseting the state in the first render. This preserves the "intialValue" provided
const prevDependeeValue = React.useRef(undefined); // mutable value to store previous dependeeValue

React.useEffect(() => {
if (isMounted.current && prevDependeeValue.current && dependeeValue !== prevDependeeValue.current) {
setValue(inputId, defaultOption, { shouldValidate: true });
} else {
isMounted.current = true;
}

prevDependeeValue.current = dependeeValue;
}, [setValue, dependeeValue, inputId, defaultOption]);

// eslint-disable-next-line no-nested-ternary
const options: SelectOption[] = hasOptions
? [defaultOption, ...dependentOptions[dependeeValue]]
: shouldInitialize
? [defaultOption, { label: defaultValue, value: defaultValue }]
: [defaultOption];

const disabled = !isEnabled || (!hasOptions && !shouldInitialize);

return (
<FormSelectUI
inputId={inputId}
updateCallback={updateCallback}
refFunction={refFunction}
defaultValue={defaultValue}
labelTextComponent={labelTextComponent}
required={required}
disabled={disabled}
isErrorState={Boolean(error)}
errorId={errorId}
errorTextComponent={errorTextComponent}
optionComponents={generateSelectOptions(inputId, options, defaultValue)}
/>
);
};

export default DependentFormSelect;
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import React from 'react';
import { Template } from '@twilio/flex-ui';
import { get } from 'lodash';
import { useFormContext } from 'react-hook-form';

import { FormSelectProps } from '../types';
import { generateSelectOptions } from './generateSelectOptions';
import { FormSelectUI } from './FormSelectUI';

const FormSelect: React.FC<FormSelectProps> = ({
inputId,
label,
initialValue,
registerOptions,
updateCallback,
htmlElRef,
isEnabled,
selectOptions,
}) => {
// TODO factor out into a custom hook to make easier sharing this chunk of code
const { errors, register } = useFormContext();
const error = get(errors, inputId);
const labelTextComponent = React.useMemo(() => <Template code={`${label}`} className=".fullstory-unmask" />, [label]);
const errorId = `${inputId}-error`;
const errorTextComponent = React.useMemo(() => (error ? <Template id={errorId} code={error.message} /> : null), [
error,
errorId,
]);
const refFunction = React.useCallback(
ref => {
if (htmlElRef && ref) {
htmlElRef.current = ref;
}

register(registerOptions)(ref);
},
[htmlElRef, register, registerOptions],
);
// ====== //

const defaultValue = initialValue.toString();
const disabled = !isEnabled;

return (
<FormSelectUI
inputId={inputId}
updateCallback={updateCallback}
refFunction={refFunction}
defaultValue={defaultValue}
labelTextComponent={labelTextComponent}
required={Boolean(registerOptions.required)}
disabled={disabled}
isErrorState={Boolean(error)}
errorId={errorId}
errorTextComponent={errorTextComponent}
optionComponents={generateSelectOptions(inputId, selectOptions, defaultValue)}
/>
);
};

export default FormSelect;
Loading
Loading