-
Notifications
You must be signed in to change notification settings - Fork 5
fix: file upload re-upload issue #158
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
Closed
+184
−18
Closed
Changes from all commits
Commits
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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -17,7 +17,7 @@ | |
| // * LINK- https://github.com/adobe/aem-core-forms-components/blob/master/ui.af.apps/src/main/content/jcr_root/apps/core/fd/components/form/fileinput/v1/fileinput/fileinput.html | ||
| // ****************************************************************************** | ||
|
|
||
| import React, { useCallback, useRef, useState } from 'react'; | ||
| import React, { useCallback, useRef, useState, useEffect } from 'react'; | ||
| import { FileObject } from '@aemforms/af-core'; | ||
| import { getFileSizeInBytes } from '@aemforms/af-core'; | ||
| import { withRuleEngine } from '../utils/withRuleEngine'; | ||
|
|
@@ -41,19 +41,52 @@ const FileUpload = (props: PROPS) => { | |
| properties, | ||
| valid | ||
| } = props; | ||
| type LocalFile = { uid: string, file: File | FileObject }; | ||
|
|
||
| const generateUid = (seed?: string) => `${Date.now()}-${Math.random().toString(36).slice(2)}${seed ? `-${seed}` : ''}`; | ||
|
|
||
| const getIdentity = (f: any) => `${f?.name || ''}|${f?.size || ''}|${f?.lastModified || ''}|${f?.type || ''}`; | ||
|
|
||
| const uidMapRef = React.useRef<Map<string, string>>(new Map()); | ||
|
|
||
| const wrapWithUid = (items: Array<File | FileObject> | null | undefined): LocalFile[] => { | ||
| const list = items && (items instanceof Array ? items : [items]); | ||
| return (list || []).map((f) => { | ||
| const identity = getIdentity(f as any); | ||
| let uid = uidMapRef.current.get(identity); | ||
| if (!uid) { | ||
| uid = generateUid(identity); | ||
| uidMapRef.current.set(identity, uid); | ||
| } | ||
| return { uid, file: f }; | ||
| }); | ||
| }; | ||
|
|
||
| let val = value && (value instanceof Array ? value : [value]); | ||
| const [files, setFiles] = useState<FileObject[]>(val || []); | ||
| const [files, setFiles] = useState<LocalFile[]>(wrapWithUid(val as Array<File | FileObject>) || []); | ||
| const [ dragOver, setDragOver ] = useState(false); | ||
|
|
||
| // Sync internal state with external value prop only once (initial mount) | ||
| const didInitFromPropsRef = useRef(false); | ||
| useEffect(() => { | ||
| if (!didInitFromPropsRef.current) { | ||
| const newVal = value && (value instanceof Array ? value : [value]); | ||
| setFiles(wrapWithUid(newVal as Array<File | FileObject>)); | ||
| didInitFromPropsRef.current = true; | ||
| } | ||
| }, [value]); | ||
|
|
||
| const maxFileSizeInBytes = getFileSizeInBytes(maxFileSize); | ||
| let multiple = props.type?.endsWith('[]') ? { multiple: true } : {}; | ||
|
|
||
| // Dispatch value to the model. When field supports multiple values, send array; otherwise a single item | ||
| const fileChangeHandler = useCallback( | ||
| (files: Array<File | FileObject>) => { | ||
| (localFiles: Array<LocalFile>) => { | ||
| const plainFiles = localFiles.map(({ file }) => file); | ||
| if (multiple) { | ||
| props.dispatchChange(files); | ||
| props.dispatchChange(plainFiles); | ||
| } else { | ||
| props.dispatchChange(files.length > 0 ? files[0] : null); | ||
| props.dispatchChange(plainFiles.length > 0 ? plainFiles[0] : null); | ||
| } | ||
| }, | ||
| [multiple, props.dispatchChange] | ||
|
|
@@ -69,30 +102,54 @@ const FileUpload = (props: PROPS) => { | |
| setDragOver(false); | ||
| }; | ||
|
|
||
| // Handles file selection via input, drag/drop, or paste | ||
| const fileUploadHandler = useCallback((e) => { | ||
| e.preventDefault(); | ||
| const newFiles = Array.from<File>(e.dataTransfer?.files || e?.target?.files || e.clipboardData?.files || []); | ||
|
|
||
| // Clear the input value to allow re-uploading the same file again | ||
| if (e.target && e.target.type === 'file') { | ||
| e.target.value = ''; | ||
| } | ||
|
|
||
| if (newFiles?.length) { | ||
| const validFiles = newFiles.filter((file: File) => file.size <= maxFileSizeInBytes); | ||
| if (validFiles.length < newFiles.length) { | ||
| // Show constraint message for files with size exceeding the limit | ||
| alert(`${props.constraintMessages?.maxFileSize}`); | ||
| } | ||
| const updatedFiles = [...files, ...validFiles]; | ||
| setFiles(updatedFiles as FileObject[]); | ||
|
|
||
| // Avoid collapsing same-named files: append new entries without deduping | ||
| const wrappedNew = validFiles.map((f) => ({ uid: generateUid(`${f.name}-${f.size}-${f.lastModified}`), file: f })); | ||
| const updatedFiles: LocalFile[] = [...files, ...wrappedNew]; | ||
| setFiles(updatedFiles); | ||
| fileChangeHandler(updatedFiles); | ||
| } | ||
|
|
||
| setDragOver(false); | ||
| }, | ||
| [files, fileChangeHandler, maxFileSizeInBytes, props?.constraintMessages] | ||
| ); | ||
|
|
||
| // Removes one file by its unique id and clears the input to allow re-uploading the same file | ||
| const removeFile = useCallback( | ||
| (index: number) => { | ||
| (uid: string) => { | ||
| const index = files.findIndex((f) => f.uid === uid); | ||
| if (index === -1) {return;} | ||
| // remove identity mapping as well to avoid leaks | ||
| const toRemove = files[index]; | ||
| const identity = getIdentity((toRemove?.file as any)); | ||
| if (identity) { | ||
| uidMapRef.current.delete(identity); | ||
| } | ||
| const fileList = [...files]; | ||
| fileList.splice(index,1); | ||
| fileList.splice(index, 1); | ||
| setFiles(fileList); | ||
| fileChangeHandler(fileList); | ||
| // Clear the input value so the same file can be selected again | ||
| if (fileInputField.current) { | ||
| (fileInputField.current as HTMLInputElement).value = ''; | ||
| } | ||
| }, | ||
| [files, fileChangeHandler] | ||
| ); | ||
|
|
@@ -156,25 +213,31 @@ const FileUpload = (props: PROPS) => { | |
| </div> | ||
| <ul className="cmp-adaptiveform-fileinput__filelist"> | ||
| {files && | ||
| files?.map((item: FileObject, index) => ( | ||
| files?.map(({ file, uid }) => ( | ||
| <li | ||
| className="cmp-adaptiveform-fileinput__fileitem" | ||
| key={item?.name} | ||
| key={uid} | ||
| > | ||
| <span | ||
| className="cmp-adaptiveform-fileinput__filename" | ||
| aria-label={item?.name} | ||
| aria-label={(file as any)?.name} | ||
| > | ||
| {item?.name} | ||
| {(file as any)?.name} | ||
| </span> | ||
| <span className="cmp-adaptiveform-fileinput__fileendcontainer"> | ||
| <span className="cmp-adaptiveform-fileinput__filesize"> | ||
| {formatBytes(item?.size)} | ||
| {formatBytes((file as any)?.size)} | ||
| </span> | ||
| <button | ||
| onClick={() => removeFile(index)} | ||
| type="button" | ||
| onClick={(e) => { | ||
| // Prevent form submit bubbling when used inside a <form> | ||
| e.preventDefault(); | ||
| e.stopPropagation(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should be prevented at form level |
||
| removeFile(uid); | ||
| }} | ||
| className="cmp-adaptiveform-fileinput__filedelete" | ||
| role="button" | ||
| aria-label="Remove file" | ||
| > | ||
| x | ||
| </button> | ||
|
|
@@ -188,4 +251,4 @@ const FileUpload = (props: PROPS) => { | |
| ); | ||
| }; | ||
|
|
||
| export default withRuleEngine(FileUpload); | ||
| export default withRuleEngine(FileUpload); | ||
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.
We can upload multiple files at once as well, I don't think that use-case is handled here.
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.
Sir multiple files upload use case was already handled before, the 2 main issues which we were experiencing was re-uploading the removed file and uploading 2 files having same name.
the use case achieved.