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

SWC-7064 - EntityUpload component #1373

Merged
merged 9 commits into from
Nov 14, 2024
4 changes: 0 additions & 4 deletions packages/synapse-react-client/.storybook/main.mts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,6 @@ const config: StorybookConfig = {

return mergeConfig(config, customStorybookConfig)
},

docs: {
autodocs: false,
},
Comment on lines -68 to -71
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

remove deprecated storybook argument that was blocking 'autodocs' generation

}

export default config
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Meta, StoryObj } from '@storybook/react'
import mockProjectEntityData from '../../mocks/entity/mockProject'
import { EntityUpload } from './EntityUpload'

const meta = {
title: 'Synapse/Upload/EntityUpload',
component: EntityUpload,
} satisfies Meta
export default meta
type Story = StoryObj<typeof meta>

export const Demo: Story = {
args: {
entityId: mockProjectEntityData.entity.id,
},
parameters: {
stack: 'mock',
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,343 @@
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'
import mockFileEntity from '../../mocks/entity/mockFileEntity'
import mockProject from '../../mocks/entity/mockProject'
import {
mockExternalObjectStoreUploadDestination,
mockExternalS3UploadDestination,
mockSynapseStorageUploadDestination,
} from '../../mocks/mock_upload_destination'
import {
useGetDefaultUploadDestination,
useGetEntity,
} from '../../synapse-queries/index'
import { getUseQuerySuccessMock } from '../../testutils/ReactQueryMockUtils'
import { createWrapper } from '../../testutils/TestingLibraryUtils'
import {
useUploadFileEntities,
UseUploadFileEntitiesReturn,
} from '../../utils/hooks/useUploadFileEntity/useUploadFileEntities'
import {
EntityUpload,
EntityUploadHandle,
EntityUploadProps,
} from './EntityUpload'
import { FileUploadProgress } from './FileUploadProgress'

jest.mock(
'../../utils/hooks/useUploadFileEntity/useUploadFileEntities',
() => ({
useUploadFileEntities: jest.fn(),
}),
)

jest.mock('../../synapse-queries/entity/useEntity', () => ({
useGetEntity: jest.fn(),
}))

jest.mock('../../synapse-queries/file/useUploadDestination.ts', () => ({
useGetDefaultUploadDestination: jest.fn(),
}))

jest.mock('./FileUploadProgress', () => ({
FILE_UPLOAD_PROGRESS_COMPONENT_HEIGHT_PX: 100,
FileUploadProgress: jest.fn(() => <div data-testid={'FileUploadProgress'} />),
}))

const mockFileUploadProgress = jest.mocked(FileUploadProgress)
const mockUseUploadFileEntities = jest.mocked(useUploadFileEntities)
const mockUseGetEntity = jest.mocked(useGetEntity)
const mockUseGetDefaultUploadDestination = jest.mocked(
useGetDefaultUploadDestination,
)

const mockUseUploadFileEntitiesReturn = {
state: 'WAITING',
isPrecheckingUpload: false,
activePrompts: [],
activeUploadCount: 0,
uploadProgress: [],
initiateUpload: jest.fn(),
} satisfies UseUploadFileEntitiesReturn

describe('EntityUpload', () => {
function renderComponent(propOverrides: Partial<EntityUploadProps> = {}) {
const user = userEvent.setup()
const ref = React.createRef<EntityUploadHandle>()
const result = render(
<EntityUpload
ref={ref}
entityId={mockProject.entity.id}
{...propOverrides}
/>,
{
wrapper: createWrapper(),
},
)

return { user, ref, result }
}

beforeEach(() => {
jest.clearAllMocks()

mockUseUploadFileEntities.mockReturnValue(mockUseUploadFileEntitiesReturn)
mockUseGetEntity.mockReturnValue(getUseQuerySuccessMock(mockProject.entity))
mockUseGetDefaultUploadDestination.mockReturnValue(
getUseQuerySuccessMock(mockSynapseStorageUploadDestination),
)
})

it('supports selecting files for upload into a container', async () => {
const { user, result } = renderComponent()

// Verify the user can select either files or a folder -- we cannot test clicking these buttons with testing-library, however
await user.click(await screen.findByText('Click to upload'))
await screen.findByRole('menuitem', { name: 'Files' })
await screen.findByRole('menuitem', { name: 'Folder' })

const fileInput = result.container.querySelector<HTMLInputElement>(
'input[type="file"][id=filesToUpload]',
)!
expect(fileInput).toBeInTheDocument()
expect(fileInput).toHaveAttribute('multiple')
const filesToUpload = [
new File(['contents'], 'file1.txt'),
new File(['contents'], 'file2.txt'),
]
await user.upload(fileInput, filesToUpload)

expect(mockUseUploadFileEntitiesReturn.initiateUpload).toHaveBeenCalledWith(
[
{ file: filesToUpload[0], rootContainerId: mockProject.entity.id },
{ file: filesToUpload[1], rootContainerId: mockProject.entity.id },
],
)
})

it('supports uploading a new version of a specified FileEntity', async () => {
mockUseGetEntity.mockReturnValue(
getUseQuerySuccessMock(mockFileEntity.entity),
)
const { user, result } = renderComponent({
entityId: mockFileEntity.entity.id,
})

const fileInput = result.container.querySelector<HTMLInputElement>(
'input[type="file"][id=filesToUpload]',
)!
expect(fileInput).toBeInTheDocument()
const fileToUpload = new File(['contents'], 'file1.txt')

await user.upload(fileInput, fileToUpload)

expect(mockUseUploadFileEntitiesReturn.initiateUpload).toHaveBeenCalledWith(
[{ file: fileToUpload, existingEntityId: mockFileEntity.entity.id }],
)
})

it('does not support selecting a folder when updating a specified FileEntity', async () => {
mockUseGetEntity.mockReturnValue(
getUseQuerySuccessMock(mockFileEntity.entity),
)
const { user, result } = renderComponent({
entityId: mockFileEntity.entity.id,
})

// Verify no menu options appear, because uploading
await user.click(await screen.findByText('Click to upload'))
expect(
screen.queryByRole('menuitem', { name: 'Files' }),
).not.toBeInTheDocument()
expect(
screen.queryByRole('menuitem', { name: 'Folder' }),
).not.toBeInTheDocument()

// Verify that the file input does not support selecting multiple files
const fileInput = result.container.querySelector<HTMLInputElement>(
'input[type="file"][id=filesToUpload]',
)!
expect(fileInput).toBeInTheDocument()
expect(fileInput).not.toHaveAttribute('multiple')
})

it('shows uploads in progress', async () => {
const hookReturnValue = {
...mockUseUploadFileEntitiesReturn,
state: 'UPLOADING',
activeUploadCount: 1,
uploadProgress: [
{
file: new File(['contents'], 'file1.txt'),
progress: { value: 1024 * 1024 * 50, total: 1024 * 1024 * 100 },
status: 'UPLOADING',
cancel: jest.fn(),
pause: jest.fn(),
resume: jest.fn(),
remove: jest.fn(),
failureReason: undefined,
},
],
} satisfies UseUploadFileEntitiesReturn
mockUseUploadFileEntities.mockReturnValue(hookReturnValue)

renderComponent({
entityId: mockFileEntity.entity.id,
})

await screen.findByTestId('FileUploadProgress')
expect(mockFileUploadProgress).toHaveBeenLastCalledWith(
{
status: 'UPLOADING',
fileName: 'file1.txt',
totalSizeInBytes: hookReturnValue.uploadProgress[0].file.size,
uploadedSizeInBytes: hookReturnValue.uploadProgress[0].file.size / 2,
onCancel: hookReturnValue.uploadProgress[0].cancel,
onPause: hookReturnValue.uploadProgress[0].pause,
onResume: hookReturnValue.uploadProgress[0].resume,
onRemove: hookReturnValue.uploadProgress[0].remove,
errorMessage: undefined,
},
expect.anything(),
)

await screen.findByText('Uploading 1 Item')
})

it('displays a prompt to the user', async () => {
const hookReturnValue = {
...mockUseUploadFileEntitiesReturn,
state: 'PROMPT_USER',
activePrompts: [
{
info: {
type: 'CONFIRM_NEW_VERSION',
fileName: 'file1.txt',
existingEntityId: 'syn123',
},
onConfirmAll: jest.fn(),
onConfirm: jest.fn(),
onSkip: jest.fn(),
onCancelAll: jest.fn(),
},
{
info: {
type: 'CONFIRM_NEW_VERSION',
fileName: 'file2.txt',
existingEntityId: 'syn456',
},
onConfirmAll: jest.fn(),
onConfirm: jest.fn(),
onSkip: jest.fn(),
onCancelAll: jest.fn(),
},
],
} satisfies UseUploadFileEntitiesReturn
mockUseUploadFileEntities.mockReturnValue(hookReturnValue)

const { user } = renderComponent({
entityId: mockFileEntity.entity.id,
})

const dialog = await screen.findByRole('dialog')
within(dialog).getByText('Update existing file?')
within(dialog).getByText(
'A file named "file1.txt" (syn123) already exists in this location. Do you want to update the existing file and create a new version?',
)

Copy link
Member

Choose a reason for hiding this comment

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

May want to add a quick check before click to verify baseline (for each of these checks):
expect(hookReturnValue.activePrompts[0].onConfirm).toHaveBeenCalledTimes(0)

expect(hookReturnValue.activePrompts[0].onConfirm).toHaveBeenCalledTimes(0)
await user.click(screen.getByRole('button', { name: 'Yes' }))
expect(hookReturnValue.activePrompts[0].onConfirm).toHaveBeenCalledTimes(1)

expect(hookReturnValue.activePrompts[0].onSkip).toHaveBeenCalledTimes(0)
await user.click(screen.getByRole('button', { name: 'No' }))
expect(hookReturnValue.activePrompts[0].onSkip).toHaveBeenCalledTimes(1)

expect(hookReturnValue.activePrompts[0].onCancelAll).toHaveBeenCalledTimes(
0,
)
await user.click(screen.getByRole('button', { name: 'Cancel All Uploads' }))
expect(hookReturnValue.activePrompts[0].onCancelAll).toHaveBeenCalledTimes(
1,
)

expect(hookReturnValue.activePrompts[0].onConfirmAll).toHaveBeenCalledTimes(
0,
)
await user.click(
screen.getByLabelText(
'Also update 1 other uploaded file that already exists',
),
)
await user.click(screen.getByRole('button', { name: 'Yes' }))
expect(hookReturnValue.activePrompts[0].onConfirmAll).toHaveBeenCalledTimes(
1,
)
})

it('displays a banner for an alternative storage location', async () => {
const bannerText = 'a rad custom storage location'
mockUseGetDefaultUploadDestination.mockReturnValue(
getUseQuerySuccessMock({
...mockExternalS3UploadDestination,
banner: bannerText,
}),
)

renderComponent()

await screen.findByText('All uploaded files will be stored in:', {
exact: false,
})
await screen.findByText(bannerText, { exact: false })
})

it('allows entering AWS credentials when the UploadDestination is an ExternalObjectStoreUploadDestination', async () => {
mockUseGetDefaultUploadDestination.mockReturnValue(
getUseQuerySuccessMock(mockExternalObjectStoreUploadDestination),
)

const accessKeyValue = 'myAccessKey'
const secretKeyValue = 'mySecretKey'

const { user } = renderComponent()

const accessKeyInput = await screen.findByLabelText('Access Key')
const secretKeyInput = await screen.findByLabelText('Secret Key')
await screen.findByText(
'Keys are used to locally sign a web request. They are not transmitted or stored by Synapse.',
)

await user.type(accessKeyInput, accessKeyValue)
await user.type(secretKeyInput, secretKeyValue)

await waitFor(() => {
expect(mockUseUploadFileEntities).toHaveBeenLastCalledWith(
mockProject.entity.id,
accessKeyValue,
secretKeyValue,
)
})
})

it('supports upload via programmatic handle', () => {
const { ref } = renderComponent()

const filesToUpload = [
new File(['contents'], 'file1.txt'),
new File(['contents'], 'file2.txt'),
]

act(() => {
ref.current?.handleUploads(filesToUpload)
})

expect(mockUseUploadFileEntitiesReturn.initiateUpload).toHaveBeenCalledWith(
[
{ file: filesToUpload[0], rootContainerId: mockProject.entity.id },
{ file: filesToUpload[1], rootContainerId: mockProject.entity.id },
],
)
})
})
Loading
Loading