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

feat(mui-file-selector): add support for dropping files and fix removing #577

Merged
merged 16 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
3 changes: 2 additions & 1 deletion apps/element-storybook/.storybook/preview.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react';
import { themes } from '@storybook/theming';
import { Preview } from '@storybook/react';
import { Title, Subtitle, Description, Primary, Controls, Stories, useOf } from '@storybook/blocks';
Expand Down Expand Up @@ -37,7 +38,7 @@ const preview: Preview = {
theme: themes.light,
source: {
excludeDecorators: true,
type: 'code'
type: 'code',
},
page: () => {
// https://github.com/storybookjs/storybook/blob/next/code/ui/blocks/src/blocks/DocsPage.tsx
Expand Down
4 changes: 2 additions & 2 deletions packages/file-selector/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@
"@availity/mui-list": "workspace:^",
"@availity/mui-progress": "workspace:^",
"@availity/mui-typography": "workspace:^",
"@availity/upload-core": "^6.1.1",
"@availity/upload-core": "7.0.0-alpha.1",
"@tanstack/react-query": "^4.36.1",
"react-dropzone": "^11.7.1",
"react-hook-form": "^7.51.3",
"tus-js-client": "4.2.3",
"uuid": "^9.0.1"
},
"devDependencies": {
"@mui/material": "^5.15.15",
"@types/tus-js-client": "^1.8.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"tsup": "^8.0.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/file-selector/src/lib/Dropzone.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('Dropzone', () => {
render(
<QueryClientProvider client={client}>
<TestForm>
<Dropzone name="test" bucketId="test" customerId="123" clientId="test" maxSize={1000} />
<Dropzone name="test" maxSize={1000} totalSize={10} setTotalSize={jest.fn()} />
</TestForm>
</QueryClientProvider>
);
Expand Down
124 changes: 29 additions & 95 deletions packages/file-selector/src/lib/Dropzone.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { ChangeEvent, MouseEvent, useCallback, useState } from 'react';
import { useDropzone, FileRejection, DropEvent } from 'react-dropzone';
import { v4 as uuid } from 'uuid';
import { Dispatch, MouseEvent, useCallback } from 'react';
import { useDropzone, FileRejection } from 'react-dropzone';
import { Divider } from '@availity/mui-divider';
import { CloudDownloadIcon } from '@availity/mui-icon';
import { Box, Stack } from '@availity/mui-layout';
import { Typography } from '@availity/mui-typography';
import Upload, { Options } from '@availity/upload-core';

import { FilePickerBtn } from './FilePickerBtn';
import { useFormContext } from 'react-hook-form';

const outerBoxStyles = {
backgroundColor: 'background.canvas',
Expand All @@ -21,131 +20,64 @@ const innerBoxStyles = {
height: '100%',
};

const CLOUD_URL = '/cloud/web/appl/vault/upload/v1/resumable';

export type DropzoneProps = {
name: string;
bucketId: string;
jordan-a-young marked this conversation as resolved.
Show resolved Hide resolved
clientId: string;
customerId: string;
allowedFileNameCharacters?: string;
allowedFileTypes?: `.${string}`[];
deliverFileOnSubmit?: boolean;
deliveryChannel?: string;
// deliverFileOnSubmit?: boolean;
// deliveryChannel?: string;
disabled?: boolean;
endpoint?: string;
fileDeliveryMetadata?: Record<string, unknown> | ((file: Upload) => Record<string, unknown>);
// endpoint?: string;
// fileDeliveryMetadata?: Record<string, unknown> | ((file: Upload) => Record<string, unknown>);
getDropRejectionMessages?: (fileRejectsions: FileRejection[]) => void;
isCloud?: boolean;
// isCloud?: boolean;
maxFiles?: number;
maxSize?: number;
multiple?: boolean;
onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
onChange?: (files: File[]) => void;
onClick?: (event: MouseEvent<HTMLButtonElement>) => void;
totalSize: number;
setTotalSize: Dispatch<React.SetStateAction<number>>;
// onDeliveryError?: (responses: unknown[]) => void;
// onDeliverySuccess?: (responses: unknown[]) => void;
onFileDelivery?: (upload: Upload) => void;
onFilePreUpload?: ((upload: Upload) => boolean)[];
// onFileDelivery?: (upload: Upload) => void;
// onFilePreUpload?: ((upload: Upload) => boolean)[];
};

export const Dropzone = ({
allowedFileNameCharacters,
// allowedFileNameCharacters,
allowedFileTypes = [],
bucketId,
clientId,
customerId,
deliveryChannel,
// deliverFileOnSubmit,
fileDeliveryMetadata,
disabled,
endpoint,
getDropRejectionMessages,
isCloud,
maxFiles,
maxSize,
multiple,
name,
onChange,
onClick,
onFilePreUpload,
onFileDelivery,
setTotalSize,
totalSize,
}: DropzoneProps) => {
const [totalSize, setTotalSize] = useState(0);
const [files, setFiles] = useState<Upload[]>([]);
const { setValue, watch } = useFormContext();

const onDrop = useCallback(
(acceptedFiles: File[], fileRejections: FileRejection[], dropEvent: DropEvent) => {
// Do something with the files
console.log('Dropzone acceptedFiles:', acceptedFiles);
console.log('Dropzone fileRejections:', fileRejections);
console.log('Dropzone dropEvent:', dropEvent);

(acceptedFiles: File[], fileRejections: FileRejection[]) => {
// Verify we have not exceeded max number of files
if (maxFiles && acceptedFiles.length > maxFiles) {
acceptedFiles.slice(0, Math.max(9, maxFiles));
}

const uploads = acceptedFiles.map((file) => {
const options: Options = {
bucketId,
customerId,
clientId,
fileTypes: allowedFileTypes,
maxSize,
allowedFileNameCharacters,
};

if (onFilePreUpload) options.onPreStart = onFilePreUpload;
if (endpoint) options.endpoint = endpoint;
if (isCloud) options.endpoint = CLOUD_URL;

const upload = new Upload(file, options);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
upload.id = `${upload.id}-${uuid()}`;
let newSize = 0;
for (const file of acceptedFiles) {
newSize += file.size;
}

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (file.dropRejectionMessage) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
upload.errorMessage = file.dropRejectionMessage;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
} else if (maxSize && totalSize + newFilesTotalSize + upload.file.size > maxSize) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
upload.errorMessage = 'Total documents size is too large';
} else {
upload.start();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
newFilesTotalSize += upload.file.size;
}
if (onFileDelivery) {
onFileDelivery(upload);
} else if (deliveryChannel && fileDeliveryMetadata) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// upload.onSuccess.push(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// if (upload?.references?.[0]) {
// allow form to revalidate when upload is complete
// setFieldTouched(name, true);
// deliver upon upload complete, not form submit
// if (!deliverFileOnSubmit) {
// callFileDelivery(upload);
// }
// }
// });
}
setTotalSize((prev) => prev + newSize);

return upload;
});
const previous = watch(name) ?? [];

// Set uploads somewhere. state?
setFiles(files);
// Set accepted files to form context
setValue(name, previous.concat(acceptedFiles));

if (getDropRejectionMessages) getDropRejectionMessages(fileRejections);
},
Expand Down Expand Up @@ -174,8 +106,10 @@ export const Dropzone = ({
inputProps={getInputProps({
multiple,
accept,
onChange,
})}
onChange={onChange}
setTotalSize={setTotalSize}
totalSize={totalSize}
/>
</>
</Stack>
Expand Down
50 changes: 42 additions & 8 deletions packages/file-selector/src/lib/FileList.test.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,50 @@
import { render } from '@testing-library/react';
import { screen, render, fireEvent, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import { FileList } from './FileList';

describe('FileList', () => {
test('should render successfully', () => {
test('should render successfully', async () => {
const mockFile = new File(['file content'], 'mock.txt', { type: 'text/plain' });

render(
<FileList
uploads={[]}
onRemoveFile={() => {
// noop
}}
/>
<QueryClientProvider client={new QueryClient()}>
<FileList
files={[mockFile]}
options={{ bucketId: '123', customerId: '123', clientId: '123' }}
onRemoveFile={() => {
// noop
}}
/>
</QueryClientProvider>
);

await waitFor(() => {
expect(screen.getByText('mock.txt')).toBeDefined();
});
});

test('should call onRemoveFile', async () => {
const mockRemove = jest.fn();
const mockFile = new File(['file content'], 'mock.txt', { type: 'text/plain' });

render(
<QueryClientProvider client={new QueryClient()}>
<FileList
files={[mockFile]}
options={{ bucketId: '123', customerId: '123', clientId: '123' }}
onRemoveFile={(id) => {
mockRemove(id);
}}
/>
</QueryClientProvider>
);

await waitFor(() => {
expect(screen.getByText('mock.txt')).toBeDefined();
});

fireEvent.click(screen.getByRole('button'));
expect(mockRemove).toHaveBeenCalled();
});
});
49 changes: 29 additions & 20 deletions packages/file-selector/src/lib/FileList.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import type Upload from '@availity/upload-core';
import type { default as Upload, UploadOptions } from '@availity/upload-core';
import { List, ListItem, ListItemText, ListItemIcon, ListItemButton } from '@availity/mui-list';
import { DeleteIcon, FileIcon } from '@availity/mui-icon';
import { Grid } from '@availity/mui-layout';

import { UploadProgressBar } from './UploadProgressBar';
import { formatBytes, getFileExtIcon } from './util';
import { useUploadCore } from './useUploadCore';

type FileRowProps = {
/** The upload instance returned by creating a new Upload via @availity/upload-core. */
upload: Upload;
/** Callback called when file is removed. The callback is passed the id of the file that was removed. */
onRemoveFile: (id: string) => void;
onRemoveFile: (id: string, upload: Upload) => void;
/** The upload instance returned by creating a new Upload via @availity/upload-core. */
// upload: Upload;
file: File;
options: UploadOptions;
};

const FileRow = ({ upload, onRemoveFile }: FileRowProps) => {
const { ext, icon } = getFileExtIcon(upload.file.name);
const FileRow = ({ file, options, onRemoveFile }: FileRowProps) => {
const { ext, icon } = getFileExtIcon(file.name);
console.log('ext, icon:', ext, icon);

const { data: upload } = useUploadCore(file, options);

if (!upload) return null;

return (
<ListItem>
<>
<Grid container spacing={2} alignItems="center" justifyContent="space-between" width="100%">
<Grid xs={1}>
<ListItemIcon>
Expand All @@ -35,35 +42,37 @@ const FileRow = ({ upload, onRemoveFile }: FileRowProps) => {
<UploadProgressBar upload={upload} />
</Grid>
<Grid xs={1}>
<ListItemButton>
<ListItemIcon
onClick={() => {
onRemoveFile(upload.id);
}}
>
<ListItemButton
onClick={() => {
onRemoveFile(upload.id, upload);
}}
>
<ListItemIcon>
<DeleteIcon />
</ListItemIcon>
</ListItemButton>
</Grid>
</Grid>
</ListItem>
</>
);
};

export type FileListProps = {
/** List of Upload objects */
uploads: Upload[];
// uploads: Upload[];
/** Callback called when file is removed. The callback is passed the id of the file that was removed. */
onRemoveFile: (id: string) => void;
files: File[];
options: UploadOptions;
onRemoveFile: (id: string, upload: Upload) => void;
};

export const FileList = ({ uploads, onRemoveFile }: FileListProps) => {
if (uploads.length === 0) return null;
export const FileList = ({ files, options, onRemoveFile }: FileListProps) => {
if (files.length === 0) return null;

return (
<List>
{uploads.map((upload) => {
return <FileRow key={upload.id} upload={upload} onRemoveFile={onRemoveFile} />;
{files.map((file) => {
return <FileRow key={file.name} file={file} options={options} onRemoveFile={onRemoveFile} />;
})}
</List>
);
Expand Down
2 changes: 1 addition & 1 deletion packages/file-selector/src/lib/FilePickerBtn.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const TestForm = () => {

return (
<FormProvider {...methods}>
<FilePickerBtn name="test" inputProps={{ ref }} />
<FilePickerBtn name="test" inputProps={{ ref }} totalSize={100} setTotalSize={jest.fn()} />
</FormProvider>
);
};
Expand Down
Loading
Loading