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

Edit Dialog for Images #1151

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
504 changes: 317 additions & 187 deletions cypress/e2e/with_mock_data/items.cy.ts

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions src/api/api.types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,12 @@ export interface ImagePost {
description?: string | null;
}

export interface ObjectFilePatch {
file_name?: string;
title?: string | null;
description?: string | null;
}

export interface APIImage
extends Required<Omit<ImagePost, 'upload_file'>>,
CreatedModifiedMixin {
Expand Down
33 changes: 31 additions & 2 deletions src/api/images.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import {
CREATED_MODIFIED_TIME_VALUES,
hooksWrapperWithProviders,
} from '../testUtils';
import { APIImage } from './api.types';
import { useDeleteImage, useGetImage, useGetImages } from './images';
import { APIImage, ObjectFilePatch } from './api.types';
import {
useDeleteImage,
useGetImage,
useGetImages,
usePatchImage,
} from './images';

describe('images api functions', () => {
afterEach(() => {
Expand Down Expand Up @@ -67,6 +72,30 @@ describe('images api functions', () => {
});
});

describe('usePatchImage', () => {
let mockDataPatch: ObjectFilePatch;
beforeEach(() => {
mockDataPatch = {
file_name: 'edited_image.jpeg',
title: 'an edited title',
description: 'an edited description',
};
});
it('sends a patch request to edit an image and returns a successful response', async () => {
const { result } = renderHook(() => usePatchImage(), {
wrapper: hooksWrapperWithProviders(),
});

result.current.mutate({ id: '1', fileMetadata: mockDataPatch });
await waitFor(() => expect(result.current.isSuccess).toBeTruthy());

expect(result.current.data).toEqual({
...ImagesJSON[0],
...mockDataPatch,
});
});
});

describe('useDeleteImage', () => {
let mockDataView: APIImage;
beforeEach(() => {
Expand Down
28 changes: 27 additions & 1 deletion src/api/images.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {

import { AxiosError } from 'axios';
import { storageApi } from './api';
import { APIImage, APIImageWithURL } from './api.types';
import { APIImage, APIImageWithURL, ObjectFilePatch } from './api.types';

export const getImage = async (id: string): Promise<APIImageWithURL> => {
return storageApi.get(`/images/${id}`).then((response) => {
Expand Down Expand Up @@ -51,6 +51,32 @@ export const useGetImages = (
});
};

const patchImage = async (
id: string,
fileMetadata: ObjectFilePatch
): Promise<APIImage> => {
return storageApi
.patch<APIImage>(`/images/${id}`, fileMetadata)
.then((response) => response.data);
};

export const usePatchImage = (): UseMutationResult<
APIImage,
AxiosError,
{ id: string; fileMetadata: ObjectFilePatch }
> => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, fileMetadata }) => patchImage(id, fileMetadata),
onSuccess: (updatedImage: APIImage) => {
queryClient.invalidateQueries({ queryKey: ['Images'] });
queryClient.invalidateQueries({
queryKey: ['Image', updatedImage.id],
});
},
});
};

const deleteImage = async (id: string): Promise<void> => {
return storageApi
.delete(`/images/${id}`, {})
Expand Down
69 changes: 67 additions & 2 deletions src/common/attachments/uploadAttachmentsDialog.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import '@uppy/dashboard/dist/style.css';
import ProgressBar from '@uppy/progress-bar';
import { DashboardModal } from '@uppy/react';
import React from 'react';
import React, { useRef } from 'react';
import { usePostAttachmentMetadata } from '../../api/attachments';
import { getNonEmptyTrimmedString } from '../../utils';

Expand Down Expand Up @@ -90,6 +90,9 @@
uppy.on('file-removed', (file) => updateFileMetadata(file, true));
uppy.on('upload-success', (file) => updateFileMetadata(file));

const inputEl = useRef<HTMLInputElement>(null);
const divEl = useRef<HTMLDivElement>(null);

return (
<DashboardModal
open={open}
Expand All @@ -106,13 +109,75 @@
id: 'name',
name: 'File name',
placeholder: 'Enter file name',
render({ value, onChange, fieldCSSClasses, required }, h) {
const point = value.lastIndexOf('.');
const name = value.slice(0, point);
const extension = value.slice(point + 1);
console.log(fieldCSSClasses.text);
return h(
'div',
{
class: fieldCSSClasses.text,
onClick: () => inputEl.current && inputEl.current.focus(),
tabIndex: 0,
ref: divEl,
style: {
padding: 0,
display: 'inline-flex',
flexDirection: 'row',
flexWrap: 'nowrap',
justifyContent: 'space-between',
alignItems: 'center',
},
},
[
h('input', {
type: 'text',
id: 'uppy-Dashboard-FileCard-input-name',
value: name,
ref: inputEl,
class: fieldCSSClasses.text,
style: { border: 0, 'box-shadow': 'none', outline: 'none' },
required: required,
onFocus: () => {
if (divEl.current) {
divEl.current.style['boxShadow'] =
'rgba(18, 105, 207, 0.15) 0px 0px 0px 3px ';
divEl.current.style['borderColor'] =
'rgba(18, 105, 207, 0.6)';
}
},
onBlur: () => {
if (divEl.current) {
divEl.current.style['boxShadow'] = '';
divEl.current.style['borderColor'] = '';
}
},
onChange: (event: { currentTarget: { value: string } }) =>
onChange(event.currentTarget.value + '.' + extension),
}),
h(
'label',
{
for: 'uppy-Dashboard-FileCard-input-name',
style: {
color: 'rgb(82, 82, 82)',
colorScheme: 'light',
height: '31px',
padding: '5px',
},
},
'.' + extension
),
]
);
},

Check warning on line 174 in src/common/attachments/uploadAttachmentsDialog.component.tsx

View check run for this annotation

Codecov / codecov/patch

src/common/attachments/uploadAttachmentsDialog.component.tsx#L113-L174

Added lines #L113 - L174 were not covered by tests
},
{
id: 'title',
name: 'Title',
placeholder: 'Enter file title',
},

{
id: 'description',
name: 'Description',
Expand Down
162 changes: 162 additions & 0 deletions src/common/editFileDialog.component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent, { UserEvent } from '@testing-library/user-event';
import { http } from 'msw';
import { MockInstance } from 'vitest';
import { storageApi } from '../api/api';
import { usePatchImage } from '../api/images';
import handleIMS_APIError from '../handleIMS_APIError';
import ImagesJSON from '../mocks/Images.json';
import { server } from '../mocks/server';
import { renderComponentWithRouterProvider } from '../testUtils';
import EditFileDialog, { FileDialogProps } from './editFileDialog.component';

vi.mock('../handleIMS_APIError');

describe('Edit file dialog', () => {
const onClose = vi.fn();
let props: FileDialogProps;
let user: UserEvent;
const createView = () => {
return renderComponentWithRouterProvider(<EditFileDialog {...props} />);
};

beforeEach(() => {
props = {
open: true,
onClose: onClose,
fileType: 'Image',
usePatchFile: usePatchImage,
};
user = userEvent.setup();
});

afterEach(() => {
vi.clearAllMocks();
});
const modifyFileValues = (values: {
file_name?: string;
title?: string;
description?: string;
}) => {
if (values.file_name !== undefined)
fireEvent.change(screen.getByLabelText('File Name *'), {
target: { value: values.file_name },
});

if (values.title !== undefined)
fireEvent.change(screen.getByLabelText('Title'), {
target: { value: values.title },
});

if (values.description !== undefined)
fireEvent.change(screen.getByLabelText('Description'), {
target: { value: values.description },
});
};

describe('Edit an image', () => {
let axiosPatchSpy: MockInstance;
beforeEach(() => {
props = {
...props,
selectedFile: ImagesJSON[0],
};

axiosPatchSpy = vi.spyOn(storageApi, 'patch');
});

it('disables save button and shows circular progress indicator when request is pending', async () => {
server.use(
http.patch('/images/:id', () => {
return new Promise(() => {});
})
);

createView();

modifyFileValues({
file_name: 'Image A',
});

const saveButton = screen.getByRole('button', { name: 'Save' });
await user.click(saveButton);

expect(saveButton).toBeDisabled();
expect(await screen.findByRole('progressbar')).toBeInTheDocument();
});

it('Edits an image correctly', async () => {
createView();

// Checks if file extension is displayed. If it's editable, actual value will not match expected.
expect(screen.getByText('.png')).toBeInTheDocument();

modifyFileValues({
file_name: 'test_file_name.jpeg',
title: 'Test Title',
description: 'Test Description',
});

const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(axiosPatchSpy).toHaveBeenCalledWith('/images/1', {
file_name: 'test_file_name.jpeg.png',
title: 'Test Title',
description: 'Test Description',
});

expect(onClose).toHaveBeenCalled();
});

it('shows correct error message when no values are changed', async () => {
createView();

const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(
screen.getByText(
"There have been no changes made. Please change a field's value or press Cancel to exit."
)
).toBeInTheDocument();
});

it('shows error message if required fields are whitespace or their current value was removed', async () => {
createView();
modifyFileValues({
file_name: '',
});
const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(screen.getByText('Please enter a file name.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});

it('displays refresh page message and a CatchAllError request works correctly', async () => {
createView();
modifyFileValues({
file_name: 'Error 500',
});
const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(handleIMS_APIError).toHaveBeenCalled();
});

it('calls onClose when Close button is clicked', async () => {
createView();
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
await user.click(cancelButton);

await waitFor(() => {
expect(onClose).toHaveBeenCalled();
});
});
});
});
Loading
Loading