forked from jcollingj/caret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
2339 lines (2131 loc) · 89.6 KB
/
main.ts
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Fuse from "fuse.js";
import { encodingForModel } from "js-tiktoken";
// @ts-ignore
import ollama from "ollama/browser";
// @ts-ignore
import pdfjs from "@bundled-es-modules/pdfjs-dist/build/pdf";
import OpenAI from "openai";
import Groq from "groq-sdk";
import { around } from "monkey-around";
import { Canvas, ViewportNode, Message, Node, Edge, EdgeDirection } from "./types";
import {
App,
Editor,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
ItemView,
WorkspaceLeaf,
setTooltip,
setIcon,
} from "obsidian";
import { CanvasFileData, CanvasNodeData, CanvasTextData } from "obsidian/canvas";
import { Extension, RangeSetBuilder, StateField, Transaction } from "@codemirror/state";
import { Decoration, DecorationSet, EditorView } from "@codemirror/view";
var parseString = require("xml2js").parseString;
export class CMDJModal extends Modal {
result: string;
selectedText: string;
startIndex: number;
endIndex: number;
plugin: any;
constructor(app: App, selectedText: string, startIndex: number, endIndex: number, plugin: any) {
super(app);
this.selectedText = selectedText;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
const textDisplay = contentEl.createEl("div", {
text: this.selectedText,
});
textDisplay.style.height = "60px";
textDisplay.style.overflow = "scroll";
contentEl.createEl("br"); // Line break
const textArea = contentEl.createEl("textarea", {
placeholder: "Type here...",
});
textArea.style.width = "100%";
textArea.style.minHeight = "100px";
textArea.style.resize = "none";
textArea.oninput = () => {
textArea.style.height = ""; // Reset the height
textArea.style.height = `${textArea.scrollHeight}px`;
};
const buttonContainer = contentEl.createEl("div", { cls: "button-container" });
// buttonContainer.style.display = "flex";
// buttonContainer.style.justifyContent = "space-between"; // This will space the buttons evenly
// Create the "Append Output" button
new Setting(buttonContainer)
.addButton((btn) =>
btn
.setButtonText("Append Output")
.onClick(async () => {
this.result = textArea.value; // Capture the value from the textarea
const content = await this.submit_edit(this.result);
this.insert_response(content);
this.close();
})
)
.addButton((btn) =>
btn
.setButtonText("Replace")
.setCta()
.onClick(async () => {
this.result = textArea.value; // Capture the value from the textarea
const content = await this.submit_edit(this.result);
this.apply_delete(this.result);
this.insert_response(content, true);
this.close();
})
);
}
async submit_edit(result: string) {
let content = `
Please apply the following instructions to the below content:
Instructions:
${this.result}
Content:
${this.selectedText}
## Rules:
- Just return the reponse that follows the instructions. No need to include a preample or anything
## Markdown Formatting:
Always apply markdown formatting. For keywords use the following:
todos - Prepend todo lines with:
- [ ]
`.trim();
const conversation = [{ role: "user", content: content }];
const message = await this.plugin.llm_call(
this.plugin.settings.llm_provider,
this.plugin.settings.model,
conversation
);
return message.content;
}
insert_response(response: string, replace: boolean = false) {
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
if (editor) {
let index = this.endIndex;
if (replace) {
index = index + 4;
}
const pos = editor.offsetToPos(index);
editor.replaceRange(`\n|+${response}+|`, pos);
editor.setCursor(pos); // Optionally set the cursor after the inserted text
editor.focus(); // Focus the editor after inserting text
}
}
apply_delete(text: string) {
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
if (editor) {
const content = editor.getValue();
const index = content.indexOf(this.selectedText);
if (index !== -1) {
const beforeText = content.substring(0, index);
const afterText = content.substring(index + this.selectedText.length);
const newText = beforeText + `|-${this.selectedText}-|` + afterText;
editor.setValue(newText);
}
}
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
export const redBackgroundField = StateField.define<DecorationSet>({
create(state): DecorationSet {
return Decoration.none;
},
update(oldState: DecorationSet, transaction: Transaction): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
const docText = transaction.state.doc.toString();
const delete_regex = /\|-(.*?)-\|/gs; // Changed to match across lines
const add_regex = /\|\+(.*?)\+\|/gs; // Changed to match across lines
let delete_match;
let add_match;
let ranges = [];
while ((delete_match = delete_regex.exec(docText)) !== null) {
const start = delete_match.index;
const end = delete_regex.lastIndex;
ranges.push({ start, end, style: "background-color: #f56c62;" });
}
while ((add_match = add_regex.exec(docText)) !== null) {
const start = add_match.index;
const end = add_regex.lastIndex;
ranges.push({ start, end, style: "background-color: #64f562;" });
}
// Sort ranges by start position
ranges.sort((a, b) => a.start - b.start);
// Add sorted ranges to the builder
ranges.forEach((range) => {
builder.add(
range.start,
range.end,
Decoration.mark({
attributes: { style: range.style },
})
);
});
return builder.finish();
},
provide(field: StateField<DecorationSet>): Extension {
return EditorView.decorations.from(field);
},
});
export class InsertNoteModal extends Modal {
plugin: any;
current_view: any;
constructor(app: App, plugin: any, view: any) {
super(app);
this.plugin = plugin;
this.current_view = view;
}
onOpen() {
const { contentEl } = this;
const all_files = this.app.vault.getFiles();
console.log(all_files);
const html_insert_files = contentEl.createEl("p", {
text: "Insert File",
cls: "insert-file-header",
});
// Create a text input for filtering files
const inputField = contentEl.createEl("input", {
type: "text",
placeholder: "Enter text to search files",
cls: "file-filter-input",
});
// Function to filter files based on input text and limit to 10 results
const filter_files = (input_text) => {
const fuse_options = {
keys: ["name"],
includeScore: true,
threshold: 0.3,
};
const fuse = new Fuse(all_files, fuse_options);
const results = fuse.search(input_text);
return results.map((result) => result.item).slice(0, 10);
};
// Display the filtered files
const filesDisplay = contentEl.createEl("div", { cls: "insert-file-files-display" });
let currentSelectedIndex = -1; // -1 means the input field is selected
// Function to update the visual selection
const updateSelection = () => {
const fileElements = filesDisplay.querySelectorAll(".insert-file-file-name");
fileElements.forEach((el, index) => {
if (index === currentSelectedIndex) {
el.classList.add("selected");
el.scrollIntoView({ block: "nearest" });
} else {
el.classList.remove("selected");
}
});
};
// Update display when input changes
inputField.addEventListener("input", () => {
const filtered_files = filter_files(inputField.value);
console.log(filtered_files);
// Clear previous file display
filesDisplay.innerHTML = "";
// Add filtered files to the display
filtered_files.forEach((file) => {
const fileElement = filesDisplay.createEl("div", { text: file.name, cls: "insert-file-file-name" });
fileElement.addEventListener("click", () => {
console.log(`File selected: ${file.name}`);
console.log(this.current_view);
if (this.current_view.getViewType() === "main-caret") {
console.log("Inserting into user message");
this.current_view.insert_text_into_user_message(`[[${file.name}]]`);
this.current_view.focusAndPositionCursorInTextBox();
this.close();
}
});
});
// Reset selection
currentSelectedIndex = -1;
updateSelection();
});
// Keyboard navigation
inputField.addEventListener("keydown", (event) => {
const fileElements = filesDisplay.querySelectorAll(".insert-file-file-name");
if (event.key === "ArrowDown") {
if (currentSelectedIndex < fileElements.length - 1) {
currentSelectedIndex++;
updateSelection();
event.preventDefault(); // Prevent scrolling the page
}
} else if (event.key === "ArrowUp") {
if (currentSelectedIndex > -1) {
currentSelectedIndex--;
updateSelection();
event.preventDefault(); // Prevent scrolling the page
}
} else if (event.key === "Enter" && currentSelectedIndex >= 0) {
event.preventDefault(); // Prevent adding an extra line break
fileElements[currentSelectedIndex].click();
}
});
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
interface CaretPluginSettings {
model: string;
llm_provider: string;
openai_api_key: string;
groq_api_key: string;
context_window: number;
}
const DEFAULT_SETTINGS: CaretPluginSettings = {
model: "",
llm_provider: "",
openai_api_key: "",
groq_api_key: "",
context_window: 0,
};
// export const VIEW_NAME_SIDEBAR_CHAT = "sidebar-caret";
// class SidebarChat extends ItemView {
// constructor(leaf: WorkspaceLeaf) {
// super(leaf);
// }
// textBox: HTMLTextAreaElement;
// messagesContainer: HTMLElement; // Container for messages
// getViewType() {
// return VIEW_NAME_SIDEBAR_CHAT;
// }
// getDisplayText() {
// return VIEW_NAME_SIDEBAR_CHAT;
// }
// async onOpen() {
// const metacontainer = this.containerEl.children[1];
// metacontainer.empty();
// const container = metacontainer.createEl("div", {
// cls: "container",
// });
// metacontainer.prepend(container);
// // this.containerEl.appendChild(container);
// // Create a container for messages
// this.messagesContainer = container.createEl("div", {
// cls: "messages-container",
// });
// // Add a "Hello World" message
// this.addMessage("MLX Testing", "system");
// this.createChatInputArea(container);
// }
// createChatInputArea(container: HTMLElement) {
// // Create a container for the text box and the submit button
// const inputContainer = container.createEl("div", {
// cls: "chat-input-container",
// });
// // Create the text box within the input container
// this.textBox = inputContainer.createEl("textarea", {
// cls: "full_width_text_container",
// });
// this.textBox.placeholder = "Type something...";
// // Create the submit button within the input container
// const button = inputContainer.createEl("button");
// button.textContent = "Submit";
// button.addEventListener("click", () => {
// this.submitMessage(this.textBox.value);
// this.textBox.value = ""; // Clear the text box after sending
// });
// }
// addMessage(text: string, sender: "user" | "system") {
// const messageDiv = this.messagesContainer.createEl("div", {
// cls: `message ${sender}`,
// });
// messageDiv.textContent = text;
// }
// submitMessage(userMessage: string) {
// let current_page_content = "";
// if (userMessage.includes("@current")) {
// // Find the first MarkdownView that is open in the workspace
// const markdownView = this.app.workspace
// .getLeavesOfType("markdown")
// // @ts-ignore
// .find((leaf) => leaf.view instanceof MarkdownView && leaf.width > 0)?.view as MarkdownView;
// if (markdownView && markdownView.editor) {
// current_page_content = markdownView.editor.getValue();
// }
// }
// this.addMessage(userMessage, "user"); // Display the user message immediately
// const current_page_message = `
// ${userMessage}
// ------ Note for Model ---
// When I am referring to @current, I meant the following:
// ${current_page_content}
// `;
// let final_message = userMessage;
// if (current_page_content.length > 0) {
// final_message = current_page_message;
// }
// const data = { message: final_message };
// fetch("http://localhost:8000/conversation", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify(data),
// })
// .then((response) => response.json())
// .then((data) => {
// this.addMessage(data.response, "system"); // Display the response
// })
// .catch((error) => {
// console.error("Error:", error);
// });
// }
// async onClose() {
// // Cleanup logic if necessary
// }
// }
export const VIEW_NAME_MAIN_CHAT = "main-caret";
class FullPageChat extends ItemView {
chat_id: string;
plugin: any;
conversation_title: string;
textBox: HTMLTextAreaElement;
messagesContainer: HTMLElement; // Container for messages
conversation: Message[]; // List to store conversation messages
constructor(plugin: any, leaf: WorkspaceLeaf, chat_id?: string, conversation: Message[] = []) {
super(leaf);
this.plugin = plugin;
this.chat_id = chat_id || this.generateRandomID(5);
this.conversation = conversation; // Initialize conversation list with default or passed value
}
getViewType() {
return VIEW_NAME_MAIN_CHAT;
}
getDisplayText() {
return `Provider ${this.plugin.settings.llm_provider} | Model ${this.plugin.settings.model} | Chat: ${this.chat_id}`;
}
async onOpen() {
const metacontainer = this.containerEl.children[1];
metacontainer.empty();
const container = metacontainer.createEl("div", {
cls: "container",
});
metacontainer.prepend(container);
// Create a container for messages
this.messagesContainer = container.createEl("div", {
cls: "messages-container",
});
// Render initial conversation
this.renderConversation();
this.createChatInputArea(container);
}
createChatInputArea(container: HTMLElement) {
// Create a container for the text box
const inputContainer = container.createEl("div", {});
// Create the text box within the input container
this.textBox = inputContainer.createEl("textarea", {
cls: "full_width_text_container",
});
this.textBox.placeholder = "Type something...";
this.textBox.addEventListener("keydown", (event) => {
if (event.key === "@") {
event.preventDefault(); // Prevent the default action
this.textBox.value += "@"; // Add the '@' sign to the textBox value
console.log("The '@' key was pressed.");
new InsertNoteModal(this.app, this.plugin, this).open(); // Open the modal
}
});
// Create a separate container for buttons within the input container
const buttonContainer = inputContainer.createEl("div", {
cls: "button-container",
});
// Create the submit button within the button container
const submitButton = buttonContainer.createEl("button", {});
submitButton.textContent = "Submit";
const submitAction = () => {
this.submitMessage(this.textBox.value);
this.textBox.value = ""; // Clear the text box after sending
};
submitButton.addEventListener("click", submitAction);
this.textBox.addEventListener("keydown", (event) => {
if (event.shiftKey && event.key === "Enter") {
event.preventDefault(); // Prevent the default action of a newline
submitAction();
}
});
}
addMessage(text: string, sender: "user" | "assistant") {
// Add message to the conversation array
this.conversation.push({ content: text, role: sender });
// Re-render the conversation in the HTML
this.renderConversation();
}
async streamMessage(stream_response) {
if (this.plugin.settings.llm_provider === "ollama") {
for await (const part of stream_response) {
this.conversation[this.conversation.length - 1].content += part.message.content;
this.renderConversation();
}
}
if (this.plugin.settings.llm_provider === "openai" || "groq") {
for await (const part of stream_response) {
const delta_content = part.choices[0]?.delta.content || "";
this.conversation[this.conversation.length - 1].content += delta_content;
this.renderConversation();
}
}
}
renderConversation() {
// Clear the current messages
this.messagesContainer.empty();
// Add each message in the conversation to the messages container
this.conversation.forEach((message) => {
const display_class = `message ${message.role}`;
const messageDiv = this.messagesContainer.createEl("div", {
cls: display_class,
});
messageDiv.textContent = message.content;
});
setTimeout(() => {
this.saveChat();
}, 200);
}
async submitMessage(userMessage: string) {
const user_message_tokens = this.plugin.encoder.encode(userMessage).length;
if (user_message_tokens > this.plugin.settings.context_window) {
new Notice(
`Single message exceeds model context window. Can't submit. Please shorten message and try again`
);
return;
}
this.addMessage(userMessage, "user");
let total_context_length = 0;
let valid_conversation = [];
for (let i = 0; i < this.conversation.length; i++) {
let message = this.conversation[i];
let modified_content = message.content;
console.log(`Message ${i.toString()} -${message.content} `);
// Check for text in double brackets and log the match
const bracket_regex = /\[\[(.*?)\]\]/g;
const match = bracket_regex.exec(modified_content);
if (match) {
const file_path = match[1];
const file = await this.app.vault.getFileByPath(file_path);
if (file) {
const file_content = await this.app.vault.cachedRead(file);
modified_content += file_content; // Update modified_content instead of message.content
} else {
new Notice(`File not found: ${file_path}`);
}
}
const encoded_message = this.plugin.encoder.encode(modified_content);
const message_length = encoded_message.length;
if (total_context_length + message_length > this.plugin.context_window) {
break;
}
total_context_length += message_length;
valid_conversation.push({ ...message, content: modified_content }); // Push modified content in a hidden way
}
console.log({ valid_conversation });
const response = await this.plugin.llm_call_streaming(
this.plugin.settings.llm_provider,
this.plugin.settings.model,
valid_conversation
);
this.addMessage("", "assistant"); // Display the response
this.streamMessage(response);
}
focusAndPositionCursorInTextBox() {
this.textBox.focus();
}
insert_text_into_user_message(text: string) {
this.textBox.value += text.trim() + " ";
}
escapeXml(unsafe: string): string {
return unsafe.replace(/[<>&'"]/g, (c) => {
switch (c) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
default:
return c;
}
});
}
async saveChat() {
const chat_folder_path = "caret/chats";
const chat_folder = this.app.vault.getAbstractFileByPath(chat_folder_path);
if (!chat_folder) {
await this.app.vault.createFolder(chat_folder_path);
}
const file_name = `${this.chat_id}.md`;
const file_path = chat_folder_path + "/" + file_name;
let file_content = `\`\`\`xml
<root>
<metadata>\n<id>${this.chat_id}</id>\n</metadata>
`;
let messages = ``;
if (this.conversation.length === 0) {
return;
}
for (let i = 0; i < this.conversation.length; i++) {
const message = this.conversation[i];
const escaped_content = this.escapeXml(message.content);
const message_xml = `
<message>
<role>${message.role}</role>
<content>${escaped_content}</content>
</message>
`.trim();
messages += message_xml;
}
let conversation = `<conversation>\n${messages}</conversation></root>\`\`\``;
file_content += conversation;
const file = await this.app.vault.getFileByPath(file_path);
try {
if (file) {
await this.app.vault.modify(file, file_content);
} else {
await this.app.vault.create(file_path, file_content);
}
} catch (error) {
console.error("Failed to save chat:", error);
}
}
generateRandomID(length: number) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
async onClose() {
// Cleanup logic if necessary
}
}
export default class CaretPlugin extends Plugin {
settings: CaretPluginSettings;
canvas_patched: boolean = false;
selected_node_colors: any = {};
color_picker_open_on_last_click: boolean = false;
openai_client: OpenAI;
groq_client: Groq;
encoder: any;
async onload() {
this.encoder = encodingForModel("gpt-4-0125-preview");
await this.loadSettings();
if (this.settings.openai_api_key) {
this.openai_client = new OpenAI({ apiKey: this.settings.openai_api_key, dangerouslyAllowBrowser: true });
}
if (this.settings.groq_api_key) {
this.groq_client = new Groq({ apiKey: this.settings.groq_api_key, dangerouslyAllowBrowser: true });
}
this.addSettingTab(new CaretSettingTab(this.app, this));
this.addCommand({
id: "patch-menu",
name: "Patch Menu",
callback: async () => {
this.patchCanvasMenu();
},
});
this.registerEvent(this.app.workspace.on("layout-change", () => {}));
const that = this;
this.registerEvent(
this.app.workspace.on("active-leaf-change", (event) => {
const currentLeaf = this.app.workspace.activeLeaf;
this.unhighlight_lineage();
if (currentLeaf?.view.getViewType() === "canvas") {
const canvas = currentLeaf.view;
// this.canvas_patched = false;
this.patchCanvasMenu();
}
})
);
this.registerEditorExtension([redBackgroundField]);
// Register the sidebar icon
this.addChatIconToRibbon();
this.addCommand({
id: "caret-log",
name: "Log",
callback: async () => {
const currentLeaf = this.app.workspace.activeLeaf;
const path = "caret/chats";
const folder = this.app.vault.getFolderByPath(path);
if (currentLeaf?.view.getViewType() === "canvas") {
const canvasView = currentLeaf.view;
const canvas = (canvasView as any).canvas;
const viewportNodes = canvas.getViewportNodes();
}
console.log(currentLeaf);
console.log(currentLeaf?.view);
},
});
this.addCommand({
id: "insert-note",
name: "Insert Note",
callback: async () => {
const currentLeaf = this.app.workspace.activeLeaf;
if (!currentLeaf) {
new Notice("No active leaf");
return;
}
const view = currentLeaf.view;
const view_type = view.getViewType();
// console.log("Workspace here");
// console.log(this.app.workspace);
// console.log("Current leaf here");
// console.log(currentLeaf);
// console.log({ view_type });
new InsertNoteModal(this.app, this, view).open();
},
});
this.addCommand({
id: "canvas-prompt",
name: "Canvas Prompt",
callback: async () => {
const currentLeaf = this.app.workspace.activeLeaf;
if (currentLeaf?.view.getViewType() === "canvas") {
const canvasView = currentLeaf.view;
const canvas = (canvasView as any).canvas;
const selection = canvas.selection;
let average_y = 0;
let average_height = 0;
let average_width = 0;
let max_x = 0;
let total_y = 0;
let count = 0;
let total_height = 0;
let total_width = 0;
let all_text = "";
for (const obj of selection) {
const { x, y, height, width } = obj;
max_x = Math.max(max_x, x);
total_y += y;
total_height += height;
total_width += width;
count++;
if ("text" in obj) {
const { text } = obj;
all_text += text + "\n";
} else if ("filePath" in obj) {
let { filePath } = obj;
const file = await this.app.vault.getFileByPath(filePath);
if (file) {
const text = await this.app.vault.read(file);
const file_text = `
Title: ${filePath.replace(".md", "")}
${text}
`.trim();
all_text += file_text;
}
}
}
average_y = count > 0 ? total_y / count : 0;
average_height = count > 0 ? total_height / count : 0;
average_width = count > 0 ? total_width / count : 0;
// This handles the model ---
// Create a modal with a text input and a submit button
const modal = new Modal(this.app);
modal.contentEl.createEl("h1", { text: "Canvas Prompt" });
const container = modal.contentEl.createDiv({ cls: "flex-col" });
const textArea = container.createEl("textarea", {
placeholder: "",
cls: "w-full mb-2",
});
const submitButton = container.createEl("button", { text: "Submit" });
submitButton.onclick = async () => {
modal.close();
const prompt = `
Please do the following:
${textArea.value}
Given this content:
${all_text}
`;
const conversation: Message[] = [{ role: "user", content: prompt }];
const message: Message = await this.llm_call(
this.settings.llm_provider,
this.settings.model,
conversation
);
const content = message.content;
const textNodeConfig = {
pos: { x: max_x + 50, y: average_y }, // Position on the canvas
size: { width: average_width, height: average_height }, // Size of the text box
position: "center", // This might relate to text alignment
text: content, // Text content from input
save: true, // Save this node's state
focus: true, // Focus and start editing immediately
};
// Create the text node on the canvas
const node = canvas.createTextNode(textNodeConfig);
const node_id = node.id;
node.color = "6";
node.zoomToSelection();
};
modal.open();
}
},
});
this.addCommand({
id: "inline-editing",
name: "Inline Editing",
hotkeys: [{ modifiers: ["Mod"], key: "j" }],
callback: () => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView && activeView.editor) {
const selectedText = activeView.editor.getSelection();
const content = activeView.editor.getValue();
const startIndex = content.indexOf(selectedText);
const endIndex = startIndex + selectedText.length;
new CMDJModal(this.app, selectedText, startIndex, endIndex, this).open();
} else {
new Notice("No active markdown editor or no text selected.");
}
},
});
// Register the custom view
// this.registerView(VIEW_NAME_SIDEBAR_CHAT, (leaf) => new SidebarChat(leaf));
this.registerView(VIEW_NAME_MAIN_CHAT, (leaf) => new FullPageChat(this, leaf));
// Define a command to insert text into the sidebar
// this.addCommand({
// id: "insert-text-into-sidebar",
// name: "Insert Text into Sidebar",
// hotkeys: [{ modifiers: ["Mod"], key: "l" }],
// callback: () => {
// const activeLeaf = this.app.workspace.activeLeaf;
// if (activeLeaf) {
// const editor = activeLeaf.view instanceof MarkdownView ? activeLeaf.view.editor : null;
// if (editor) {
// const selectedText = editor.getSelection();
// this.insertTextIntoSidebar(selectedText);
// }
// }
// },
// });
// // Define a command to clear text from the sidebar
// this.addCommand({
// id: "clear-text-in-sidebar",
// name: "Clear Text in Sidebar",
// hotkeys: [{ modifiers: ["Mod"], key: ";" }],
// callback: () => {
// this.clearTextInSidebar();
// },
// });
this.addCommand({
id: "open-chat",
name: "Open Chat",
callback: async () => {
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
if (editor) {
let content = editor.getValue();
content = content.replace("```xml", "").trim();
content = content.replace("```", "").trim();
const xml_object = await this.parseXml(content);
const convo_id = xml_object.root.metadata[0].id[0];
const messages_from_xml = xml_object.root.conversation[0].message;
const messages: Message[] = [];
if (messages_from_xml) {
for (let i = 0; i < messages_from_xml.length; i++) {
const role = messages_from_xml[i].role[0];
const content = messages_from_xml[i].content[0];
messages.push({ role, content });
}
}
if (convo_id && messages) {
const leaf = this.app.workspace.getLeaf(true);
const chatView = new FullPageChat(this, leaf, convo_id, messages);
leaf.open(chatView);
this.app.workspace.revealLeaf(leaf);
} else {
new Notice("No valid chat data found in the current document.");
}
} else {
new Notice("No active markdown editor found.");
}
},
});
this.addCommand({
id: "apply-diffs",
name: "Apply Diffs",
hotkeys: [{ modifiers: ["Mod"], key: "d" }],
callback: () => {
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
if (editor) {
let content = editor.getValue();
// Regex to find |-content-|
const deleteRegex = /\|-(.*?)-\|/gs;
// Regex to find |+content+|
// Replace all instances of |-content-| with empty string
content = content.replace(deleteRegex, "");
// Replace all instances of |+content+| with empty string
// @ts-ignore
content = content.replaceAll("|+", "");
// @ts-ignore
content = content.replaceAll("+|", "");
// Set the modified content back to the editor
editor.setValue(content);
new Notice("Dips applied successfully.");
} else {
new Notice("No active markdown editor found.");
}
},
});
}
async highlight_lineage() {
await new Promise((resolve) => setTimeout(resolve, 200)); // Sleep for 200 milliseconds
const canvas_view = this.app.workspace.getMostRecentLeaf()?.view;
// @ts-ignore
if (!canvas_view?.canvas) {
return;
}
const canvas = (canvas_view as any).canvas; // Assuming canvas is a property of the view
const selection = canvas.selection;
const selection_iterator = selection.values();
const node = selection_iterator.next().value;
if (!node) {