import debounce from 'debounce-promise'; import { ChangeEvent, useState } from 'react'; import { UseFormSetValue, useForm } from 'react-hook-form'; import { selectors } from '@grafana/e2e-selectors'; import { Button, Input, Switch, Field, Label, TextArea, Stack, Alert, Box } from '@grafana/ui'; import { FolderPicker } from 'app/core/components/Select/FolderPicker'; import { validationSrv } from 'app/features/manage-dashboards/services/ValidationSrv'; import { DashboardScene } from '../scene/DashboardScene'; import { DashboardChangeInfo, NameAlreadyExistsError, SaveButton, isNameExistsError } from './shared'; import { useSaveDashboard } from './useSaveDashboard'; interface SaveDashboardAsFormDTO { firstName?: string; title: string; description: string; folder: { uid?: string; title?: string }; copyTags: boolean; } export interface Props { dashboard: DashboardScene; changeInfo: DashboardChangeInfo; } export function SaveDashboardAsForm({ dashboard, changeInfo }: Props) { const { changedSaveModel } = changeInfo; const { register, handleSubmit, setValue, formState, getValues, watch } = useForm({ mode: 'onBlur', defaultValues: { title: changeInfo.isNew ? changedSaveModel.title! : `${changedSaveModel.title} Copy`, description: changedSaveModel.description ?? '', folder: { uid: dashboard.state.meta.folderUid, title: dashboard.state.meta.folderTitle, }, copyTags: false, }, }); const { errors, isValid, defaultValues } = formState; const formValues = watch(); const { state, onSaveDashboard } = useSaveDashboard(false); const [contentSent, setContentSent] = useState<{ title?: string; folderUid?: string }>({}); const [hasFolderChanged, setHasFolderChanged] = useState(false); const onSave = async (overwrite: boolean) => { const data = getValues(); const result = await onSaveDashboard(dashboard, { overwrite, folderUid: data.folder.uid, rawDashboardJSON: changedSaveModel, // save as config saveAsCopy: true, isNew: changeInfo.isNew, copyTags: data.copyTags, title: data.title, description: data.description, }); if (result.status === 'success') { dashboard.closeModal(); } else { setContentSent({ title: data.title, folderUid: data.folder.uid, }); } }; const cancelButton = ( ); const saveButton = (overwrite: boolean) => { const showSaveButton = !isValid && hasFolderChanged ? true : isValid; return ; }; function renderFooter(error?: Error) { const formValuesMatchContentSent = formValues.title.trim() === contentSent.title && formValues.folder.uid === contentSent.folderUid; if (isNameExistsError(error) && formValuesMatchContentSent) { return ; } return ( <> {error && formValuesMatchContentSent && ( {error.message &&

{error.message}

}
)} {cancelButton} {saveButton(false)} ); } return (
onSave(false))}> } invalid={!!errors.title} error={errors.title?.message}> ) => { setValue('title', e.target.value, { shouldValidate: true }); }, 400)} /> } invalid={!!errors.description} error={errors.description?.message} >