import React, { FC, useEffect, useState } from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { DataSourcePicker } from '@grafana/runtime'; import { ExpressionDatasourceRef } from '@grafana/runtime/src/utils/DataSourceWithBackend'; import { Button, Field, FormAPI, FormFieldErrors, FormsOnSubmit, HorizontalGroup, Input, InputControl, Legend, } from '@grafana/ui'; import { FolderPicker } from 'app/core/components/Select/FolderPicker'; import { DashboardInput, DashboardInputs, DataSourceInput, ImportDashboardDTO, LibraryPanelInputState, } from '../state/reducers'; import { validateTitle, validateUid } from '../utils/validation'; import { ImportDashboardLibraryPanelsList } from './ImportDashboardLibraryPanelsList'; interface Props extends Pick, 'register' | 'errors' | 'control' | 'getValues' | 'watch'> { uidReset: boolean; inputs: DashboardInputs; initialFolderId: number; onCancel: () => void; onUidReset: () => void; onSubmit: FormsOnSubmit; } export const ImportDashboardForm: FC = ({ register, errors, control, getValues, uidReset, inputs, initialFolderId, onUidReset, onCancel, onSubmit, watch, }) => { const [isSubmitted, setSubmitted] = useState(false); const watchDataSources = watch('dataSources'); const watchFolder = watch('folder'); /* This useEffect is needed for overwriting a dashboard. It submits the form even if there's validation errors on title or uid. */ useEffect(() => { if (isSubmitted && (errors.title || errors.uid)) { onSubmit(getValues(), {} as any); } }, [errors, getValues, isSubmitted, onSubmit]); const newLibraryPanels = inputs?.libraryPanels?.filter((i) => i.state === LibraryPanelInputState.New) ?? []; const existingLibraryPanels = inputs?.libraryPanels?.filter((i) => i.state === LibraryPanelInputState.Exists) ?? []; return ( <> Options await validateTitle(v, getValues().folder.id), })} type="text" data-testid={selectors.components.ImportDashboardForm.name} /> ( )} name="folder" control={control} /> <> {!uidReset ? ( await validateUid(v) })} addonAfter={!uidReset && } /> ) : ( await validateUid(v) })} /> )} {inputs.dataSources && inputs.dataSources.map((input: DataSourceInput, index: number) => { if (input.pluginId === ExpressionDatasourceRef.type) { return null; } const dataSourceOption = `dataSources[${index}]`; const current = watchDataSources ?? []; return ( ( )} control={control} rules={{ required: true }} /> ); })} {inputs.constants && inputs.constants.map((input: DashboardInput, index) => { const constantIndex = `constants[${index}]`; return ( ); })} ); }; function getButtonVariant(errors: FormFieldErrors) { return errors && (errors.title || errors.uid) ? 'destructive' : 'primary'; } function getButtonText(errors: FormFieldErrors) { return errors && (errors.title || errors.uid) ? 'Import (Overwrite)' : 'Import'; }