-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageView.tsx
More file actions
82 lines (73 loc) · 2.24 KB
/
ImageView.tsx
File metadata and controls
82 lines (73 loc) · 2.24 KB
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
import { useEffect, useState } from 'react'
import { FileSource } from '../../lib/sources/types.js'
import { contentTypes, parseFileSize } from '../../lib/utils.js'
import { Spinner } from '../Layout.js'
import ContentHeader from './ContentHeader.js'
interface ViewerProps {
source: FileSource
setError: (error: Error | undefined) => void
}
interface Content {
dataUri: string
fileSize?: number
}
/**
* Image viewer component.
*/
export default function ImageView({ source, setError }: ViewerProps) {
const [content, setContent] = useState<Content>()
const [isLoading, setIsLoading] = useState(true)
const { fileName, resolveUrl, requestInit } = source
useEffect(() => {
async function loadContent() {
try {
setIsLoading(true)
const res = await fetch(resolveUrl, requestInit)
if (res.status === 401) {
const text = await res.text()
setError(new Error(text))
setContent(undefined)
return
}
const arrayBuffer = await res.arrayBuffer()
// base64 encode and display image
const b64 = arrayBufferToBase64(arrayBuffer)
const dataUri = `data:${contentType(fileName)};base64,${b64}`
const fileSize = parseFileSize(res.headers)
setContent({ dataUri, fileSize })
setError(undefined)
} catch (error) {
setContent(undefined)
setError(error as Error)
} finally {
setIsLoading(false)
}
}
void loadContent()
}, [fileName, resolveUrl, requestInit, setError])
return <ContentHeader content={content}>
{content?.dataUri && <img
alt={source.sourceId}
className='image'
src={content.dataUri} />}
{isLoading && <div className='center'><Spinner /></div>}
</ContentHeader>
}
/**
* Convert an ArrayBuffer to a base64 string.
*
* @param buffer - the ArrayBuffer to convert
* @returns base64 encoded string
*/
function arrayBufferToBase64(buffer: ArrayBuffer): string {
let binary = ''
const bytes = new Uint8Array(buffer)
for (const byte of bytes) {
binary += String.fromCharCode(byte)
}
return btoa(binary)
}
function contentType(filename: string): string {
const ext = filename.split('.').pop() ?? ''
return contentTypes[ext] ?? 'image/png'
}