refactor: download function to be reusable

This commit is contained in:
Ephraim Atta-Duncan
2023-12-07 14:52:12 +00:00
parent 935601ad16
commit 38ad3a1922
6 changed files with 66 additions and 93 deletions

View File

@ -5,11 +5,10 @@ import { useState } from 'react';
import { Download } from 'lucide-react';
import { getFile } from '@documenso/lib/universal/upload/get-file';
import { downloadFile } from '@documenso/lib/client-only/download-pdf';
import type { DocumentData } from '@documenso/prisma/client';
import { Button } from '../../primitives/button';
import { useToast } from '../../primitives/use-toast';
export type DownloadButtonProps = HTMLAttributes<HTMLButtonElement> & {
disabled?: boolean;
@ -24,44 +23,18 @@ export const DocumentDownloadButton = ({
disabled,
...props
}: DownloadButtonProps) => {
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const onDownloadClick = async () => {
try {
setIsLoading(true);
setIsLoading(true);
if (!documentData) {
return;
}
const bytes = await getFile(documentData);
const blob = new Blob([bytes], {
type: 'application/pdf',
});
const link = window.document.createElement('a');
const baseTitle = fileName?.includes('.pdf') ? fileName.split('.pdf')[0] : fileName;
link.href = window.URL.createObjectURL(blob);
link.download = baseTitle ? `${baseTitle}_signed.pdf` : 'document.pdf';
link.click();
window.URL.revokeObjectURL(link.href);
} catch (err) {
console.error(err);
toast({
title: 'Error',
description: 'An error occurred while downloading your document.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
if (!documentData) {
return;
}
await downloadFile({ documentData, fileName }).then(() => {
setIsLoading(false);
});
};
return (

View File

@ -1,7 +1,8 @@
// Inspired by react-hot-toast library
import * as React from 'react';
import { ToastActionElement, type ToastProps } from './toast';
import type { ToastActionElement } from './toast';
import { type ToastProps } from './toast';
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;