aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/new/document-modal/content/pdf.tsx
blob: a025cf6132559832054b9f129fedcd199e9ff2b7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"use client"

import { Document, Page, pdfjs } from "react-pdf"
import { useState } from "react"
import "react-pdf/dist/Page/AnnotationLayer.css"
import "react-pdf/dist/Page/TextLayer.css"

// Configure PDF.js worker to use local package
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
	"pdfjs-dist/build/pdf.worker.min.mjs",
	import.meta.url,
).toString()

interface PdfViewerProps {
	url: string | null | undefined
}

export function PdfViewer({ url }: PdfViewerProps) {
	const [numPages, setNumPages] = useState<number | null>(null)
	const [loading, setLoading] = useState(true)
	const [error, setError] = useState<string | null>(null)

	if (!url) {
		return (
			<div className="flex items-center justify-center h-full text-gray-400">
				No PDF URL provided
			</div>
		)
	}

	function onDocumentLoadSuccess({ numPages }: { numPages: number }) {
		setNumPages(numPages)
		setLoading(false)
		setError(null)
	}

	function onDocumentLoadError(error: Error) {
		setError(error.message || "Failed to load PDF")
		setLoading(false)
	}

	return (
		<div className="flex flex-col h-full w-full overflow-hidden scrollbar-thin">
			{loading && (
				<div className="flex items-center justify-center h-full text-gray-400">
					Loading PDF...
				</div>
			)}
			{error && (
				<div className="flex items-center justify-center h-full text-red-400">
					Error: {error}
				</div>
			)}
			<div className="flex-1 overflow-auto w-full">
				<Document
					file={
						url ||
						"https://corsproxy.io/?" +
							encodeURIComponent("http://www.pdf995.com/samples/pdf.pdf")
					}
					onLoadSuccess={onDocumentLoadSuccess}
					onLoadError={onDocumentLoadError}
					loading={null}
					className="w-full"
				>
					{numPages && (
						<div className="flex flex-col items-center gap-4 py-4 w-full">
							{Array.from(new Array(numPages), (_, index) => (
								<Page
									key={`page_${index + 1}`}
									pageNumber={index + 1}
									renderTextLayer
									renderAnnotationLayer
									className="shadow-lg"
									width={630}
								/>
							))}
						</div>
					)}
				</Document>
			</div>
		</div>
	)
}