-
Notifications
You must be signed in to change notification settings - Fork 43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✨ Add upload YAML questionnaire form #1290
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
client/src/app/pages/assessment/import-questionnaire-form/import-questionnaire-form.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import React, { useState } from "react"; | ||
import { AxiosResponse } from "axios"; | ||
import { useTranslation } from "react-i18next"; | ||
import * as yup from "yup"; | ||
|
||
import { | ||
ActionGroup, | ||
Button, | ||
ButtonVariant, | ||
FileUpload, | ||
Form, | ||
FormHelperText, | ||
HelperText, | ||
HelperTextItem, | ||
} from "@patternfly/react-core"; | ||
|
||
import { HookFormPFGroupController } from "@app/components/HookFormPFFields"; | ||
import { useForm } from "react-hook-form"; | ||
import { FileLoadError, IReadFile } from "@app/api/models"; | ||
import { yupResolver } from "@hookform/resolvers/yup"; | ||
import { useCreateFileMutation } from "@app/queries/targets"; | ||
|
||
export interface ImportQuestionnaireFormProps { | ||
onSaved: (response?: AxiosResponse) => void; | ||
} | ||
export interface ImportQuestionnaireFormValues { | ||
yamlFile: IReadFile; | ||
} | ||
|
||
export const yamlFileSchema: yup.SchemaOf<IReadFile> = yup.object({ | ||
fileName: yup.string().required(), | ||
fullFile: yup.mixed<File>(), | ||
loadError: yup.mixed<FileLoadError>(), | ||
loadPercentage: yup.number(), | ||
loadResult: yup.mixed<"danger" | "success" | undefined>(), | ||
data: yup.string(), | ||
responseID: yup.number(), | ||
}); | ||
|
||
export const ImportQuestionnaireForm: React.FC< | ||
ImportQuestionnaireFormProps | ||
> = ({ onSaved }) => { | ||
const { t } = useTranslation(); | ||
|
||
const [filename, setFilename] = useState<string>(); | ||
const [isFileRejected, setIsFileRejected] = useState(false); | ||
const validationSchema: yup.SchemaOf<ImportQuestionnaireFormValues> = yup | ||
.object() | ||
.shape({ | ||
yamlFile: yamlFileSchema, | ||
}); | ||
const methods = useForm<ImportQuestionnaireFormValues>({ | ||
resolver: yupResolver(validationSchema), | ||
mode: "onChange", | ||
}); | ||
|
||
const { | ||
handleSubmit, | ||
formState: { isSubmitting, isValidating, isValid, isDirty }, | ||
getValues, | ||
setValue, | ||
control, | ||
watch, | ||
setFocus, | ||
clearErrors, | ||
trigger, | ||
reset, | ||
} = methods; | ||
|
||
const { mutateAsync: createYamlFileAsync } = useCreateFileMutation(); | ||
|
||
const handleFileUpload = async (file: File) => { | ||
setFilename(file.name); | ||
const formFile = new FormData(); | ||
formFile.append("file", file); | ||
|
||
const newYamlFile: IReadFile = { | ||
fileName: file.name, | ||
fullFile: file, | ||
}; | ||
|
||
return createYamlFileAsync({ | ||
formData: formFile, | ||
file: newYamlFile, | ||
}); | ||
}; | ||
|
||
const onSubmit = (values: ImportQuestionnaireFormValues) => { | ||
console.log("values", values); | ||
onSaved(); | ||
}; | ||
return ( | ||
<Form onSubmit={handleSubmit(onSubmit)}> | ||
<HookFormPFGroupController | ||
control={control} | ||
name="yamlFile" | ||
label={t("terms.uploadYamlFile")} | ||
fieldId="yamlFile" | ||
helperText={t("dialog.uploadYamlFile")} | ||
renderInput={({ field: { onChange, name }, fieldState: { error } }) => ( | ||
<FileUpload | ||
id={`${name}-file-upload`} | ||
name={name} | ||
value={filename} | ||
filename={filename} | ||
filenamePlaceholder={t("dialog.dragAndDropFile")} | ||
dropzoneProps={{ | ||
accept: { | ||
"text/yaml": [".yml", ".yaml"], | ||
}, | ||
maxSize: 1000000, | ||
onDropRejected: (event) => { | ||
const currentFile = event[0]; | ||
if (currentFile.file.size > 1000000) { | ||
methods.setError(name, { | ||
type: "custom", | ||
message: t("dialog.maxFileSize"), | ||
}); | ||
} | ||
setIsFileRejected(true); | ||
}, | ||
}} | ||
validated={isFileRejected || error ? "error" : "default"} | ||
onFileInputChange={async (_, file) => { | ||
console.log("uploading file", file); | ||
//TODO: handle new api here. This is just a placeholder. | ||
try { | ||
await handleFileUpload(file); | ||
setFocus(name); | ||
clearErrors(name); | ||
trigger(name); | ||
} catch (err) { | ||
//Handle new api error here | ||
} | ||
}} | ||
onClearClick={() => { | ||
//TODO | ||
console.log("clearing file"); | ||
avivtur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}} | ||
browseButtonText="Upload" | ||
/> | ||
)} | ||
/> | ||
|
||
{isFileRejected && ( | ||
<FormHelperText> | ||
<HelperText> | ||
<HelperTextItem variant="error"> | ||
You should select a YAML file. | ||
</HelperTextItem> | ||
</HelperText> | ||
</FormHelperText> | ||
)} | ||
<ActionGroup> | ||
<Button | ||
type="submit" | ||
aria-label="submit" | ||
id="import-questionnaire-submit-button" | ||
variant={ButtonVariant.primary} | ||
isDisabled={!isValid || isSubmitting || isValidating || !isDirty} | ||
> | ||
{t("actions.import")} | ||
</Button> | ||
</ActionGroup> | ||
</Form> | ||
); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see many "yamlFile" occurences here, maybe extract it to a const?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have moved to using the "name" provided by the controller component on subsequent occurrences. TS helps us here by inferring the types from the react hook form form values initialization.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I meant maybe to add at the top of the file adding something like:
const yamlID = "yamlFile"
or similar const name so if the type changes in the future, you can change it in only one place and not multiple places. If it's not possible because of the type inferring than please disregard this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The form values are defined in one place so I think that accomplishes what you are suggesting here. When we define the formValues, the internal TS support for react-hook-form allows us to infer the types from usage so that we will get a TS error if there is a spelling error or another issue.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
gotcha, thanks for the explanation 😄