-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleFileImporter.tsx
More file actions
137 lines (110 loc) · 3.96 KB
/
SimpleFileImporter.tsx
File metadata and controls
137 lines (110 loc) · 3.96 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import { ChangeEvent, ReactNode, useId, useState } from 'react'
import { KnowledgeModelData, ProjectImporterEvent } from '../data'
import { ProjectImporter } from '../project-importer'
import { FlashError } from './Flash'
type ReadAs = 'text' | 'arrayBuffer' | 'dataURL'
export type SimpleFileImporterProps<TParsed = unknown> = {
// SDK opinionated output
onImport: (events: ProjectImporterEvent[]) => void
// Optional context
knowledgeModel?: KnowledgeModelData | null
// UI
heading: ReactNode
label: ReactNode
description?: ReactNode
// File handling
accept?: string // default application/json
readAs?: ReadAs // default text
// Parsing + import mapping
parse?: (raw: string | ArrayBuffer) => TParsed // default JSON.parse(text)
importData: (
importer: ProjectImporter,
parsed: TParsed,
knowledgeModel: KnowledgeModelData | null,
) => void
// Errors
errorMessage?: ReactNode
formatError?: (err: unknown) => ReactNode
inputId?: string
}
function defaultJsonParse(raw: string | ArrayBuffer): unknown {
if (typeof raw !== 'string') {
throw new Error('Expected text content')
}
return JSON.parse(raw)
}
function readFile(file: File, readAs: ReadAs): Promise<string | ArrayBuffer> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onerror = () => reject(reader.error ?? new Error('Failed to read file'))
reader.onload = () => {
const result = reader.result
if (typeof result === 'string' || result instanceof ArrayBuffer) {
resolve(result)
} else {
reject(new Error('Unsupported file content'))
}
}
if (readAs === 'text') reader.readAsText(file)
else if (readAs === 'arrayBuffer') reader.readAsArrayBuffer(file)
else reader.readAsDataURL(file)
})
}
export function SimpleFileImporter<TParsed = unknown>({
onImport,
knowledgeModel = null,
heading,
label,
description,
accept = 'application/json',
readAs = 'text',
parse = defaultJsonParse as (raw: string | ArrayBuffer) => TParsed,
importData,
errorMessage = 'Error reading or parsing file. Make sure you selected a valid document.',
formatError,
inputId,
}: SimpleFileImporterProps<TParsed>) {
const autoId = useId()
const id = inputId ?? `simple-importer-${autoId}`
const [error, setError] = useState<ReactNode | null>(null)
const onFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
try {
const raw = await readFile(file, readAs)
const parsed = parse(raw)
const importer = new ProjectImporter()
importData(importer, parsed, knowledgeModel)
setError(null)
onImport(importer.getEvents())
} catch (err) {
setError(formatError ? formatError(err) : errorMessage)
} finally {
// Allow selecting the same file again
event.target.value = ''
}
}
return (
<div className="col col-detail mx-auto">
<div className="mb-3">
<h2>{heading}</h2>
</div>
<div className="mb-3">
{error && <FlashError>{error}</FlashError>}
<div className="form-group">
<label htmlFor={id} className="form-label">
{label}
</label>
<input
type="file"
id={id}
accept={accept}
className={`form-control${error ? ' is-invalid' : ''}`}
onChange={onFileChange}
/>
{description && <div className="mt-2 text-muted">{description}</div>}
</div>
</div>
</div>
)
}