Files
sign/packages/ui/components/document/document-download-button.tsx

79 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-17 19:56:18 +10:00
'use client';
import { HTMLAttributes, useState } from 'react';
2023-08-17 19:56:18 +10:00
import { Download } from 'lucide-react';
import { getFile } from '@documenso/lib/universal/upload/get-file';
import { DocumentData } from '@documenso/prisma/client';
2023-08-17 19:56:18 +10:00
import { Button } from '@documenso/ui/primitives/button';
2023-09-14 13:21:03 +10:00
import { useToast } from '@documenso/ui/primitives/use-toast';
2023-08-17 19:56:18 +10:00
export type DownloadButtonProps = HTMLAttributes<HTMLButtonElement> & {
disabled?: boolean;
fileName?: string;
documentData?: DocumentData;
2023-08-17 19:56:18 +10:00
};
2023-09-20 13:48:30 +10:00
export const DocumentDownloadButton = ({
2023-08-17 19:56:18 +10:00
className,
fileName,
documentData,
2023-08-17 19:56:18 +10:00
disabled,
...props
}: DownloadButtonProps) => {
2023-09-14 13:21:03 +10:00
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
2023-08-17 19:56:18 +10:00
const onDownloadClick = async () => {
2023-08-17 19:56:18 +10:00
try {
setIsLoading(true);
2023-08-17 19:56:18 +10:00
if (!documentData) {
return;
}
2023-08-17 19:56:18 +10:00
const bytes = await getFile(documentData);
2023-08-17 19:56:18 +10:00
const blob = new Blob([bytes], {
type: 'application/pdf',
});
2023-08-17 19:56:18 +10:00
const link = window.document.createElement('a');
2023-08-17 19:56:18 +10:00
link.href = window.URL.createObjectURL(blob);
link.download = fileName || 'document.pdf';
2023-08-17 19:56:18 +10:00
link.click();
window.URL.revokeObjectURL(link.href);
} catch (err) {
console.error(err);
2023-09-14 13:21:03 +10:00
toast({
title: 'Error',
description: 'An error occurred while downloading your document.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
2023-08-17 19:56:18 +10:00
};
return (
<Button
type="button"
variant="outline"
className={className}
disabled={disabled || !documentData}
2023-08-17 19:56:18 +10:00
onClick={onDownloadClick}
loading={isLoading}
2023-08-17 19:56:18 +10:00
{...props}
>
<Download className="mr-2 h-5 w-5" />
Download
</Button>
);
};