-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathImportNodesModal.tsx
More file actions
591 lines (539 loc) · 18.4 KB
/
Copy pathImportNodesModal.tsx
File metadata and controls
591 lines (539 loc) · 18.4 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import { App, Modal, Notice } from "obsidian";
import { createRoot, Root } from "react-dom/client";
import { StrictMode, useState, useEffect, useCallback } from "react";
import type DiscourseGraphPlugin from "../index";
import type { ImportableNode, GroupWithNodes } from "~/types";
import { getUserNameById } from "~/utils/typeUtils";
import { getAvailableGroupIds } from "@repo/database/lib/groups";
import {
fetchUserNames,
getPublishedNodesForGroups,
getLocalNodeInstanceIds,
getSpaceNameFromIds,
getSpaceUris,
importSelectedNodes,
} from "~/utils/importNodes";
import { getLoggedInClient, getSupabaseContext } from "~/utils/supabaseContext";
import {
computeImportPreview,
type ImportPreviewData,
} from "~/utils/importPreview";
type ImportNodesModalProps = {
plugin: DiscourseGraphPlugin;
onClose: () => void;
};
const ImportNodesContent = ({ plugin, onClose }: ImportNodesModalProps) => {
const [step, setStep] = useState<
"loading" | "select" | "preview" | "importing"
>("loading");
const [groupsWithNodes, setGroupsWithNodes] = useState<GroupWithNodes[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [importProgress, setImportProgress] = useState({
current: 0,
total: 0,
});
const [previewData, setPreviewData] = useState<ImportPreviewData | null>(
null,
);
const [previewLoading, setPreviewLoading] = useState(false);
const loadImportableNodes = useCallback(async () => {
setIsLoading(true);
try {
const client = await getLoggedInClient(plugin);
if (!client) {
new Notice("Cannot get Supabase client");
onClose();
return;
}
const context = await getSupabaseContext(plugin);
if (!context) {
new Notice("Cannot get Supabase context");
onClose();
return;
}
const groupIds = await getAvailableGroupIds(client);
if (groupIds.length === 0) {
new Notice("You are not a member of any groups");
onClose();
return;
}
await fetchUserNames(plugin, client);
const publishedNodes = await getPublishedNodesForGroups({
client,
groupIds,
currentSpaceId: context.spaceId,
});
const localNodeInstanceIds = getLocalNodeInstanceIds(plugin);
// Filter out nodes that already exist locally
const importableNodes = publishedNodes.filter(
(node) => !localNodeInstanceIds.has(node.source_local_id),
);
const uniqueSpaceIds = [
...new Set(importableNodes.map((n) => n.space_id)),
];
const [spaceNames, spaceUris] = await Promise.all([
getSpaceNameFromIds(client, uniqueSpaceIds),
getSpaceUris(client, uniqueSpaceIds),
]);
// Keep spaceNames in settings up to date for UI display (formatImportSource reads it)
if (uniqueSpaceIds.length > 0) {
if (!plugin.settings.spaceNames) plugin.settings.spaceNames = {};
for (const spaceId of uniqueSpaceIds) {
const spaceUri = spaceUris.get(spaceId);
const spaceName = spaceNames.get(spaceId);
if (spaceUri && spaceName) {
plugin.settings.spaceNames[spaceUri] = spaceName;
}
}
await plugin.saveSettings();
}
const grouped: Map<string, GroupWithNodes> = new Map();
for (const node of importableNodes) {
const groupId = String(node.space_id);
if (!grouped.has(groupId)) {
grouped.set(groupId, {
groupId,
groupName:
spaceNames.get(node.space_id) ?? `Space ${node.space_id}`,
nodes: [],
authorIds: new Set(),
});
}
const group = grouped.get(groupId)!;
const spaceName =
spaceNames.get(node.space_id) ?? `Space ${node.space_id}`;
group.nodes.push({
nodeInstanceId: node.source_local_id,
title: node.text,
spaceId: node.space_id,
spaceName,
groupId,
selected: false,
createdAt: node.createdAt,
modifiedAt: node.modifiedAt,
filePath: node.filePath,
authorId: node.authorId,
});
if (node.authorId) group.authorIds.add(node.authorId);
}
setGroupsWithNodes(Array.from(grouped.values()));
setStep("select");
} catch (error) {
console.error("Error loading importable nodes:", error);
const errorMessage =
error instanceof Error ? error.message : String(error);
new Notice(`Failed to load nodes: ${errorMessage}`, 5000);
onClose();
} finally {
setIsLoading(false);
}
}, [plugin, onClose]);
useEffect(() => {
void loadImportableNodes();
}, [loadImportableNodes]);
const handleNodeToggle = (groupId: string, nodeIndex: number) => {
setGroupsWithNodes((prev) =>
prev.map((group) => {
if (group.groupId !== groupId) return group;
return {
...group,
nodes: group.nodes.map((node, idx) =>
idx === nodeIndex ? { ...node, selected: !node.selected } : node,
),
};
}),
);
};
const getSelectedNodes = (): ImportableNode[] => {
const selected: ImportableNode[] = [];
for (const group of groupsWithNodes) {
for (const node of group.nodes) {
if (node.selected) {
selected.push(node);
}
}
}
return selected;
};
const handleNext = async () => {
const selectedNodes = getSelectedNodes();
if (selectedNodes.length === 0) {
new Notice("Please select at least one node to import");
return;
}
setPreviewLoading(true);
try {
const preview = await computeImportPreview({ plugin, selectedNodes });
setPreviewData(preview);
setStep("preview");
} catch (error) {
console.error("Error computing preview:", error);
const errorMessage =
error instanceof Error ? error.message : String(error);
new Notice(`Failed to compute preview: ${errorMessage}`, 5000);
} finally {
setPreviewLoading(false);
}
};
const handleImport = async () => {
const selectedNodes = getSelectedNodes();
if (selectedNodes.length === 0) {
new Notice("Please select at least one node to import");
return;
}
setStep("importing");
setImportProgress({ current: 0, total: selectedNodes.length });
try {
const result = await importSelectedNodes({
plugin,
selectedNodes,
onProgress: (current, total) => {
setImportProgress({ current, total });
},
precomputedData: previewData
? {
nodeKeys: previewData.nodeKeys,
keyToRid: previewData.keyToRid,
keyToRelationEndpointId: previewData.keyToRelationEndpointId,
relationInstancesBySpace: previewData.relationInstancesBySpace,
}
: undefined,
});
if (result.failed > 0) {
new Notice(
`Import completed with some issues:\n${result.success} files imported successfully\n${result.failed} files failed`,
5000,
);
} else {
new Notice(`Successfully imported ${result.success} node(s)`, 3000);
}
onClose();
} catch (error) {
console.error("Error importing nodes:", error);
const errorMessage =
error instanceof Error ? error.message : String(error);
new Notice(`Import failed: ${errorMessage}`, 5000);
setStep("select");
}
};
const renderLoadingStep = () => (
<div className="text-center">
<h3 className="mb-4">Loading importable nodes...</h3>
<div className="text-muted text-sm">
Fetching groups and published nodes
</div>
</div>
);
const renderSelectStep = () => {
const totalNodes = groupsWithNodes.reduce(
(sum, group) => sum + group.nodes.length,
0,
);
const selectedCount = groupsWithNodes.reduce(
(sum, group) => sum + group.nodes.filter((n) => n.selected).length,
0,
);
// Group nodes by space for better organization
const nodesBySpace = new Map<
number,
{
spaceName: string;
authorIds: Set<number>;
nodes: Array<{
node: ImportableNode;
groupId: string;
nodeIndex: number;
}>;
}
>();
for (const group of groupsWithNodes) {
for (const [nodeIndex, node] of group.nodes.entries()) {
if (!nodesBySpace.has(node.spaceId)) {
nodesBySpace.set(node.spaceId, {
spaceName: node.spaceName,
authorIds: group.authorIds,
nodes: [],
});
}
nodesBySpace.get(node.spaceId)!.nodes.push({
node,
groupId: group.groupId,
nodeIndex,
});
}
}
return (
<div>
<h3 className="mb-4">Select nodes to import</h3>
<p className="text-muted mb-4 text-sm">
{totalNodes > 0
? `${totalNodes} importable node(s) found. Select which nodes to import into your vault.`
: "No importable nodes found."}
</p>
<div className="mb-4">
<button
onClick={() =>
setGroupsWithNodes((prev) =>
prev.map((group) => ({
...group,
nodes: group.nodes.map((n) => ({ ...n, selected: true })),
})),
)
}
className="mr-2 rounded border px-3 py-1 text-sm"
>
Select All
</button>
<button
onClick={() =>
setGroupsWithNodes((prev) =>
prev.map((group) => ({
...group,
nodes: group.nodes.map((n) => ({ ...n, selected: false })),
})),
)
}
className="rounded border px-3 py-1 text-sm"
>
Deselect All
</button>
</div>
<div className="max-h-96 overflow-y-auto rounded border">
{Array.from(nodesBySpace.entries()).map(
([spaceId, { spaceName, nodes, authorIds }]) => {
return (
<div key={spaceId} className="border-b">
<div className="bg-muted/10 flex items-center px-3 py-2">
<span className="mr-2">📂</span>
<span className="text-accent-foreground line-clamp-1 font-medium italic">
{spaceName}
</span>
{authorIds.size === 1 && (
<span>
({getUserNameById(plugin, [...authorIds][0]!)})
</span>
)}
<span className="text-muted ml-2 text-sm">
({nodes.length} node{nodes.length !== 1 ? "s" : ""})
</span>
</div>
{nodes.map(({ node, groupId, nodeIndex }) => (
<div
key={`${node.nodeInstanceId}-${groupId}`}
className="flex items-start border-t p-3 pl-8"
>
<input
type="checkbox"
checked={node.selected}
onChange={() => handleNodeToggle(groupId, nodeIndex)}
className="mr-3 mt-1 flex-shrink-0"
/>
<div className="min-w-0 flex-1">
<div className="line-clamp-3 font-medium">
{node.title}
{node.authorId && authorIds.size > 1 && (
<span className="font-light">
({getUserNameById(plugin, node.authorId)})
</span>
)}
</div>
</div>
</div>
))}
</div>
);
},
)}
</div>
<div className="mt-6 flex justify-between">
<button onClick={onClose} className="px-4 py-2">
Cancel
</button>
<button
onClick={() => {
void handleNext();
}}
className="!bg-accent !text-on-accent rounded px-4 py-2"
disabled={selectedCount === 0 || previewLoading}
>
{previewLoading ? "Loading..." : `Next (${selectedCount})`}
</button>
</div>
</div>
);
};
const renderPreviewStep = () => {
if (!previewData) return null;
const hasNewNodeTypes = previewData.newNodeTypeSchemas.length > 0;
const hasNewRelationTypes = previewData.newRelationTypeSchemas.length > 0;
const newTriplets = previewData.relationTriplets.filter(
(t) => t.isNewTriplet,
);
const hasNewTriplets = newTriplets.length > 0;
const hasAnyNew = hasNewNodeTypes || hasNewRelationTypes || hasNewTriplets;
return (
<div>
<h3 className="mb-2">Import preview</h3>
<p className="text-muted mb-4 text-sm">
Review what will be imported and created.
</p>
<div className="max-h-96 overflow-y-auto">
{/* Summary section */}
<div className="mb-4 rounded border p-3">
<div className="mb-1 text-sm font-medium uppercase tracking-wide opacity-60">
Summary
</div>
<div className="flex gap-6 text-sm">
<div>
<span className="font-semibold">
{previewData.selectedNodeCount}
</span>{" "}
node{previewData.selectedNodeCount !== 1 ? "s" : ""}
</div>
<div>
<span className="font-semibold">
{previewData.relationInstanceCount}
</span>{" "}
relation{previewData.relationInstanceCount !== 1 ? "s" : ""}
</div>
</div>
</div>
{/* New schemas section */}
{hasAnyNew && (
<div className="mb-4 rounded border p-3">
<div className="mb-2 text-sm font-medium uppercase tracking-wide opacity-60">
New schemas to create
</div>
{hasNewNodeTypes && (
<div className="mb-2">
<div className="mb-1 text-sm font-medium">Node types</div>
<div className="flex flex-wrap gap-1">
{previewData.newNodeTypeSchemas.map((nt) => (
<span
key={nt.id}
className="bg-accent/15 text-accent rounded px-2 py-0.5 text-xs"
>
{nt.name}
</span>
))}
</div>
</div>
)}
{hasNewRelationTypes && (
<div className="mb-2">
<div className="mb-1 text-sm font-medium">Relation types</div>
<div className="flex flex-wrap gap-1">
{previewData.newRelationTypeSchemas.map((rt) => (
<span
key={rt.id}
className="bg-accent/15 text-accent rounded px-2 py-0.5 text-xs"
>
{rt.label}
{rt.complement ? ` / ${rt.complement}` : ""}
</span>
))}
</div>
</div>
)}
{hasNewTriplets && (
<div>
<div className="mb-1 text-sm font-medium">
Discourse relations
</div>
<div className="space-y-1">
{newTriplets.map((t, i) => (
<div key={i} className="flex items-center gap-1 text-xs">
<span className="rounded bg-secondary px-1.5 py-0.5">
{t.sourceNodeTypeName}
</span>
<span className="text-accent font-medium">
{t.relationTypeLabel}
</span>
<span className="rounded bg-secondary px-1.5 py-0.5">
{t.destNodeTypeName}
</span>
</div>
))}
</div>
</div>
)}
</div>
)}
{!hasAnyNew && (
<div className="text-muted rounded border p-3 text-center text-sm">
No new schemas or relations will be created.
</div>
)}
</div>
<div className="mt-6 flex justify-between">
<button onClick={() => setStep("select")} className="px-4 py-2">
Back
</button>
<button
onClick={() => {
void handleImport();
}}
className="!bg-accent !text-on-accent rounded px-4 py-2"
>
Confirm Import
</button>
</div>
</div>
);
};
const renderImportingStep = () => (
<div className="text-center">
<h3 className="mb-4">Importing nodes</h3>
<div className="mb-4">
<div className="bg-modifier-border mb-2 h-2 rounded-full">
<div
className="bg-accent h-2 rounded-full transition-all duration-300"
style={{
width: `${(importProgress.current / importProgress.total) * 100}%`,
}}
/>
</div>
<div className="text-muted text-sm">
{importProgress.current} of {importProgress.total} node(s) processed
</div>
</div>
</div>
);
if (isLoading || step === "loading") {
return renderLoadingStep();
}
switch (step) {
case "select":
return renderSelectStep();
case "preview":
return renderPreviewStep();
case "importing":
return renderImportingStep();
default:
return null;
}
};
export class ImportNodesModal extends Modal {
private plugin: DiscourseGraphPlugin;
private root: Root | null = null;
constructor(app: App, plugin: DiscourseGraphPlugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
this.root = createRoot(contentEl);
this.root.render(
<StrictMode>
<ImportNodesContent plugin={this.plugin} onClose={() => this.close()} />
</StrictMode>,
);
}
onClose() {
if (this.root) {
this.root.unmount();
this.root = null;
}
}
}