Initial commit

This commit is contained in:
James Griffing 2023-11-08 07:34:00 -08:00
parent 7112f01bc6
commit 6fcc8e204f
2 changed files with 2354 additions and 116 deletions

241
main.ts
View File

@ -1,134 +1,143 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; import {
MarkdownPostProcessorContext,
Plugin,
MarkdownRenderChild,
TFile
} from 'obsidian';
// Remember to rename these classes and interfaces! interface IPluginSettings {
customSetting: string;
interface MyPluginSettings {
mySetting: string;
} }
const DEFAULT_SETTINGS: MyPluginSettings = { const DEFAULT_SETTINGS: IPluginSettings = {
mySetting: 'default' customSetting: 'defaultValue',
} };
export default class MyPlugin extends Plugin { class EnhancedMessagingPlugin extends Plugin {
settings: MyPluginSettings; settings: IPluginSettings;
async onload() { async onload(): Promise<void> {
await this.loadSettings(); await this.loadSettings();
// This creates an icon in the left ribbon. this.registerMarkdownCodeBlockProcessor('gpt', async (source, element, context) => {
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => { await this.processGptBlocks(source, element, context);
// Called when the user clicks the icon.
new Notice('This is a notice!');
}); });
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
} }
onunload() { onunload(): void {
console.log('Unloading EnhancedMessagingPlugin');
} }
async loadSettings() { private async loadSettings(): Promise<void> {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
} }
async saveSettings() { private async processGptBlocks(
await this.saveData(this.settings); source: string,
element: HTMLElement,
context: MarkdownPostProcessorContext
): Promise<void> {
const messagesContainer = document.createElement('div');
messagesContainer.classList.add('gpt-messages');
const sectionInfo = await context.getSectionInfo(element);
console.log(sectionInfo);
const inputField = document.createElement('input');
inputField.type = 'text';
inputField.classList.add('gpt-input');
element.appendChild(messagesContainer);
element.appendChild(inputField);
const messages = this.parseSource(source);
messages.forEach((message: { role: string; content: string }) => {
this.appendMessage(message, messagesContainer);
});
inputField.addEventListener('keyup', async (event) => {
await this.handleKeyUp(event, messages, inputField, messagesContainer, context);
});
context.addChild(new MarkdownRenderChild(element));
}
private async handleKeyUp(
event: KeyboardEvent,
messages: { role: string; content: string }[],
inputField: HTMLInputElement,
messagesContainer: HTMLElement,
context: MarkdownPostProcessorContext
): Promise<void> {
if (event.key === 'Enter') {
const content = inputField.value.trim();
if (content) {
const newMessage = { role: 'user', content };
messages.push(newMessage);
this.appendMessage(newMessage, messagesContainer);
await this.updateSource(messages, messagesContainer, context);
inputField.value = '';
}
}
}
private appendMessage(message: { role: string; content: string }, container: HTMLElement): void {
const messageElement = document.createElement('div');
messageElement.classList.add('gpt-message', `gpt-message-${message.role}`);
messageElement.textContent = message.content;
container.appendChild(messageElement);
}
// The updateSource function now awaits the read operation
private async updateSource(
messages: { role: string; content: string }[],
messagesContainer: HTMLElement,
context: MarkdownPostProcessorContext
): Promise<void> {
const file = this.app.vault.getAbstractFileByPath(context.sourcePath) as TFile;
if (!file) {
return;
}
const content = await this.app.vault.read(file); // Await reading the file content
const lines = content.split('\n');
const sectionInfo = context.getSectionInfo(messagesContainer);
if (!sectionInfo) {
console.error('Section info is null.');
return;
}
const { lineStart: startLine, lineEnd: endLine } = sectionInfo;
// Remove the old messages
lines.splice(startLine, endLine - startLine + 1);
// Prepare new message lines in the correct format
const messageLines = messages.map(message =>
`{"role": "${message.role}", "content": "${message.content}" }`
);
const newLines = `\`\`\`gpt\n[${messageLines.join(',\n')}]\n\`\`\``;
// Insert the new messages
lines.splice(startLine, 0, newLines);
// Join the lines back together and write the content
await this.app.vault.modify(file, lines.join('\n'));
}
private parseSource(source: string): { role: string; content: string }[] {
try {
return JSON.parse(source) || [];
} catch (error) {
console.error('Error parsing GPT block source:', error);
return [];
}
} }
} }
class SampleModal extends Modal { export default EnhancedMessagingPlugin;
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
}

2229
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff