Skip to content

Commit

Permalink
Replace download PDF button
Browse files Browse the repository at this point in the history
  • Loading branch information
gruz0 committed Nov 25, 2024
1 parent fb657a6 commit cae6112
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 15 deletions.
22 changes: 7 additions & 15 deletions src/app/ideas/[id]/IdeaAnalysisReport.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { usePlausible } from 'next-plausible'
import React, { useEffect, useState } from 'react'
Expand All @@ -9,6 +8,7 @@ import FeedbackForm from '@/components/FeedbackForm'
import HorizontalLine from '@/components/HorizontalLine'
import MessageBox from '@/components/MessageBox'
import { Goals } from '@/lib/goals'
import DownloadPDFButton from './components/DownloadPDFButton'
import { NavBar } from './components/NavBar'
import SectionActionableNextSteps from './components/SectionActionableNextSteps'
import SectionCompetitors from './components/SectionCompetitors'
Expand Down Expand Up @@ -242,20 +242,16 @@ export const IdeaAnalysisReport = ({ data }: Props) => {
</h1>

{readyForReport ? (
<Link
href={`/api/ideas/${data.id}/pdf`}
<DownloadPDFButton
ideaId={data.id}
onClick={() =>
plausible(Goals.DownloadPDF, {
props: {
buttonId: 'top_button',
},
})
}
target="_blank"
className="rounded bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
>
PDF
</Link>
/>
) : (
<span className="rounded bg-gray-500 px-4 py-2 font-semibold text-white">
Loading...
Expand Down Expand Up @@ -350,20 +346,16 @@ export const IdeaAnalysisReport = ({ data }: Props) => {
</p>

{readyForReport ? (
<Link
href={`/api/ideas/${data.id}/pdf`}
<DownloadPDFButton
ideaId={data.id}
onClick={() =>
plausible(Goals.DownloadPDF, {
props: {
buttonId: 'bottom_button',
},
})
}
target="_blank"
className="rounded bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
>
Download
</Link>
/>
) : (
<span className="rounded bg-gray-500 px-4 py-2 font-semibold text-white">
Loading...
Expand Down
100 changes: 100 additions & 0 deletions src/app/ideas/[id]/components/DownloadPDFButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
'use client'
import React, { useState } from 'react'

interface DownloadPDFButtonProps {
ideaId: string
onClick?: () => void
}

type DownloadError = string | null

const DownloadPDFButton: React.FC<DownloadPDFButtonProps> = ({
ideaId,
onClick,
}) => {
const [loading, setLoading] = useState<boolean>(false)
const [error, setError] = useState<DownloadError>(null)

const handleDownload = async () => {
if (onClick) {
onClick()
}

setLoading(true)
setError(null)

try {
const response = await fetch(`/api/ideas/${ideaId}/pdf`, {
method: 'GET',
headers: {
'Content-Type': 'application/pdf',
},
})

if (!response.ok) {
let errorMessage = `Server error: ${response.status} ${response.statusText}`
try {
const errorData = await response.json()
if (errorData.error) {
errorMessage = `Error: ${errorData.error}`
}
} catch (parseError) {
errorMessage = (parseError as Error).message
}
throw new Error(errorMessage)
}

const blob = await response.blob()

const url = window.URL.createObjectURL(new Blob([blob]))

const link = document.createElement('a')
link.href = url

const filename = 'CheckMVP-Report.pdf'
link.setAttribute('download', filename)

document.body.appendChild(link)

link.click()

link.parentNode?.removeChild(link)
window.URL.revokeObjectURL(url)
} catch (err) {
console.error('Error downloading PDF:', err)

if (err instanceof Error) {
setError(err.message)
} else {
setError('An unknown error occurred while downloading the PDF.')
}
} finally {
setLoading(false)
}
}

return (
<div>
<button
onClick={handleDownload}
disabled={loading}
className={`rounded px-4 py-2 font-semibold text-white transition-colors duration-200 ${
loading
? 'cursor-not-allowed bg-blue-400'
: 'bg-blue-600 hover:bg-blue-700'
}`}
aria-busy={loading}
aria-disabled={loading}
>
{loading ? 'Generating PDF...' : 'Download PDF'}
</button>
{error && (
<p className="mt-2 text-red-500" role="alert">
{error}
</p>
)}
</div>
)
}

export default DownloadPDFButton

0 comments on commit cae6112

Please sign in to comment.