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

Add a useDownload hook #4069

Merged
merged 2 commits into from
Jun 18, 2024
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
40 changes: 40 additions & 0 deletions src/web/components/form/__tests__/useDownload.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* SPDX-FileCopyrightText: 2024 Greenbone AG
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

/* eslint-disable react/prop-types */

import {describe, test, expect, testing} from '@gsa/testing';

import {fireEvent, render, screen} from 'web/utils/testing';

import useDownload from '../useDownload';
import Download from '../download';

const TestComponent = () => {
const [ref, download] = useDownload();
return (
<>
<Download ref={ref} />
<button
data-testid="download"
onClick={() => download({filename: 'foo', data: 'bar'})}
/>
</>
);
};

describe('useDownload', () => {
test('should download a file', () => {
const createObjectURL = testing.fn().mockReturnValue('foo://bar');
window.URL.createObjectURL = createObjectURL;
window.URL.revokeObjectURL = testing.fn();

render(<TestComponent />);

fireEvent.click(screen.getByTestId('download'));

expect(createObjectURL).toHaveBeenCalled();
});
});
37 changes: 37 additions & 0 deletions src/web/components/form/useDownload.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* SPDX-FileCopyrightText: 2024 Greenbone AG
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import {useRef, useCallback} from 'react';

import logger from 'gmp/log';

import {hasValue} from 'gmp/utils/identity';

const log = logger.getLogger('web.components.form.useDownload');

/**
* Hook to download a file
*
* Should be used in combination with the Download component
*
* @returns Array of downloadRef and download function
*/
const useDownload = () => {
const downloadRef = useRef(null);

const download = useCallback(({filename, data, mimetype}) => {
if (!hasValue(downloadRef.current)) {
log.warn('Download ref not set.');
return;
}

downloadRef.current.setFilename(filename);
downloadRef.current.setData(data, mimetype);
downloadRef.current.download();
}, []);
bjoernricks marked this conversation as resolved.
Show resolved Hide resolved
return [downloadRef, download];
};

export default useDownload;
Loading