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

72 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-17 19:56:18 +10:00
'use client';
import type { HTMLAttributes } from 'react';
import { useState } from 'react';
2023-08-17 19:56:18 +10:00
2024-08-27 20:34:39 +09:00
import { Trans } from '@lingui/macro';
import { useLingui } from '@lingui/react';
2023-08-17 19:56:18 +10:00
import { Download } from 'lucide-react';
2024-01-02 04:38:35 +00:00
import { downloadPDF } from '@documenso/lib/client-only/download-pdf';
import type { DocumentData } from '@documenso/prisma/client';
2024-01-02 04:52:15 +00:00
import { useToast } from '@documenso/ui/primitives/use-toast';
import { Button } from '../../primitives/button';
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) => {
2024-08-27 20:34:39 +09:00
const { _ } = useLingui();
2024-01-02 04:38:35 +00:00
const { toast } = useToast();
2023-08-17 19:56:18 +10:00
2024-08-27 20:34:39 +09:00
const [isLoading, setIsLoading] = useState(false);
const onDownloadClick = async () => {
2024-01-02 04:38:35 +00:00
try {
setIsLoading(true);
2023-08-17 19:56:18 +10:00
2024-01-02 04:38:35 +00:00
if (!documentData) {
setIsLoading(false);
return;
}
2023-09-14 13:21:03 +10:00
2024-01-02 04:38:35 +00:00
await downloadPDF({ documentData, fileName }).then(() => {
setIsLoading(false);
});
} catch (err) {
setIsLoading(false);
2024-01-02 04:38:35 +00:00
toast({
2024-08-27 20:34:39 +09:00
title: _('Something went wrong'),
description: _('An error occurred while downloading your document.'),
2024-01-02 04:38:35 +00:00
variant: 'destructive',
});
}
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}
>
2024-03-28 13:13:29 +08:00
{!isLoading && <Download className="mr-2 h-5 w-5" />}
2024-08-27 20:34:39 +09:00
<Trans>Download</Trans>
2023-08-17 19:56:18 +10:00
</Button>
);
};