-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdocument-import-dialog.tsx
More file actions
321 lines (284 loc) · 9 KB
/
document-import-dialog.tsx
File metadata and controls
321 lines (284 loc) · 9 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { FileTextIcon, UploadIcon } from "lucide-react";
import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";
import {
ImportDialogFooter,
ImportDialogShell,
ImportEmptyState,
ImportErrorState,
ImportItemsList,
ImportLoadingState,
} from "@/components/features/import/import-dialog-shared";
import { Button } from "@/components/ui/button";
import { useImportDialog } from "@/hooks/use-import-dialog";
import { useMemories } from "@/hooks/use-memories";
import {
convertToImportItems,
type DocumentImportItem,
type DocumentParserStatus,
parseDocument,
} from "@/lib/document/document-parser";
import { createLogger } from "@/lib/logger";
import { findDuplicates } from "@/lib/storage/memories";
const logger = createLogger("component:document-import-dialog");
const STATUS_MESSAGES: Record<DocumentParserStatus, string> = {
idle: "Ready to import",
reading: "Reading document...",
parsing: "AI is extracting information...",
success: "Information extracted!",
error: "Failed to extract data",
};
const PROGRESS_BY_STATUS: Record<DocumentParserStatus, number> = {
idle: 0,
reading: 30,
parsing: 60,
success: 100,
error: 0,
};
function getDescription(status: DocumentParserStatus): string {
switch (status) {
case "idle":
return "Upload a PDF or text file to extract information.";
case "success":
return "Select the information you want to import.";
case "reading":
return "Reading your document...";
case "parsing":
return "AI is extracting your information...";
case "error":
return "Something went wrong. Please try again.";
}
}
type DocumentImportDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess?: () => void;
};
export function DocumentImportDialog({
open,
onOpenChange,
onSuccess,
}: DocumentImportDialogProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [fileName, setFileName] = useState<string | null>(null);
const lastImportKeyRef = useRef<string | null>(null);
const lastImportTimeRef = useRef<number>(0);
const abortControllerRef = useRef<AbortController | null>(null);
const { entries: existingMemories } = useMemories();
const {
status,
setStatus,
error,
setError,
importItems,
setImportItems,
isSaving,
selectedCount,
requestIdRef,
handleToggleItem,
handleToggleAll,
handleSaveSelected,
handleClose,
} = useImportDialog<DocumentImportItem, DocumentParserStatus>(
{
importTag: "document-import",
successMessage: "Imported {count} memories!",
successDescription: "Your document data has been saved as memories.",
onSuccess,
onOpenChange,
},
"idle",
);
const progress = PROGRESS_BY_STATUS[status];
const handleFileSelect = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const isPdf =
file.type === "application/pdf" ||
file.name.toLowerCase().endsWith(".pdf");
const isTxt =
file.type === "text/plain" || file.name.toLowerCase().endsWith(".txt");
if (!isPdf && !isTxt) {
setError("Please select a PDF or text file");
setStatus("error");
event.target.value = "";
return;
}
const importKey = `${file.name}:${file.size}`;
const now = Date.now();
if (
importKey === lastImportKeyRef.current &&
now - lastImportTimeRef.current < 5_000
) {
logger.debug("Skipping duplicate import for:", file.name);
event.target.value = "";
return;
}
lastImportKeyRef.current = importKey;
lastImportTimeRef.current = now;
abortControllerRef.current?.abort();
const controller = new AbortController();
abortControllerRef.current = controller;
setFileName(file.name);
setStatus("reading");
setError(null);
setImportItems([]);
const currentRequestId = ++requestIdRef.current;
const requestId = String(currentRequestId);
try {
const result = await parseDocument(file, {
requestId,
signal: controller.signal,
onStageChange: (stage) => {
if (requestIdRef.current !== currentRequestId) return;
setStatus(stage);
},
});
if (requestIdRef.current !== currentRequestId) return;
if (!result.success || !result.items) {
if (result.error === "cancelled") return;
const errorMsg =
result.error || "Failed to extract data from document";
setStatus("error");
setError(errorMsg);
toast.error(errorMsg);
return;
}
const items = convertToImportItems(result.items);
const duplicatesMap = await findDuplicates(items, existingMemories);
const enrichedItems = items.map((item, i) => {
const duplicate = duplicatesMap.get(i);
return duplicate ? { ...item, existingDuplicate: duplicate } : item;
});
setImportItems(enrichedItems);
setStatus("success");
logger.debug(
`[req:${requestId}] Successfully extracted document data:`,
items.length,
"items",
);
} catch (err) {
if (requestIdRef.current !== currentRequestId) return;
if (err instanceof Error && err.name === "AbortError") return;
const errMsg =
err instanceof Error ? err.message : "An unexpected error occurred";
logger.error(`[req:${requestId}] Import error:`, err);
setStatus("error");
setError(errMsg);
toast.error(errMsg);
}
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
},
[requestIdRef, setStatus, setError, setImportItems, existingMemories],
);
const handleCloseWrapper = (open: boolean) => {
if (!open) {
abortControllerRef.current?.abort();
abortControllerRef.current = null;
setFileName(null);
}
handleClose(open);
};
const handleRetry = () => {
setStatus("idle");
setError(null);
setFileName(null);
};
const showFooter = status === "success" && importItems.length > 0;
return (
<ImportDialogShell
open={open}
onOpenChange={handleCloseWrapper}
title={
<>
<FileTextIcon className="size-5 text-primary" />
Import from Document
</>
}
description={getDescription(status)}
footer={
showFooter ? (
<ImportDialogFooter
selectedCount={selectedCount}
isSaving={isSaving}
onCancel={() => handleCloseWrapper(false)}
onSave={handleSaveSelected}
/>
) : undefined
}
>
{status === "idle" && (
<div className="flex flex-col items-center justify-center py-8 gap-6">
<div className="size-20 rounded-full bg-primary/10 flex items-center justify-center">
<FileTextIcon className="size-10 text-primary" />
</div>
<p className="text-xs text-amber-600">
Requires an AI provider to be configured in settings.
</p>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.txt"
onChange={handleFileSelect}
className="hidden"
/>
<Button
onClick={() => fileInputRef.current?.click()}
className="gap-2"
>
<UploadIcon className="size-4" />
Select Document
</Button>
<p className="text-xs text-muted-foreground">
Supported formats: PDF, TXT
</p>
</div>
)}
{(status === "reading" || status === "parsing") && (
<ImportLoadingState
progress={progress}
statusMessage={STATUS_MESSAGES[status]}
extra={
fileName && (
<p className="text-xs text-center text-muted-foreground truncate">
{fileName}
</p>
)
}
/>
)}
{status === "error" && (
<ImportErrorState
error={error}
defaultError="Failed to extract data. Please try again."
onRetry={handleRetry}
/>
)}
{status === "success" && importItems.length > 0 && (
<ImportItemsList
items={importItems}
itemIdPrefix="doc-item"
onToggleItem={handleToggleItem}
onToggleAll={handleToggleAll}
headerExtra={
fileName && (
<span className="text-xs text-muted-foreground truncate max-w-[150px]">
from {fileName}
</span>
)
}
/>
)}
{status === "success" && importItems.length === 0 && (
<ImportEmptyState
message="No useful information could be extracted from this document. Try a different file."
onRetry={handleRetry}
retryText="Try Another File"
/>
)}
</ImportDialogShell>
);
}