From 5ec599747ceeabef6b9cad3ad8e8bfd6af939d34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Ricks?= Date: Tue, 16 Apr 2024 11:32:03 +0200 Subject: [PATCH 1/2] Add: Add a useDownload hook The useDownload hook in conjunction with the Download component should replace the withDownload HOC in future. --- src/web/components/form/useDownload.jsx | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/web/components/form/useDownload.jsx diff --git a/src/web/components/form/useDownload.jsx b/src/web/components/form/useDownload.jsx new file mode 100644 index 0000000000..160b586535 --- /dev/null +++ b/src/web/components/form/useDownload.jsx @@ -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(); + }, []); + return [downloadRef, download]; +}; + +export default useDownload; From b3f679b64c6a7c5d74557dc9d7e7ceb7901dfdc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Ricks?= Date: Mon, 17 Jun 2024 11:32:07 +0200 Subject: [PATCH 2/2] Add a simple test for useDownload hook Combine Download with useDownload in a simple test. --- .../components/form/__tests__/useDownload.jsx | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/web/components/form/__tests__/useDownload.jsx diff --git a/src/web/components/form/__tests__/useDownload.jsx b/src/web/components/form/__tests__/useDownload.jsx new file mode 100644 index 0000000000..53ade8a4f0 --- /dev/null +++ b/src/web/components/form/__tests__/useDownload.jsx @@ -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 ( + <> + +