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

Likhith/74106/migrate file uploader to ts #22

Closed
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
1 change: 1 addition & 0 deletions packages/account/globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module '@binary-com/binary-document-uploader';
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { isDesktop, isMobile, PlatformContext } from '@deriv/shared';
import FileUploaderContainer from '../file-uploader-container';
import FileUploaderContainer, { TFileUploaderContainer } from '../file-uploader-container';

jest.mock('@deriv/components', () => {
const original_module = jest.requireActual('@deriv/components');
Expand All @@ -26,7 +26,7 @@ describe('<FileUploaderContainer />', () => {
jest.clearAllMocks();
});

const props = {
const props: TFileUploaderContainer = {
getSocket: jest.fn(),
onFileDrop: jest.fn(),
onRef: jest.fn(),
Expand All @@ -52,11 +52,7 @@ describe('<FileUploaderContainer />', () => {
});

it('should render FileUploaderContainer component if getSocket is not passed as prop', () => {
const new_props = {
onFileDrop: jest.fn(),
onRef: jest.fn(),
};
render(<FileUploaderContainer {...new_props} />);
render(<FileUploaderContainer {...props} />);
expect(screen.getByTestId('dt_file_uploader_container')).toBeInTheDocument();
});

Expand Down Expand Up @@ -109,7 +105,7 @@ describe('<FileUploaderContainer />', () => {
</PlatformContext.Provider>
);

expect(screen.getAllByText('mockedIcon')).toHaveLength(1);
expect(screen.getByText('mockedIcon')).toBeInTheDocument();
expect(screen.queryByText(file_size_msg)).not.toBeInTheDocument();
expect(screen.queryByText(file_type_msg)).not.toBeInTheDocument();
expect(screen.queryByText(file_time_msg)).not.toBeInTheDocument();
Expand All @@ -120,7 +116,7 @@ describe('<FileUploaderContainer />', () => {
it('should call ref function on rendering the component', () => {
render(
<PlatformContext.Provider value={{ is_appstore: true }}>
<FileUploaderContainer onRef={props.onRef} />
<FileUploaderContainer {...props} />
</PlatformContext.Provider>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ describe('<FileUploader />', () => {
jest.clearAllMocks();
});

const props = {
const props: {
onFileDrop: (file: File | undefined) => void;
getSocket: () => WebSocket;
ref: React.RefObject<HTMLElement>;
} = {
onFileDrop: jest.fn(),
getSocket: jest.fn(),
ref: React.createRef(),
ref: React.createRef<HTMLElement>(),
};

const large_file_error_msg = /file size should be 8mb or less/i;
Expand All @@ -48,11 +52,11 @@ describe('<FileUploader />', () => {

const file = new File(['hello'], 'hello.png', { type: 'image/png' });

const input = screen.getByTestId('dt_file_upload_input');
const input: HTMLInputElement = screen.getByTestId('dt_file_upload_input');
fireEvent.change(input, { target: { files: [file] } });

await waitFor(() => {
expect(input.files[0]).toBe(file);
expect(input?.files?.length && input.files[0]).toBe(file);
expect(input.files).toHaveLength(1);
});
});
Expand Down Expand Up @@ -101,12 +105,12 @@ describe('<FileUploader />', () => {
render(<FileUploader {...props} />);
const file = new File(['hello'], 'hello.png', { type: 'image/png' });

const input = screen.getByTestId('dt_file_upload_input');
const input: HTMLInputElement = screen.getByTestId('dt_file_upload_input');
fireEvent.change(input, { target: { files: [file] } });

await waitFor(() => {
expect(screen.getByText(/hello\.png/i)).toBeInTheDocument();
expect(input.files[0]).toBe(file);
expect(input?.files?.length && input.files[0]).toBe(file);
expect(input.files).toHaveLength(1);
});

Expand All @@ -133,11 +137,11 @@ describe('<FileUploader />', () => {
const blob = new Blob(['sample_data']);
const file = new File([blob], 'hello.pdf', { type: 'application/pdf' });

const input = screen.getByTestId('dt_file_upload_input');
const input: HTMLInputElement = screen.getByTestId('dt_file_upload_input');
fireEvent.change(input, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText(/hello\.pdf/i)).toBeInTheDocument();
expect(input.files[0]).toBe(file);
expect(input?.files?.length && input.files[0]).toBe(file);
});
props.ref.current.upload();
expect(compressImageFiles).toBeCalled();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Icon, Text } from '@deriv/components';
import { PlatformContext, isDesktop, WS } from '@deriv/shared';
import { Localize, localize } from '@deriv/translations';
import FileUploader from './file-uploader.jsx';
import FileUploader from './file-uploader';
import { TFile, TPlatformContext } from 'Types';

export type TFileUploaderContainer = {
is_description_enabled?: boolean;
getSocket: () => WebSocket;
onFileDrop: (file: TFile | undefined) => void;
onRef: (ref: React.RefObject<unknown> | undefined) => void;
};

const FileProperties = () => {
const properties = [
Expand Down Expand Up @@ -37,8 +44,13 @@ const FileProperties = () => {
);
};

const FileUploaderContainer = ({ is_description_enabled = true, getSocket, onFileDrop, onRef }) => {
const { is_appstore } = React.useContext(PlatformContext);
const FileUploaderContainer = ({
is_description_enabled = true,
getSocket,
onFileDrop,
onRef,
}: TFileUploaderContainer) => {
const { is_appstore } = React.useContext<Partial<TPlatformContext>>(PlatformContext);
const ref = React.useRef();

const getSocketFunc = getSocket ?? WS.getSocket;
Expand Down Expand Up @@ -124,11 +136,4 @@ const FileUploaderContainer = ({ is_description_enabled = true, getSocket, onFil
);
};

FileUploaderContainer.propTypes = {
is_description_enabled: PropTypes.bool,
getSocket: PropTypes.func,
onFileDrop: PropTypes.func,
onRef: PropTypes.func,
};

export default FileUploaderContainer;
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import DocumentUploader from '@binary-com/binary-document-uploader';
Expand All @@ -12,6 +11,11 @@ import {
max_document_size,
supported_filetypes,
} from '@deriv/shared';
import { TFile } from 'Types';

type TFileObject = {
file: TFile;
};

const UploadMessage = () => {
return (
Expand All @@ -23,34 +27,38 @@ const UploadMessage = () => {
</React.Fragment>
);
};
const fileReadErrorMessage = filename => {

const fileReadErrorMessage = (filename: string) => {
return localize('Unable to read file {{name}}', { name: filename });
};

const FileUploader = React.forwardRef(({ onFileDrop, getSocket }, ref) => {
const FileUploader = React.forwardRef<
HTMLElement,
{ onFileDrop: (file: TFile | undefined) => void; getSocket: () => WebSocket }
>(({ onFileDrop, getSocket }, ref) => {
const [document_file, setDocumentFile] = useStateCallback({ files: [], error_message: null });

const handleAcceptedFiles = files => {
const handleAcceptedFiles = (files: TFileObject[]) => {
if (files.length > 0) {
setDocumentFile({ files, error_message: null }, file => {
setDocumentFile({ files, error_message: null }, (file: TFile) => {
onFileDrop(file);
});
}
};

const handleRejectedFiles = files => {
const handleRejectedFiles = (files: TFileObject[]) => {
const is_file_too_large = files.length > 0 && files[0].file.size > max_document_size;
const supported_files = files.filter(each_file => getSupportedFiles(each_file.file.name));
const error_message =
is_file_too_large && supported_files.length > 0
? localize('File size should be 8MB or less')
: localize('File uploaded is not supported');

setDocumentFile({ files, error_message }, file => onFileDrop(file));
setDocumentFile({ files, error_message }, (file: TFile) => onFileDrop(file));
};

const removeFile = () => {
setDocumentFile({ files: [], error_message: null }, file => onFileDrop(file));
setDocumentFile({ files: [], error_message: null }, (file: TFile) => onFileDrop(file));
};

const upload = () => {
Expand All @@ -77,7 +85,9 @@ const FileUploader = React.forwardRef(({ onFileDrop, getSocket }, ref) => {
}

// send files
const uploader_promise = uploader.upload(processed_files[0]).then(api_response => api_response);
const uploader_promise = uploader
.upload(processed_files[0])
.then((api_response: unknown) => api_response);
resolve(uploader_promise);
});
});
Expand Down Expand Up @@ -122,9 +132,4 @@ const FileUploader = React.forwardRef(({ onFileDrop, getSocket }, ref) => {

FileUploader.displayName = 'FileUploader';

FileUploader.propTypes = {
onFileDrop: PropTypes.func,
getSocket: PropTypes.func,
};

export default FileUploader;
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import FileUploaderContainer from './file-uploader-container.jsx';
import FileUploaderContainer from './file-uploader-container';

export default FileUploaderContainer;
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import PropTypes from 'prop-types';
import DocumentUploader from '@binary-com/binary-document-uploader';
import { localize } from '@deriv/translations';
import { compressImageFiles, readFiles, DOCUMENT_TYPE, PAGE_TYPE } from '@deriv/shared';
import { TFile } from 'Types';

type TDocumentSetting = {
documentType: keyof typeof DOCUMENT_TYPE;
pageType: keyof typeof PAGE_TYPE;
expirationDate: string;
documentId: string;
lifetimeValid: boolean;
};

type TProcessedFile = TFile & TDocumentSetting & { message: string };

const fileReadErrorMessage = filename => {
const fileReadErrorMessage = (filename: string) => {
return localize('Unable to read file {{name}}', { name: filename });
};

const uploadFile = (file, getSocket, settings) =>
new Promise((resolve, reject) => {
const uploadFile = (file: File, getSocket: () => WebSocket, settings: TDocumentSetting) => {
return new Promise((resolve, reject) => {
if (!file) {
reject();
}
Expand All @@ -18,9 +28,9 @@ const uploadFile = (file, getSocket, settings) =>

let is_file_error = false;

compressImageFiles([file]).then(files_to_process => {
readFiles(files_to_process, fileReadErrorMessage, settings).then(processed_files => {
processed_files.forEach(item => {
compressImageFiles([file]).then((files_to_process: File[]) => {
readFiles(files_to_process, fileReadErrorMessage, settings).then((processed_files: TProcessedFile[]) => {
processed_files.forEach((item: TProcessedFile) => {
if (item.message) {
is_file_error = true;
reject(item);
Expand All @@ -36,17 +46,6 @@ const uploadFile = (file, getSocket, settings) =>
});
});
});

uploadFile.propTypes = {
file: PropTypes.element.isRequired,
getSocket: PropTypes.func.isRequired,
settings: PropTypes.shape({
documentType: PropTypes.oneOf(Object.values(DOCUMENT_TYPE)).isRequired,
pageType: PropTypes.oneOf(Object.values(PAGE_TYPE)),
expirationDate: PropTypes.string,
documentId: PropTypes.string,
lifetimeValid: PropTypes.bool,
}),
};

export default uploadFile;
15 changes: 15 additions & 0 deletions packages/account/src/Types/common-prop.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,18 @@ export type TToken = {
scopes: string[];
token: string;
};

export type TFile = {
path: string;
lastModified: number;
lastModifiedDate: Date;
name: string;
size: number;
type: string;
webkitRelativePath: string;
};

export type TPlatformContext = {
is_appstore?: boolean;
displayName?: string;
};
5 changes: 2 additions & 3 deletions packages/account/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@
"Modules/*": ["src/Modules/*"],
"Sections/*": ["src/Sections/*"],
"Stores/*": ["src/Stores/*"],
"Styles/*": ["src/Styles/*"],
"Types": ["src/Types"],
"@deriv/*": ["../*/src"]
"@deriv/*": ["../*/src"],
}
},
"include": ["src", "globals.d.ts"]
"include": ["src","globals.d.ts"]
}
2 changes: 1 addition & 1 deletion packages/p2p/src/stores/my-profile-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ export default class MyProfileStore extends BaseStore {
this.setIsConfirmDeleteModalOpen(true);
}
}

onSubmit() {
const { general_store } = this.root_store;

Expand Down