/* * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) * * SPDX-License-Identifier: AGPL-3.0-only */ import React, { MutableRefObject, useCallback, useEffect, useRef } from 'react' import { Logger } from '../../../utils/logger' const log = new Logger('UploadInput') export interface UploadInputProps { onLoad: (file: File) => Promise acceptedFiles: string onClickRef: MutableRefObject<(() => void) | undefined> 'data-cy'?: string } export const UploadInput: React.FC = ({ onLoad, acceptedFiles, onClickRef, ...props }) => { const fileInputReference = useRef(null) const onClick = useCallback(() => { const fileInput = fileInputReference.current if (!fileInput) { return } fileInput.addEventListener('change', () => { if (!fileInput.files || fileInput.files.length < 1) { return } const file = fileInput.files[0] onLoad(file) .then(() => { fileInput.value = '' }) .catch((error) => { log.error('Error while uploading file', error) }) }) fileInput.click() }, [onLoad]) useEffect(() => { onClickRef.current = onClick }) return ( ) }