-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathModifyNodeModal.tsx
More file actions
703 lines (655 loc) · 22.2 KB
/
Copy pathModifyNodeModal.tsx
File metadata and controls
703 lines (655 loc) · 22.2 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import { App, Modal, Notice, TFile } from "obsidian";
import { createRoot, Root } from "react-dom/client";
import {
StrictMode,
useState,
useEffect,
useRef,
useCallback,
useMemo,
} from "react";
import { DiscourseNode } from "~/types";
import type DiscourseGraphPlugin from "~/index";
import { QueryEngine } from "~/services/QueryEngine";
import { isProvisionalSchema } from "~/utils/typeUtils";
import { getNodeTypeIdForFile } from "~/utils/relationsStore";
import { formatNodeName } from "~/utils/createNode";
// APFS and ext4 both enforce a 255 UTF-8 byte limit per filename component.
const MAX_FILENAME_BYTES = 255;
const MD_EXTENSION_BYTES = 3; // ".md"
const getByteLength = (str: string): number =>
new TextEncoder().encode(str).byteLength;
// Remove characters from the end until the string fits within maxBytes.
const trimToByteLimit = (str: string, maxBytes: number): string => {
if (getByteLength(str) <= maxBytes) return str;
let trimmed = str;
while (trimmed.length > 0 && getByteLength(trimmed) > maxBytes) {
trimmed = trimmed.slice(0, -1);
}
return trimmed;
};
const computeMaxTitleBytes = (nodeType: DiscourseNode | null): number => {
const formatOverhead = nodeType
? getByteLength(formatNodeName("", nodeType) ?? "")
: 0;
return Math.max(1, MAX_FILENAME_BYTES - MD_EXTENSION_BYTES - formatOverhead);
};
type ModifyNodeFormProps = {
nodeTypes: DiscourseNode[];
onSubmit: (params: {
nodeType: DiscourseNode;
title: string;
initialFile?: TFile; // for edit mode
selectedExistingNode?: TFile;
/** DiscourseRelation.id; when set, relation is created with currentFile as the other end. */
relationshipId?: string;
relationshipTargetFile?: TFile;
insertBacklink: boolean;
}) => Promise<void>;
onCancel: () => void;
initialTitle?: string;
initialNodeType?: DiscourseNode;
initialFile?: TFile; // for edit mode
currentFile?: TFile; // the file where the node is being created from
plugin: DiscourseGraphPlugin;
/** When true, show the insert-backlink checkbox (editor flows that honor insertBacklink). */
showInsertBacklinkOption?: boolean;
};
export const ModifyNodeForm = ({
nodeTypes,
onSubmit,
onCancel,
initialTitle = "",
initialNodeType,
initialFile,
currentFile,
plugin,
showInsertBacklinkOption = false,
}: ModifyNodeFormProps) => {
const isEditMode = !!initialFile;
const [title, setTitle] = useState(initialFile?.basename || initialTitle);
const [selectedNodeType, setSelectedNodeType] =
useState<DiscourseNode | null>(initialNodeType || null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [selectedExistingNode, setSelectedExistingNode] =
useState<TFile | null>(null);
const [query, setQuery] = useState(initialFile?.basename || initialTitle);
const [activeIndex, setActiveIndex] = useState(0);
const [isFocused, setIsFocused] = useState(false);
const [searchResults, setSearchResults] = useState<TFile[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [selectedRelationshipKey, setSelectedRelationshipKey] = useState<
string | undefined
>(undefined);
const [insertBacklink, setInsertBacklink] = useState(!!initialTitle);
const queryEngine = useRef(new QueryEngine(plugin.app));
const titleInputRef = useRef<HTMLTextAreaElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
const menuRef = useRef<HTMLUListElement>(null);
const debounceTimeoutRef = useRef<number | null>(null);
const selectedFileRef = useRef<TFile | null>(null);
const maxTitleBytes = useMemo(
() => computeMaxTitleBytes(selectedNodeType),
[selectedNodeType],
);
// Search for nodes when query changes (only in create mode)
useEffect(() => {
if (isEditMode) {
setSearchResults([]);
return;
}
const searchQuery = query.trim();
if (searchQuery.length < 2) {
setSearchResults([]);
return;
}
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
setIsSearching(true);
debounceTimeoutRef.current = window.setTimeout(() => {
void (async () => {
try {
const results = selectedNodeType
? await queryEngine.current.searchDiscourseNodesByTitle(
searchQuery,
selectedNodeType.id,
)
: await queryEngine.current.searchDiscourseNodesByTitle(
searchQuery,
);
setSearchResults(results);
} catch (error) {
console.error("Error searching nodes:", error);
setSearchResults([]);
} finally {
setIsSearching(false);
}
})();
}, 250);
return () => {
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
};
}, [query, selectedNodeType, isEditMode]);
const isOpen = useMemo(() => {
return (
!selectedExistingNode &&
isFocused &&
searchResults.length > 0 &&
query.trim().length >= 2
);
}, [selectedExistingNode, isFocused, searchResults.length, query]);
useEffect(() => {
setActiveIndex(0);
}, [searchResults]);
useEffect(() => {
if (isOpen && titleInputRef.current && popoverRef.current) {
const inputRect = titleInputRef.current.getBoundingClientRect();
const popover = popoverRef.current;
popover.style.position = "fixed";
popover.style.top = `${inputRect.bottom + 4}px`;
popover.style.left = `${inputRect.left}px`;
popover.style.width = `${inputRect.width}px`;
}
}, [isOpen, query]);
useEffect(() => {
if (menuRef.current && isOpen && activeIndex >= 0) {
const activeElement = menuRef.current.children[
activeIndex
] as HTMLElement;
if (activeElement) {
activeElement.scrollIntoView({
block: "nearest",
behavior: "smooth",
});
}
}
}, [activeIndex, isOpen]);
// Focus the content input on mount so users can start typing immediately,
// with cursor placed at the end of any pre-filled text
useEffect(() => {
const el = titleInputRef.current;
if (!el) return;
el.focus();
const len = el.value.length;
el.setSelectionRange(len, len);
}, []);
useEffect(() => {
const el = titleInputRef.current;
if (!el) return;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}, [query]);
// Determine available relationships based on current file and selected node type
const availableRelationships = useMemo(() => {
if (!currentFile || !selectedNodeType || isEditMode) {
return [];
}
const currentFileCache = plugin.app.metadataCache.getFileCache(currentFile);
const currentNodeTypeId = currentFileCache?.frontmatter?.nodeTypeId as
| string
| undefined;
if (!currentNodeTypeId) {
return [];
}
// Find all accepted relations that connect the current node type to the selected node type
const relevantRelations = plugin.settings.discourseRelations.filter(
(relation) => {
if (isProvisionalSchema(relation)) return false;
return (
(relation.sourceId === currentNodeTypeId &&
relation.destinationId === selectedNodeType.id) ||
(relation.sourceId === selectedNodeType.id &&
relation.destinationId === currentNodeTypeId)
);
},
);
const relations = relevantRelations
.map((relation) => {
const relationType = plugin.settings.relationTypes.find(
(rt) => rt.id === relation.relationshipTypeId,
);
if (!relationType || isProvisionalSchema(relationType)) return null;
const isCurrentFileSource = relation.sourceId === currentNodeTypeId;
return {
relationTypeId: relation.relationshipTypeId,
label: isCurrentFileSource
? relationType.label
: relationType.complement,
isCurrentFileSource,
uniqueKey: relation.id,
};
})
.filter(Boolean) as Array<{
relationTypeId: string;
label: string;
isCurrentFileSource: boolean;
uniqueKey: string;
}>;
return [
...relations,
{
uniqueKey: "",
label: "No relation",
relationTypeId: "",
isCurrentFileSource: false,
},
];
}, [currentFile, selectedNodeType, isEditMode, plugin]);
// Default to first option when list appears or selection is no longer valid
useEffect(() => {
const first = availableRelationships[0];
if (!first) return;
const isValid =
selectedRelationshipKey !== undefined &&
availableRelationships.some(
(r) => r.uniqueKey === selectedRelationshipKey,
);
if (isValid) return;
setSelectedRelationshipKey(first.uniqueKey);
}, [availableRelationships, selectedRelationshipKey]);
const isFormValid = title.trim() && selectedNodeType;
const handleSelect = useCallback(
async (file: TFile) => {
selectedFileRef.current = file;
setSelectedExistingNode(file);
setQuery(file.basename);
setTitle(file.basename);
setInsertBacklink(true);
// Auto-detect node type from the selected file's frontmatter
const nodeTypeId = await getNodeTypeIdForFile(plugin, file);
if (nodeTypeId && selectedFileRef.current === file) {
const detected = nodeTypes.find((nt) => nt.id === nodeTypeId);
if (detected) setSelectedNodeType(detected);
}
},
[nodeTypes, plugin],
);
const handleClearSelection = useCallback(() => {
selectedFileRef.current = null;
setSelectedExistingNode(null);
setInsertBacklink(!!initialTitle);
setQuery("");
setTitle("");
setTimeout(() => {
titleInputRef.current?.focus();
}, 50);
}, [initialTitle]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (selectedExistingNode) {
// If locked, only handle Escape
if (e.key === "Escape") {
e.preventDefault();
handleClearSelection();
}
return;
}
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIndex((prev) =>
prev < searchResults.length - 1 ? prev + 1 : prev,
);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIndex((prev) => (prev > 0 ? prev - 1 : 0));
} else if (e.key === "Enter") {
e.preventDefault();
if (isOpen && searchResults[activeIndex]) {
void handleSelect(searchResults[activeIndex]);
} else if (isFormValid && !isSubmitting) {
void handleConfirm();
}
} else if (e.key === "Escape") {
e.preventDefault();
onCancel();
}
};
const handleNodeTypeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const selectedId = e.target.value;
const newSelectedType =
nodeTypes.find((nt) => nt.id === selectedId) || null;
setSelectedNodeType(newSelectedType);
if (selectedExistingNode) {
selectedFileRef.current = null;
setSelectedExistingNode(null);
setQuery("");
setTitle("");
} else {
const newMaxBytes = computeMaxTitleBytes(newSelectedType);
if (getByteLength(query) > newMaxBytes) {
const trimmed = trimToByteLimit(query, newMaxBytes);
setQuery(trimmed);
setTitle(trimmed);
}
}
setSelectedRelationshipKey(undefined);
};
const handleQueryChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newQuery = trimToByteLimit(e.target.value, maxTitleBytes);
setQuery(newQuery);
setTitle(newQuery);
if (selectedExistingNode) {
setSelectedExistingNode(null);
}
};
const handleConfirm = useCallback(async () => {
if (!isFormValid || isSubmitting) {
return;
}
const trimmedTitle = title.trim();
if (!trimmedTitle) {
new Notice("Please enter a title", 3000);
return;
}
if (!selectedNodeType) {
new Notice("Please select a node type", 3000);
return;
}
try {
setIsSubmitting(true);
const key =
selectedRelationshipKey ?? availableRelationships[0]?.uniqueKey ?? "";
const selectedRel = key
? availableRelationships.find((r) => r.uniqueKey === key)
: undefined;
await onSubmit({
nodeType: selectedNodeType,
title: trimmedTitle,
initialFile,
selectedExistingNode: selectedExistingNode || undefined,
relationshipId: selectedRel?.uniqueKey || undefined,
relationshipTargetFile: currentFile || undefined,
insertBacklink,
});
onCancel();
} catch (error) {
console.error(
`Error ${isEditMode ? "modifying" : "creating"} node:`,
error,
);
new Notice(
`Error ${isEditMode ? "modifying" : "creating"} node: ${error instanceof Error ? error.message : String(error)}`,
5000,
);
} finally {
setIsSubmitting(false);
}
}, [
isFormValid,
isSubmitting,
onSubmit,
onCancel,
title,
selectedNodeType,
isEditMode,
initialFile,
selectedExistingNode,
selectedRelationshipKey,
currentFile,
availableRelationships,
insertBacklink,
]);
return (
<div>
<h2>{isEditMode ? "Modify discourse node" : "Create discourse node"}</h2>
<div className="setting-item">
<div className="setting-item-name">Content</div>
<div className="setting-item-control">
{selectedExistingNode ? (
// Locked state: show selected node with clear button
<div className="relative flex w-full items-start">
<textarea
value={selectedExistingNode.basename}
readOnly
disabled={isSubmitting}
rows={1}
className="font-inherit border-background-modifier-border bg-background-secondary text-text-normal min-h-[2.5em] w-full cursor-default resize-none overflow-y-auto rounded-md border p-2 pr-8"
/>
<button
onClick={handleClearSelection}
className="text-muted hover:text-normal absolute right-2 top-2 flex h-4 w-4 cursor-pointer items-center justify-center rounded border-0 bg-transparent text-xs"
aria-label="Clear selection"
type="button"
disabled={isSubmitting}
>
✕
</button>
</div>
) : (
// Search input with popover (only in create mode)
<div className="relative w-full">
<textarea
ref={titleInputRef}
placeholder={
isEditMode
? "Enter new content"
: selectedNodeType
? `Search for existing ${selectedNodeType.name.toLowerCase()} or enter new content`
: "Search for existing nodes or enter new content"
}
value={query}
onChange={handleQueryChange}
onKeyDown={handleKeyDown}
onFocus={() => {
if (!isEditMode) {
setIsFocused(true);
}
}}
onBlur={() => {
setTimeout(() => setIsFocused(false), 200);
}}
disabled={isSubmitting}
rows={1}
className="font-inherit border-background-modifier-border bg-background-primary text-text-normal min-h-[2.5em] w-full resize-none overflow-hidden rounded-md border p-2"
autoComplete="off"
/>
{getByteLength(query) >= maxTitleBytes && (
<p className="text-error mt-1 text-xs">
Character limit reached
</p>
)}
{isOpen && !isEditMode && (
<div
ref={popoverRef}
className="suggestion-container fixed z-[1000] mt-1 max-h-[256px] overflow-y-auto rounded-[var(--radius-s)] border border-[var(--background-modifier-border)] bg-[var(--background-primary)] shadow-[var(--shadow-s)]"
>
<ul
ref={menuRef}
className="suggestion-list m-0 list-none py-1"
>
{isSearching ? (
<li className="suggestion-item py-2 text-[var(--text-muted)]">
Searching...
</li>
) : searchResults.length === 0 ? (
<li className="suggestion-item py-2 text-[var(--text-muted)]">
No results found
</li>
) : (
searchResults.map((file, index) => (
<li
key={file.path}
className={`suggestion-item flex cursor-pointer items-center gap-2 py-2 ${
index === activeIndex
? "is-selected bg-[var(--background-modifier-hover)]"
: "bg-transparent"
}`}
onMouseDown={(e) => {
e.preventDefault();
void handleSelect(file);
}}
onMouseEnter={() => setActiveIndex(index)}
>
<span>{file.basename}</span>
</li>
))
)}
</ul>
</div>
)}
</div>
)}
</div>
</div>
<div className="setting-item">
<div className="setting-item-name">Type</div>
<div className="setting-item-control">
<select
value={selectedNodeType?.id || ""}
onChange={handleNodeTypeChange}
disabled={isSubmitting || isEditMode}
className="w-full"
>
<option value="">Select node type</option>
{nodeTypes.map((nodeType) => (
<option key={nodeType.id} value={nodeType.id}>
{nodeType.name}
</option>
))}
</select>
</div>
</div>
{availableRelationships.length > 0 && !isEditMode && currentFile && (
<div className="setting-item">
<div className="setting-item-name">
Relationship with "{currentFile.basename}"
</div>
<div className="setting-item-control">
<select
value={
selectedRelationshipKey ??
availableRelationships[0]?.uniqueKey ??
""
}
onChange={(e) => setSelectedRelationshipKey(e.target.value)}
disabled={isSubmitting}
className="w-full"
>
{availableRelationships.map((rel) => (
<option key={rel.uniqueKey || "none"} value={rel.uniqueKey}>
{rel.label}
</option>
))}
</select>
</div>
</div>
)}
{!isEditMode && showInsertBacklinkOption && (
<div className="setting-item">
<div className="setting-item-name">Insert backlink</div>
<div className="setting-item-control">
<input
type="checkbox"
checked={insertBacklink}
onChange={(e) => setInsertBacklink(e.target.checked)}
disabled={isSubmitting}
/>
</div>
</div>
)}
<div className="modal-button-container mt-5 flex justify-end gap-2">
<button
type="button"
className="mod-normal"
onClick={onCancel}
disabled={isSubmitting}
>
Cancel
</button>
<button
type="button"
className="mod-cta"
onClick={() => {
void handleConfirm();
}}
disabled={!isFormValid || isSubmitting}
>
{isSubmitting
? isEditMode
? "Modifying..."
: "Creating..."
: "Confirm"}
</button>
</div>
</div>
);
};
type ModifyNodeModalProps = {
nodeTypes: DiscourseNode[];
plugin: DiscourseGraphPlugin;
onSubmit: (params: {
nodeType: DiscourseNode;
title: string;
initialFile?: TFile;
selectedExistingNode?: TFile;
relationshipId?: string;
relationshipTargetFile?: TFile;
insertBacklink: boolean;
}) => Promise<void>;
initialTitle?: string;
initialNodeType?: DiscourseNode;
initialFile?: TFile;
currentFile?: TFile;
showInsertBacklinkOption?: boolean;
};
class ModifyNodeModal extends Modal {
private nodeTypes: DiscourseNode[];
private onSubmit: (params: {
nodeType: DiscourseNode;
title: string;
initialFile?: TFile;
selectedExistingNode?: TFile;
relationshipId?: string;
relationshipTargetFile?: TFile;
insertBacklink: boolean;
}) => Promise<void>;
private root: Root | null = null;
private initialTitle?: string;
private initialNodeType?: DiscourseNode;
private initialFile?: TFile;
private currentFile?: TFile;
private plugin: DiscourseGraphPlugin;
private showInsertBacklinkOption?: boolean;
constructor(app: App, props: ModifyNodeModalProps) {
super(app);
this.nodeTypes = props.nodeTypes;
this.onSubmit = props.onSubmit;
this.initialTitle = props.initialTitle;
this.initialNodeType = props.initialNodeType;
this.initialFile = props.initialFile;
this.currentFile = props.currentFile;
this.plugin = props.plugin;
this.showInsertBacklinkOption = props.showInsertBacklinkOption;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
this.root = createRoot(contentEl);
this.root.render(
<StrictMode>
<ModifyNodeForm
nodeTypes={this.nodeTypes}
onSubmit={this.onSubmit}
onCancel={() => this.close()}
initialTitle={this.initialTitle}
initialNodeType={this.initialNodeType}
initialFile={this.initialFile}
currentFile={this.currentFile}
plugin={this.plugin}
showInsertBacklinkOption={this.showInsertBacklinkOption}
/>
</StrictMode>,
);
}
onClose() {
if (this.root) {
this.root.unmount();
this.root = null;
}
const { contentEl } = this;
contentEl.empty();
}
}
export default ModifyNodeModal;