Skip to content
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"zod": "^3.23.6"
},
"dependencies": {
"@douglasneuroinformatics/libjs": "^1.1.0",
"@douglasneuroinformatics/libjs": "^1.2.0",
"@douglasneuroinformatics/libui-form-types": "^0.11.0",
"@radix-ui/react-accordion": "^1.2.1",
"@radix-ui/react-alert-dialog": "^1.1.2",
Expand Down
14 changes: 7 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 10 additions & 4 deletions src/components/Form/DateField/DateField.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { toBasicISOString } from '@douglasneuroinformatics/libjs';
import { toBasicISOString, toLocalISOString } from '@douglasneuroinformatics/libjs';
import { getByText, render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { DateField } from './DateField';

Expand All @@ -10,6 +10,12 @@ describe('DateField', () => {
const setValue = vi.fn();

beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2025, 0, 1, 22));
});

afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});

Expand Down Expand Up @@ -78,14 +84,14 @@ describe('DateField', () => {
datepicker = screen.getByTestId('datepicker');
await userEvent.click(getByText(datepicker, '1'));
expectedDate = new Date(new Date().setDate(1));
expectedDateString = toBasicISOString(expectedDate);
expectedDateString = toLocalISOString(expectedDate).split('T')[0]!;
expect(toBasicISOString(setValue.mock.lastCall?.[0])).toBe(expectedDateString);

await userEvent.click(input);
datepicker = screen.getByTestId('datepicker');
await userEvent.click(getByText(datepicker, '2'));
expectedDate = new Date(new Date().setDate(2));
expectedDateString = toBasicISOString(expectedDate);
expectedDateString = toLocalISOString(expectedDate).split('T')[0]!;
expect(toBasicISOString(setValue.mock.lastCall?.[0])).toBe(expectedDateString);
});
it('should render the value provided as a prop', () => {
Expand Down
26 changes: 14 additions & 12 deletions src/hooks/useDownload/useDownload.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import React from 'react';

import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand All @@ -17,8 +15,6 @@ describe('useDownload', () => {
let download: ReturnType<typeof useDownload>;

beforeEach(() => {
vi.spyOn(document, 'createElement');
vi.spyOn(React, 'useState');
const { result } = renderHook(() => useDownload());
download = result.current;
});
Expand All @@ -27,15 +23,12 @@ describe('useDownload', () => {
vi.clearAllMocks();
});

it('should render', () => {
expect(download).toBeDefined();
});

it('should invoke the fetch data function', async () => {
const fetchData = vi.fn(() => 'hello world');
await download('hello.txt', fetchData);
expect(fetchData).toHaveBeenCalledOnce();
});

it('should attempt at add a notification if the fetch data function throws an error', async () => {
await act(() =>
download('hello.txt', () => {
Expand All @@ -45,6 +38,7 @@ describe('useDownload', () => {
expect(mockNotificationsStore.addNotification).toHaveBeenCalledOnce();
expect(mockNotificationsStore.addNotification.mock.lastCall?.[0]).toMatchObject({ message: 'An error occurred!' });
});

it('should attempt at add a notification if the fetch data function throws a non-error', async () => {
await act(() =>
download('hello.txt', () => {
Expand All @@ -54,11 +48,19 @@ describe('useDownload', () => {
);
expect(mockNotificationsStore.addNotification).toHaveBeenCalledOnce();
});
it('should attempt to create one anchor element', async () => {
await act(() => download('hello.txt', () => 'hello world'));
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(document.createElement).toHaveBeenLastCalledWith('a');

it('should invoke HTMLAnchorElement.prototype.click once', async () => {
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click');
await act(() => download('hello.txt', 'hello world'));
expect(click).toHaveBeenCalledOnce();
});

it('should allow multiple simultaneous downloads', async () => {
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click');
await act(() => Promise.all([download('foo.txt', 'foo'), download('bar.txt', 'bar')]));
expect(click).toHaveBeenCalledTimes(2);
});

it('should invoke the fetch data a gather an image', async () => {
const fetchData = vi.fn(() => new Blob());
await download('testdiv.png', fetchData, { blobType: 'image/png' });
Expand Down
28 changes: 16 additions & 12 deletions src/hooks/useDownload/useDownload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,47 @@ interface DownloadFunction {
(filename: string, data: () => Promisable<string>, options?: DownloadTextOptions): Promise<void>;
}

type Downloadable = {
blobType: string;
data: Blob | string;
filename: string;
id: string;
};

/**
* Used to trigger downloads of arbitrary data to the client
* @returns A function to invoke the download
*/
export function useDownload(): DownloadFunction {
const notifications = useNotificationsStore();
const [state, setState] = useState<{
blobType: string;
data: Blob | string;
filename: string;
} | null>(null);
const [downloads, setDownloads] = useState<Downloadable[]>([]);

useEffect(() => {
if (state) {
const { blobType, data, filename } = state;
if (downloads.length) {
const { blobType, data, filename, id } = downloads.at(-1)!;
const anchor = document.createElement('a');
document.body.appendChild(anchor);

const blob = new Blob([data], { type: blobType });

const url = URL.createObjectURL(blob);
anchor.href = url;
anchor.download = filename;
anchor.click();
URL.revokeObjectURL(url);
anchor.remove();
setState(null);
setDownloads((prevDownloads) => prevDownloads.filter((item) => item.id !== id));
}
}, [state]);
}, [downloads]);

return async (filename, _data, options) => {
try {
const data = typeof _data === 'function' ? await _data() : _data;
if (typeof data !== 'string' && !options?.blobType) {
throw new Error("argument 'blobType' must be defined when download is called with a Blob object");
}
setState({ blobType: options?.blobType ?? 'text/plain', data, filename });
setDownloads((prevDownloads) => [
...prevDownloads,
{ blobType: options?.blobType ?? 'text/plain', data, filename, id: crypto.randomUUID() }
]);
} catch (error) {
const message = error instanceof Error ? error.message : 'An unknown error occurred';
notifications.addNotification({
Expand Down
Loading