Skip to content
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

fix(RV-428): Fix change upload flow to reflect UI #494

Merged
merged 1 commit into from
Dec 27, 2024
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
19 changes: 10 additions & 9 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions frontend/src/components/ExtractUploadFile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ export const ExtractUploadFile: React.FC<ExtractUploadFileProps> = ({
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const files = Array.from(event.target.files);
if (files.length > 0) {
setUploadedFile([]);
clearFiles();
setHasError(false);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The setHasError is set to false here. Is there a try/catch logic that will handle errors in case the file that is uploaded is not a pdf?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handled outside in the extractProcess page

    try {
      setIsLoading(true);
      const newQueries = pdfs
        .map((pdf) => {
          return pdf.images.map((page, index) => {
            const selectedTemplateName = selectedTemplates.find(
              (temp) => temp.fileName === pdf.file,
            )?.templateName;
            return {
              pdfName: pdf.file,
              fieldNames: templates.find(
                (template) => template.name === selectedTemplateName,
              )?.pages[index].fieldNames as Field[],
              sourceImage: page,
              templateImage: templates.find(
                (template) => template.name === selectedTemplateName,
              )?.pages[index].templateImage as string,
            };
          });
        })
        .map((perBatch) =>
          perBatch.map(async (args) => ({
            name: args.pdfName,
            resp: await ImageToText({
              sourceImage: args.sourceImage,
              templateImage: args.templateImage,
              fieldNames: args.fieldNames,
            }),
          })),
        )
        .flat();
      const new_responses = await Promise.all(
        newQueries.map(async (query) => ({
          name: (await query).name,
          resp: (await query).resp,
        })),
      );
      const arrResults: { [key: string]: IResults } = {};

      new_responses.forEach((response) => {
        if (response.name in arrResults) {
          Object.keys(response.resp as ImageToTextResponse).forEach((key) => {
            arrResults[response.name][key] = {
              text: response.resp ? response.resp[key][0] : "",
              confidence: response.resp ? response.resp[key][1] : 0,
            };
          });
        } else {
          arrResults[response.name] = {};
          Object.keys(response.resp as ImageToTextResponse).forEach((key) => {
            arrResults[response.name][key] = {
              text: response.resp ? response.resp[key][0] : "",
              confidence: response.resp ? response.resp[key][1] : 0,
            };
          });
        }
      });

      const arrTransformedResponses: Submission[] = Object.keys(arrResults).map(
        (key) => {
          const transformedResponses: Submission = {
            template_name: templates[0].name,
            template_image: templates[0].pages[0].templateImage,
            file_name: key,
            file_image: pdfs.find((pdf) => pdf.file === key)
              ?.images[0] as string,
            results: arrResults[key],
          };
          return transformedResponses;
        },
      );

      localStorage.setItem(
        "arr_submissions",
        JSON.stringify(arrTransformedResponses),
      );

      // Update loading state and navigate
      setIsLoading(false);
      navigate("/extract/review");
    } catch (error) {
      console.error("Error processing templates:", error);
      setIsLoading(false);
      navigate("/extract/upload");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [navigate]);

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we navigate back to the start of the flow

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we def need to get design/product for the app when the user uploads not a pdf

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for now i just gated the input to only take in pdfs

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome!

}
setUploadedFile(files);
const filesObj: IFilesObj = { files };
localStorage.setItem("files", JSON.stringify(filesObj));
Expand Down Expand Up @@ -243,8 +248,9 @@ export const ExtractUploadFile: React.FC<ExtractUploadFileProps> = ({
>
{uploadedFile.length} file(s) selected
</label>
{!isUploadComplete && (
<FileInput
hidePreview
accept=".pdf"
multiple
onChange={handleChange}
id={`file-input-multiple-${id}-2`}
Expand All @@ -253,7 +259,6 @@ export const ExtractUploadFile: React.FC<ExtractUploadFileProps> = ({
chooseText="Change file(s)"
dragText=" "
/>
)}
</div>
<div
className="display-flex flex-column width-full height-full margin-bottom-2 margin-top-1"
Expand Down Expand Up @@ -352,6 +357,7 @@ export const ExtractUploadFile: React.FC<ExtractUploadFileProps> = ({
style={{ width: "80%" }}
>
<FileInput
accept=".pdf"
multiple
onChange={handleChange}
id={`file-input-multiple-${id}-1`}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/FileInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export const FileInputForwardRef: React.ForwardRefRenderFunction<
}
}
setFiles(fileArr);

console.log('change')
if (onChange) onChange(e);
};

Expand Down
7 changes: 4 additions & 3 deletions frontend/src/components/FileInput/file-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type FileInputProps = {
disabled?: boolean;
multiple?: boolean;
accept?: string;
hidePreview?: boolean;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
onDrop?: (e: React.DragEvent) => void;
};
Expand All @@ -43,6 +44,7 @@ export const FileInputForwardRef: React.ForwardRefRenderFunction<
multiple,
className,
accept,
hidePreview,
onChange,
onDrop,
...inputProps
Expand Down Expand Up @@ -103,15 +105,14 @@ export const FileInputForwardRef: React.ForwardRefRenderFunction<
filePreviews.push(
<FilePreview
key={key}
hidePreview
imageId={imageId}
file={files[parseInt(`${i}`)]}
/>,
);
}
}

const instructionClasses = classnames("usa-file-input__instructions", {
"display-none": filePreviews.length > 0,
});

const previewHeaderText =
Expand Down Expand Up @@ -187,7 +188,7 @@ export const FileInputForwardRef: React.ForwardRefRenderFunction<
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{filePreviews.length > 0 && (
{filePreviews.length > 0 && !hidePreview && (
<div
data-testid="file-input-preview-heading"
className="usa-file-input__preview-heading"
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/FileInput/file-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ const SPACER_GIF =
export const FilePreview = ({
imageId,
file,
hidePreview,
}: {
imageId: string;
file: File;
hidePreview?: boolean;
}): React.ReactElement => {
const [previewSrc, setPreviewSrc] = useState(SPACER_GIF);
const [showGenericPreview, setShowGenericPreview] = useState(false);
Expand Down Expand Up @@ -47,7 +49,7 @@ export const FilePreview = ({
return (
<div
data-testid="file-input-preview"
className="usa-file-input__preview"
className={`${hidePreview ? 'display-none' : ''} usa-file-input__preview`}
aria-hidden="true"
>
<img
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/UploadFile.scss
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
}

.dashed-container-upload {
height: 160px;
height: 245px;
}

.upload-back-button {
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/components/UploadFile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export const Uploadfile = () => {
const file = fileList[i];
filesObj["files"].push(file);
}
if(files.length > 0) {
clearFiles();
localStorage.setItem("files", JSON.stringify('{}'));
}
localStorage.setItem("files", JSON.stringify(filesObj));
addFile(event.target?.files[0]);
}
Expand Down Expand Up @@ -59,6 +63,7 @@ export const Uploadfile = () => {
<div className="display-flex flex-column flex-align-center width-full height-full">
<FileInput
onChange={handleChange}
accept=".pdf"
id={`file-input-${id}`}
className="padding-bottom-2"
name="file-input-single"
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/AnnotateTemplate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ const AnnotateTemplate: React.FC = () => {
<UploadHeader
title="Annotate new template"
onBack={() => navigate("/new-template/upload")}
onSubmit={handleSubmit}
/>
<Divider margin="0px" />
<div className="display-flex flex-justify-center padding-top-4">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ exports[`UploadTemplate component > matches the snapshot 1`] = `
data-testid="file-input-box"
/>
<input
accept=".pdf"
class="usa-file-input__input"
data-testid="file-input-input"
id="file-input-:r0:"
Expand Down
Loading