Grafana-UI: Update React Hook Form to v7 (#33328)

* Update hook form

* Update Form component

* Update ChangePassword.tsx

* Update custom types

* Update SaveDashboardForm

* Update form story

* Update FieldArray.story.tsx

* Bump hook form version

* Update typescript to v4.2.4

* Update ForgottenPassword.tsx

* Update LoginForm.tsx

* Update SignupPage.tsx

* Update VerifyEmail.tsx

* Update AdminEditOrgPage.tsx

* Update UserCreatePage.tsx

* Update BasicSettings.tsx

* Update NotificationChannelForm.tsx

* Update NotificationChannelOptions.tsx

* Update NotificationSettings.tsx

* Update OptionElement.tsx

* Update AlertRuleForm.tsx

* Update AlertTypeStep.tsx

* Update AnnotationsField.tsx

* Update ConditionField.tsx

* Update ConditionsStep.tsx

* Update GroupAndNamespaceFields.tsx

* Update LabelsField.tsx

* Update QueryStep.tsx

* Update RowOptionsForm.tsx

* Update SaveDashboardAsForm.tsx

* Update NewDashboardsFolder.tsx

* Update ImportDashboardForm.tsx

* Update DashboardImportPage.tsx

* Update NewOrgPage.tsx

* Update OrgProfile.tsx

* Update UserInviteForm.tsx

* Update PlaylistForm.tsx

* Update ChangePasswordForm.tsx

* Update UserProfileEditForm.tsx

* Update TeamSettings.tsx

* Update SignupInvited.tsx

* Expose setValue from the Form

* Update typescript to v4.2.4

* Remove ref from field props

* Fix tests

* Revert TS update

* Use exact version

* Update latest batch of changes

* Reduce the number of strict TS errors

* Fix defaults

* more type error fixes

* Update CreateTeam

* fix folder picker in rule form

* fixes for hook form 7

* Update docs

Co-authored-by: Domas <domasx2@gmail.com>
This commit is contained in:
Alex Khomenko
2021-04-29 16:54:38 +03:00
committed by GitHub
parent 9de2f1bb8f
commit 3b515e650c
56 changed files with 471 additions and 433 deletions

View File

@@ -7,7 +7,7 @@ import { AlertTypeStep } from './AlertTypeStep';
import { ConditionsStep } from './ConditionsStep';
import { DetailsStep } from './DetailsStep';
import { QueryStep } from './QueryStep';
import { useForm, FormContext } from 'react-hook-form';
import { useForm, FormProvider } from 'react-hook-form';
import { RuleFormType, RuleFormValues } from '../../types/rule-form';
import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector';
@@ -39,7 +39,11 @@ export const AlertRuleForm: FC<Props> = ({ existing }) => {
defaultValues,
});
const { handleSubmit, watch, errors } = formAPI;
const {
handleSubmit,
watch,
formState: { errors },
} = formAPI;
const hasErrors = !!Object.values(errors).filter((x) => !!x).length;
@@ -52,7 +56,6 @@ export const AlertRuleForm: FC<Props> = ({ existing }) => {
useCleanup((state) => state.unifiedAlerting.ruleForm.saveRule);
const submit = (values: RuleFormValues, exitOnSave: boolean) => {
console.log('submit', values);
dispatch(
saveRuleFormAction({
values: {
@@ -68,7 +71,7 @@ export const AlertRuleForm: FC<Props> = ({ existing }) => {
};
return (
<FormContext {...formAPI}>
<FormProvider {...formAPI}>
<form onSubmit={handleSubmit((values) => submit(values, false))} className={styles.form}>
<PageToolbar title="Create alert rule" pageIcon="bell" className={styles.toolbar}>
<Link to="/alerting/list">
@@ -121,7 +124,7 @@ export const AlertRuleForm: FC<Props> = ({ existing }) => {
</CustomScrollbar>
</div>
</form>
</FormContext>
</FormProvider>
);
};

View File

@@ -6,7 +6,7 @@ import { css } from '@emotion/css';
import { RuleEditorSection } from './RuleEditorSection';
import { useFormContext } from 'react-hook-form';
import { RuleFormType, RuleFormValues } from '../../types/rule-form';
import { DataSourcePicker, DataSourcePickerProps } from '@grafana/runtime';
import { DataSourcePicker } from '@grafana/runtime';
import { useRulesSourcesWithRuler } from '../../hooks/useRuleSourcesWithRuler';
import { RuleFolderPicker } from './RuleFolderPicker';
import { GroupAndNamespaceFields } from './GroupAndNamespaceFields';
@@ -31,7 +31,13 @@ interface Props {
export const AlertTypeStep: FC<Props> = ({ editingExistingRule }) => {
const styles = useStyles(getStyles);
const { register, control, watch, errors, setValue } = useFormContext<RuleFormValues>();
const {
register,
control,
watch,
formState: { errors },
setValue,
} = useFormContext<RuleFormValues & { location?: string }>();
const ruleFormType = watch('type');
const dataSourceName = watch('dataSourceName');
@@ -61,9 +67,8 @@ export const AlertTypeStep: FC<Props> = ({ editingExistingRule }) => {
invalid={!!errors.name?.message}
>
<Input
{...register('name', { required: { value: true, message: 'Must enter an alert name' } })}
autoFocus={true}
ref={register({ required: { value: true, message: 'Must enter an alert name' } })}
name="name"
/>
</Field>
<div className={styles.flexRow}>
@@ -75,25 +80,29 @@ export const AlertTypeStep: FC<Props> = ({ editingExistingRule }) => {
invalid={!!errors.type?.message}
>
<InputControl
as={Select}
render={({ field: { onChange, ref, ...field } }) => (
<Select
{...field}
options={alertTypeOptions}
onChange={(v: SelectableValue) => {
const value = v?.value;
// when switching to system alerts, null out data source selection if it's not a rules source with ruler
if (
value === RuleFormType.system &&
dataSourceName &&
!rulesSourcesWithRuler.find(({ name }) => name === dataSourceName)
) {
setValue('dataSourceName', null);
}
onChange(value);
}}
/>
)}
name="type"
options={alertTypeOptions}
control={control}
rules={{
required: { value: true, message: 'Please select alert type' },
}}
onChange={(values: SelectableValue[]) => {
const value = values[0]?.value;
// when switching to system alerts, null out data source selection if it's not a rules source with ruler
if (
value === RuleFormType.system &&
dataSourceName &&
!rulesSourcesWithRuler.find(({ name }) => name === dataSourceName)
) {
setValue('dataSourceName', null);
}
return value;
}}
/>
</Field>
{ruleFormType === RuleFormType.system && (
@@ -104,21 +113,25 @@ export const AlertTypeStep: FC<Props> = ({ editingExistingRule }) => {
invalid={!!errors.dataSourceName?.message}
>
<InputControl
as={(DataSourcePicker as unknown) as React.ComponentType<Omit<DataSourcePickerProps, 'current'>>}
valueName="current"
filter={dataSourceFilter}
render={({ field: { onChange, ref, value, ...field } }) => (
<DataSourcePicker
{...field}
current={value}
filter={dataSourceFilter}
noDefault
alerting
onChange={(ds: DataSourceInstanceSettings) => {
// reset location if switching data sources, as different rules source will have different groups and namespaces
setValue('location', undefined);
onChange(ds?.name ?? null);
}}
/>
)}
name="dataSourceName"
noDefault={true}
control={control}
alerting={true}
rules={{
required: { value: true, message: 'Please select a data source' },
}}
onChange={(ds: DataSourceInstanceSettings[]) => {
// reset location if switching data sources, as differnet rules source will have different groups and namespaces
setValue('location', undefined);
return ds[0]?.name ?? null;
}}
/>
</Field>
)}
@@ -134,10 +147,10 @@ export const AlertTypeStep: FC<Props> = ({ editingExistingRule }) => {
invalid={!!errors.folder?.message}
>
<InputControl
as={RuleFolderPicker}
render={({ field: { ref, ...field } }) => (
<RuleFolderPicker {...field} enableCreateNew={true} enableReset={true} />
)}
name="folder"
enableCreateNew={true}
enableReset={true}
rules={{
required: { value: true, message: 'Please select a folder' },
}}

View File

@@ -8,11 +8,16 @@ import { AnnotationKeyInput } from './AnnotationKeyInput';
const AnnotationsField: FC = () => {
const styles = useStyles(getStyles);
const { control, register, watch, errors } = useFormContext<RuleFormValues>();
const annotations = watch('annotations');
const {
control,
register,
watch,
formState: { errors },
} = useFormContext();
const annotations = watch('annotations') as RuleFormValues['annotations'];
const existingKeys = useCallback(
(index: number): string[] => annotations.filter((_, idx) => idx !== index).map(({ key }) => key),
(index: number): string[] => annotations.filter((_, idx: number) => idx !== index).map(({ key }) => key),
[annotations]
);
@@ -31,10 +36,10 @@ const AnnotationsField: FC = () => {
error={errors.annotations?.[index]?.key?.message}
>
<InputControl
as={AnnotationKeyInput}
width={15}
name={`annotations[${index}].key`}
existingKeys={existingKeys(index)}
render={({ field: { ref, ...field } }) => (
<AnnotationKeyInput {...field} existingKeys={existingKeys(index)} width={15} />
)}
control={control}
rules={{ required: { value: !!annotations[index]?.value, message: 'Required.' } }}
/>
@@ -45,9 +50,10 @@ const AnnotationsField: FC = () => {
error={errors.annotations?.[index]?.value?.message}
>
<TextArea
name={`annotations[${index}].value`}
className={styles.annotationTextArea}
ref={register({ required: { value: !!annotations[index]?.key, message: 'Required.' } })}
{...register(`annotations[${index}].value`, {
required: { value: !!annotations[index]?.key, message: 'Required.' },
})}
placeholder={`value`}
defaultValue={field.value}
/>

View File

@@ -5,7 +5,11 @@ import { useFormContext } from 'react-hook-form';
import { RuleFormValues } from '../../types/rule-form';
export const ConditionField: FC = () => {
const { watch, setValue, errors } = useFormContext<RuleFormValues>();
const {
watch,
setValue,
formState: { errors },
} = useFormContext<RuleFormValues>();
const queries = watch('queries');
const condition = watch('condition');
@@ -36,18 +40,22 @@ export const ConditionField: FC = () => {
invalid={!!errors.condition?.message}
>
<InputControl
width={42}
name="condition"
as={Select}
onChange={(values: SelectableValue[]) => values[0]?.value ?? null}
options={options}
render={({ field: { onChange, ref, ...field } }) => (
<Select
{...field}
width={42}
options={options}
onChange={(v: SelectableValue) => onChange(v?.value ?? null)}
noOptionsMessage="No queries defined"
/>
)}
rules={{
required: {
value: true,
message: 'Please select the condition to alert on',
},
}}
noOptionsMessage="No queries defined"
/>
</Field>
);

View File

@@ -3,12 +3,12 @@ import { Field, Input, Select, useStyles, InputControl, InlineLabel, Switch } fr
import { css } from '@emotion/css';
import { GrafanaTheme } from '@grafana/data';
import { RuleEditorSection } from './RuleEditorSection';
import { useFormContext, ValidationOptions } from 'react-hook-form';
import { useFormContext, RegisterOptions } from 'react-hook-form';
import { RuleFormType, RuleFormValues, TimeOptions } from '../../types/rule-form';
import { ConditionField } from './ConditionField';
import { GrafanaAlertStatePicker } from './GrafanaAlertStatePicker';
const timeRangeValidationOptions: ValidationOptions = {
const timeRangeValidationOptions: RegisterOptions = {
required: {
value: true,
message: 'Required.',
@@ -29,7 +29,12 @@ const timeOptions = Object.entries(TimeOptions).map(([key, value]) => ({
export const ConditionsStep: FC = () => {
const styles = useStyles(getStyles);
const [showErrorHandling, setShowErrorHandling] = useState(false);
const { register, control, watch, errors } = useFormContext<RuleFormValues>();
const {
register,
control,
watch,
formState: { errors },
} = useFormContext<RuleFormValues>();
const type = watch('type');
@@ -48,7 +53,7 @@ export const ConditionsStep: FC = () => {
error={errors.evaluateEvery?.message}
invalid={!!errors.evaluateEvery?.message}
>
<Input width={8} ref={register(timeRangeValidationOptions)} name="evaluateEvery" />
<Input width={8} {...register('evaluateEvery', timeRangeValidationOptions)} />
</Field>
<InlineLabel
width={7}
@@ -61,7 +66,7 @@ export const ConditionsStep: FC = () => {
error={errors.evaluateFor?.message}
invalid={!!errors.evaluateFor?.message}
>
<Input width={8} ref={register(timeRangeValidationOptions)} name="evaluateFor" />
<Input width={8} {...register('evaluateFor', timeRangeValidationOptions)} />
</Field>
</div>
</Field>
@@ -72,18 +77,18 @@ export const ConditionsStep: FC = () => {
<>
<Field label="Alert state if no data or all values are null">
<InputControl
as={GrafanaAlertStatePicker}
render={({ field: { onChange, ref, ...field } }) => (
<GrafanaAlertStatePicker {...field} width={42} onChange={(value) => onChange(value?.value)} />
)}
name="noDataState"
width={42}
onChange={(values) => values[0]?.value}
/>
</Field>
<Field label="Alert state if execution error or timeout">
<InputControl
as={GrafanaAlertStatePicker}
render={({ field: { onChange, ref, ...field } }) => (
<GrafanaAlertStatePicker {...field} width={42} onChange={(value) => onChange(value?.value)} />
)}
name="execErrState"
width={42}
onChange={(values) => values[0]?.value}
/>
</Field>
</>
@@ -96,19 +101,22 @@ export const ConditionsStep: FC = () => {
<div className={styles.flexRow}>
<Field invalid={!!errors.forTime?.message} error={errors.forTime?.message} className={styles.inlineField}>
<Input
ref={register({ pattern: { value: /^\d+$/, message: 'Must be a postive integer.' } })}
name="forTime"
{...register('forTime', { pattern: { value: /^\d+$/, message: 'Must be a postive integer.' } })}
width={8}
/>
</Field>
<InputControl
name="forTimeUnit"
as={Select}
options={timeOptions}
render={({ field: { onChange, ref, ...field } }) => (
<Select
{...field}
options={timeOptions}
onChange={(value) => onChange(value?.value)}
width={15}
className={styles.timeUnit}
/>
)}
control={control}
width={15}
className={styles.timeUnit}
onChange={(values) => values[0]?.value}
/>
</div>
</Field>
@@ -125,7 +133,6 @@ const getStyles = (theme: GrafanaTheme) => ({
flexRow: css`
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: flex-start;
align-items: flex-start;
`,

View File

@@ -14,7 +14,12 @@ interface Props {
}
export const GroupAndNamespaceFields: FC<Props> = ({ dataSourceName }) => {
const { control, watch, errors, setValue } = useFormContext<RuleFormValues>();
const {
control,
watch,
formState: { errors },
setValue,
} = useFormContext<RuleFormValues>();
const [customGroup, setCustomGroup] = useState(false);
@@ -44,32 +49,34 @@ export const GroupAndNamespaceFields: FC<Props> = ({ dataSourceName }) => {
<>
<Field label="Namespace" error={errors.namespace?.message} invalid={!!errors.namespace?.message}>
<InputControl
as={SelectWithAdd}
className={inputStyle}
render={({ field: { onChange, ref, ...field } }) => (
<SelectWithAdd
{...field}
className={inputStyle}
onChange={(value) => {
setValue('group', ''); //reset if namespace changes
onChange(value);
}}
onCustomChange={(custom: boolean) => {
custom && setCustomGroup(true);
}}
options={namespaceOptions}
width={42}
/>
)}
name="namespace"
options={namespaceOptions}
control={control}
width={42}
rules={{
required: { value: true, message: 'Required.' },
}}
onChange={(values) => {
setValue('group', ''); //reset if namespace changes
return values[0];
}}
onCustomChange={(custom: boolean) => {
custom && setCustomGroup(true);
}}
/>
</Field>
<Field label="Group" error={errors.group?.message} invalid={!!errors.group?.message}>
<InputControl
as={SelectWithAdd}
render={({ field: { ref, ...field } }) => (
<SelectWithAdd {...field} options={groupOptions} width={42} custom={customGroup} className={inputStyle} />
)}
name="group"
className={inputStyle}
options={groupOptions}
width={42}
custom={customGroup}
control={control}
rules={{
required: { value: true, message: 'Required.' },

View File

@@ -3,7 +3,6 @@ import { Button, Field, FieldArray, Input, InlineLabel, Label, useStyles } from
import { GrafanaTheme } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { useFormContext } from 'react-hook-form';
import { RuleFormValues } from '../../types/rule-form';
interface Props {
className?: string;
@@ -11,7 +10,12 @@ interface Props {
const LabelsField: FC<Props> = ({ className }) => {
const styles = useStyles(getStyles);
const { register, control, watch, errors } = useFormContext<RuleFormValues>();
const {
register,
control,
watch,
formState: { errors },
} = useFormContext();
const labels = watch('labels');
return (
<div className={cx(className, styles.wrapper)}>
@@ -33,8 +37,9 @@ const LabelsField: FC<Props> = ({ className }) => {
error={errors.labels?.[index]?.key?.message}
>
<Input
ref={register({ required: { value: !!labels[index]?.value, message: 'Required.' } })}
name={`labels[${index}].key`}
{...register(`labels[${index}].key`, {
required: { value: !!labels[index]?.value, message: 'Required.' },
})}
placeholder="key"
defaultValue={field.key}
/>
@@ -46,8 +51,9 @@ const LabelsField: FC<Props> = ({ className }) => {
error={errors.labels?.[index]?.value?.message}
>
<Input
ref={register({ required: { value: !!labels[index]?.key, message: 'Required.' } })}
name={`labels[${index}].value`}
{...register(`labels[${index}].value`, {
required: { value: !!labels[index]?.key, message: 'Required.' },
})}
placeholder="value"
defaultValue={field.value}
/>

View File

@@ -7,7 +7,11 @@ import { RuleFormType, RuleFormValues } from '../../types/rule-form';
import { AlertingQueryEditor } from '../../../components/AlertingQueryEditor';
export const QueryStep: FC = () => {
const { control, watch, errors } = useFormContext<RuleFormValues>();
const {
control,
watch,
formState: { errors },
} = useFormContext<RuleFormValues>();
const type = watch('type');
const dataSourceName = watch('dataSourceName');
return (
@@ -16,8 +20,7 @@ export const QueryStep: FC = () => {
<Field error={errors.expression?.message} invalid={!!errors.expression?.message}>
<InputControl
name="expression"
dataSourceName={dataSourceName}
as={ExpressionEditor}
render={({ field: { ref, ...field } }) => <ExpressionEditor {...field} dataSourceName={dataSourceName} />}
control={control}
rules={{
required: { value: true, message: 'A valid expression is required' },
@@ -32,7 +35,7 @@ export const QueryStep: FC = () => {
>
<InputControl
name="queries"
as={AlertingQueryEditor}
render={({ field: { ref, ...field } }) => <AlertingQueryEditor {...field} />}
control={control}
rules={{
validate: (queries) => Array.isArray(queries) && !!queries.length,

View File

@@ -6,7 +6,7 @@ export interface Folder {
id: number;
}
export interface Props extends Omit<FolderPickerProps, 'initiailTitle' | 'initialFolderId'> {
export interface Props extends Omit<FolderPickerProps, 'initialTitle' | 'initialFolderId'> {
value?: Folder;
}