diff --git a/.editorconfig b/.editorconfig index 84b8a66..81f3ec3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,10 +1,10 @@ -# top-most EditorConfig file -root = true - -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -indent_style = tab -indent_size = 4 -tab_width = 4 +# top-most EditorConfig file +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 4 +tab_width = 4 diff --git a/.eslintrc b/.eslintrc index 0807290..551b0a8 100644 --- a/.eslintrc +++ b/.eslintrc @@ -11,13 +11,16 @@ "plugin:@typescript-eslint/recommended" ], "parserOptions": { - "sourceType": "module" + "sourceType": "module", + "ecmaVersion": 12 }, "rules": { "no-unused-vars": "off", + "no-mixed-spaces-and-tabs": "error", "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], "@typescript-eslint/ban-ts-comment": "off", "no-prototype-builtins": "off", - "@typescript-eslint/no-empty-function": "off" + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-extra-semi": "error" } } \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..afce94f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +* text=auto eol=lf +# Files with Unix line endings +*.ts text eol=lf +*.js text eol=lf +*.jsx text eol=lf +*.mjs text eol=lf +*.json text eol=lf +*.sh text eol=lf +*.md text eol=lf \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..6237a71 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,20 @@ +name: build + +on: + push: + branches: ["master"] + pull_request: + branches: ["master"] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 14 + - run: npm install + - run: npm run lint + - run: npm run build \ No newline at end of file diff --git a/.gitignore b/.gitignore index e09a007..b5b913d 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ node_modules # Don't include the compiled main.js file in the repo. # They should be uploaded to GitHub releases instead. -main.js +# main.js # Exclude sourcemaps *.map diff --git a/README.md b/README.md index 31e5155..e79cc40 100644 --- a/README.md +++ b/README.md @@ -1,96 +1,54 @@ -# Obsidian Sample Plugin +# Lightweight ChatGPT Plugin for Obsidian -This is a sample plugin for Obsidian (https://obsidian.md). +With this Lightweight ChatGPT Plugin, you can quickly and senselessly generate ideas, draft content, or get assistance from the ChatGPT AI, all without leaving Obsidian, without interrupt your creative flow. -This project uses Typescript to provide type checking and documentation. -The repo depends on the latest plugin API (obsidian.d.ts) in Typescript Definition format, which contains TSDoc comments describing what it does. +The Lightweight ChatGPT Plugin is a fast, easy-to-use, and non-intrusive AI assistant plugin, which senselessly integrates OpenAI's ChatGPT API directly into Obsidian. -**Note:** The Obsidian API is still in early alpha and is subject to change at any time! +If you enjoy this plugin or would like to show your support, please consider giving it a free star on GitHub ~ -This sample plugin demonstrates some of the basic functionality the plugin API can do. -- Changes the default font color to red using `styles.css`. -- Adds a ribbon icon, which shows a Notice when clicked. -- Adds a command "Open Sample Modal" which opens a Modal. -- Adds a plugin setting tab to the settings page. -- Registers a global click event and output 'click' to the console. -- Registers a global interval which logs 'setInterval' to the console. -## First time developing plugins? -Quick starting guide for new plugin devs: +## Features -- Check if [someone already developed a plugin for what you want](https://obsidian.md/plugins)! There might be an existing plugin similar enough that you can partner up with. -- Make a copy of this repo as a template with the "Use this template" button (login to GitHub if you don't see it). -- Clone your repo to a local development folder. For convenience, you can place this folder in your `.obsidian/plugins/your-plugin-name` folder. -- Install NodeJS, then run `npm i` in the command line under your repo folder. -- Run `npm run dev` to compile your plugin from `main.ts` to `main.js`. -- Make changes to `main.ts` (or create new `.ts` files). Those changes should be automatically compiled into `main.js`. -- Reload Obsidian to load the new version of your plugin. -- Enable plugin in settings window. -- For updates to the Obsidian API run `npm update` in the command line under your repo folder. +- **Seamless integration with Obsidian:** + - Enjoy the convenience of accessing lightweight ChatGPT directly within Obsidian. + - You no longer have to worry about being interrupted in your creative process by leaving Obsidian to switch between software. +- **User-friendly interface:** + - Interact with the ChatGPT API through an intuitive and straightforward lightweight design interface. +- **Direct API access:** + - Send text to OpenAI's ChatGPT API and receive responses directly in Obsidian, quickly enriching your content or generating new ideas. +- **Flexible response handling:** + - Copy the AI-generated response to the clipboard. Alternatively, insert it directly at the cursor position in your current document, or at the end of the document. -## Releasing new releases -- Update your `manifest.json` with your new version number, such as `1.0.1`, and the minimum Obsidian version required for your latest release. -- Update your `versions.json` file with `"new-plugin-version": "minimum-obsidian-version"` so older versions of Obsidian can download an older version of your plugin that's compatible. -- Create new GitHub release using your new version number as the "Tag version". Use the exact version number, don't include a prefix `v`. See here for an example: https://github.com/obsidianmd/obsidian-sample-plugin/releases -- Upload the files `manifest.json`, `main.js`, `styles.css` as binary attachments. Note: The manifest.json file must be in two places, first the root path of your repository and also in the release. -- Publish the release. -> You can simplify the version bump process by running `npm version patch`, `npm version minor` or `npm version major` after updating `minAppVersion` manually in `manifest.json`. -> The command will bump version in `manifest.json` and `package.json`, and add the entry for the new version to `versions.json` +## Configuration -## Adding your plugin to the community plugin list +You need to first set your own OpenAI API key in the Plugin Settings , so that the plugin can work properly. -- Check https://github.com/obsidianmd/obsidian-releases/blob/master/plugin-review.md -- Publish an initial version. -- Make sure you have a `README.md` file in the root of your repo. -- Make a pull request at https://github.com/obsidianmd/obsidian-releases to add your plugin. +1. Generate an OpenAI API key on the official website. [Click here](https://beta.openai.com/account/api-keys) +2. In Obsidian, go to `Settings`, click `Community Plugins` in the left menu , and enable `Lightweight ChatGPT Plugin` in the Installed Plugins. +3. Click the gear icon to enter the plugin settings. Then enter your API key in the `OpenAI API Key` field. -## How to use +To download Obsidian: [Click here](https://www.obsidian.md/) -- Clone this repo. -- `npm i` or `yarn` to install dependencies -- `npm run dev` to start compilation in watch mode. +To view the plugin page: [Click here](https://obsidian.md/plugins?id=lightweight-chatgpt-plugin) -## Manually installing the plugin +## Usage -- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`. +You can open the Lightweight ChatGPT Plugin window in three ways: -## Improve code quality with eslint (optional) -- [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code. -- To use eslint with this project, make sure to install eslint from terminal: - - `npm install -g eslint` -- To use eslint to analyze this project use this command: - - `eslint main.ts` - - eslint will then create a report with suggestions for code improvement by file and line number. -- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder: - - `eslint .\src\` +- By clicking on the Obsidian ribbon on the left. -## Funding URL +- By the keyboard shortcuts `ALT + C `. +- By the Obsidian command `Open Lightweight ChatGPT Plugin Window`. -You can include funding URLs where people who use your plugin can financially support it. +In the Lightweight ChatGPT Plugin Window, the content you selected in the current Markdown document will be copied to the text box automatically. So you can use this text to ask questions or perform other operations, or directly write down anything you want to say. -The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file: +Tips: You can also send content directly using the `CTRL + ENTER` shortcut. -```json -{ - "fundingUrl": "https://buymeacoffee.com" -} -``` -If you have multiple URLs, you can also do: -```json -{ - "fundingUrl": { - "Buy Me a Coffee": "https://buymeacoffee.com", - "GitHub Sponsor": "https://github.com/sponsors", - "Patreon": "https://www.patreon.com/" - } -} -``` -## API Documentation -See https://github.com/obsidianmd/obsidian-api +Lightweight ChatGPT Plugin for Obsidian wants to be a nice companion to boost your creativity and productivity. Experience the seamless AI-enhanced writing and content generation capabilities within Obsidian today! \ No newline at end of file diff --git a/main.js b/main.js new file mode 100644 index 0000000..d19e5f5 --- /dev/null +++ b/main.js @@ -0,0 +1,406 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// main.ts +var main_exports = {}; +__export(main_exports, { + default: () => LightweightChatGPTPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian = require("obsidian"); +var DEFAULT_SETTINGS = { + apiKey: "", + maxTokens: 16, + temperature: 1, + chatGPTModel: "gpt-3.5-turbo", + insertionMode: "end", + showSidebarIcon: true +}; +var LightweightChatGPTPlugin = class extends import_obsidian.Plugin { + async onload() { + try { + await this.loadSettings(); + } catch (error) { + console.error("Error loading settings:", error); + } + this.app.workspace.onLayoutReady(() => { + if (this.settings.showSidebarIcon) { + this.addSidebarIcon(); + } + }); + this.addCommand({ + id: "lightweight-chatgpt-window-hotkey", + name: "Open Lightweight ChatGPT Plugin Window", + callback: () => { + try { + new LightweightChatGPTWindow(this.app, this.settings.apiKey, this.settings.temperature, this.settings.maxTokens, this.settings.insertionMode).open(); + } catch (error) { + console.error("Error opening Lightweight ChatGPT Plugin Window:", error); + } + }, + hotkeys: [ + { + modifiers: ["Alt"], + key: "c" + } + ] + }); + try { + this.addSettingTab(new LightweightChatGPTSettingTab(this.app, this)); + } catch (error) { + console.error("Error adding settings tab:", error); + } + } + addSidebarIcon() { + try { + this.ribbonIconEl = this.addRibbonIcon("feather", "Lightweight ChatGPT Plugin Window", (evt) => { + try { + new LightweightChatGPTWindow(this.app, this.settings.apiKey, this.settings.temperature, this.settings.maxTokens, this.settings.insertionMode).open(); + } catch (error) { + console.error("Error opening Lightweight ChatGPT Plugin Window:", error); + } + }); + } catch (error) { + console.error("Error adding sidebar icon:", error); + } + this.ribbonIconEl.addClass("lightweight-chatgpt-ribbon-class"); + } + removeSidebarIcon() { + if (this.ribbonIconEl) { + try { + this.ribbonIconEl.remove(); + } catch (error) { + console.error("Error closing sidebar icon:", error); + } + } + } + onunload() { + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + async saveSettings() { + await this.saveData(this.settings); + } +}; +var LightweightChatGPTWindow = class extends import_obsidian.Modal { + constructor(app, apiKey, temperature, maxTokens, insertionMode) { + super(app); + this.apiKey = apiKey; + this.temperature = temperature; + this.maxTokens = maxTokens; + this.insertionMode = insertionMode; + } + onOpen() { + const { contentEl } = this; + contentEl.createEl("h2", { text: "Lightweight ChatGPT Plugin Window" }); + const activeView = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView); + const selectedText = activeView ? activeView.editor.getSelection() : ""; + this.inputTextArea = contentEl.createEl("textarea"); + this.inputTextArea.rows = 4; + this.inputTextArea.style.width = "100%"; + this.inputTextArea.placeholder = "Enter your text here ..."; + this.inputTextArea.value = selectedText ? `${selectedText} +==== +` : ""; + this.inputTextArea.addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey && !event.ctrlKey) { + event.preventDefault(); + this.insertAtCursor(this.inputTextArea, "\n"); + } else if (event.key === "Enter" && event.ctrlKey) { + event.preventDefault(); + sendButton.click(); + } + }); + contentEl.createEl("hr"); + const maxTokensContainer = contentEl.createEl("div"); + maxTokensContainer.style.display = "flex"; + maxTokensContainer.style.justifyContent = "space-between"; + maxTokensContainer.style.alignItems = "center"; + maxTokensContainer.style.marginTop = "1rem"; + const maxTokensLabelContainer = maxTokensContainer.createEl("div"); + maxTokensLabelContainer.createEl("label", { text: "Max tokens:" }); + const maxTokensDescription = maxTokensLabelContainer.createEl("p", { text: "Max OpenAI ChatGpt Tokens" }); + maxTokensDescription.style.fontSize = "0.8rem"; + maxTokensDescription.style.marginTop = "0.25rem"; + maxTokensDescription.style.marginRight = "0.5rem"; + this.maxTokensInput = maxTokensContainer.createEl("input", { type: "number" }); + this.maxTokensInput.placeholder = "Enter max Tokens number"; + this.maxTokensInput.style.width = "40%"; + this.maxTokensInput.style.height = "calc(1.5em + 1.25em)"; + this.maxTokensInput.style.textAlign = "right"; + this.maxTokensInput.min = "1"; + this.maxTokensInput.max = "2048"; + this.maxTokensInput.value = this.maxTokens.toString(); + this.maxTokensInput.addEventListener("input", () => { + if (parseInt(this.maxTokensInput.value) > parseInt(this.maxTokensInput.max)) { + this.maxTokensInput.value = this.maxTokensInput.max; + new import_obsidian.Notice(`Max tokens cannot exceed ${this.maxTokensInput.max}`); + } else if (!parseInt(this.maxTokensInput.value) && parseInt(this.maxTokensInput.value) < parseInt(this.maxTokensInput.min)) { + this.maxTokensInput.value = this.maxTokensInput.min; + new import_obsidian.Notice(`Max tokens cannot be less than ${this.maxTokensInput.min}`); + } + }); + const buttonSendContainer = contentEl.createEl("div"); + buttonSendContainer.style.marginTop = "1rem"; + const sendButton = buttonSendContainer.createEl("button", { + text: "Send" + }, (el) => { + el.style.backgroundColor = "green"; + el.style.color = "white"; + }); + const responseDivider = contentEl.createEl("hr"); + responseDivider.style.display = "none"; + this.outputContainer = contentEl.createEl("div"); + this.outputContainer.style.whiteSpace = "pre-wrap"; + this.outputContainer.style.userSelect = "text"; + const buttonsContainer = contentEl.createEl("div"); + buttonsContainer.style.display = "flex"; + buttonsContainer.style.marginTop = "1rem"; + const copyToClipboardButton = buttonsContainer.createEl("button", { + text: "Copy to clipboard" + }, (el) => { + el.style.backgroundColor = "green"; + el.style.color = "white"; + }); + copyToClipboardButton.style.marginRight = "1rem"; + copyToClipboardButton.style.display = "none"; + const addToPostButton = buttonsContainer.createEl("button", { text: "Add to current document" }); + addToPostButton.style.marginRight = "1rem"; + addToPostButton.style.display = "none"; + sendButton.addEventListener("click", async () => { + if (!parseInt(this.maxTokensInput.value)) { + new import_obsidian.Notice(`Use the default value of ${this.maxTokens.toString()} for max Tokens`); + this.maxTokensInput.value = this.maxTokens.toString(); + } + if (!this.inputTextArea.value) { + new import_obsidian.Notice("Please Enter text"); + return; + } + sendButton.textContent = "Sending ..."; + sendButton.textContent = "Waiting for API full response ..."; + copyToClipboardButton.style.display = "none"; + addToPostButton.style.display = "none"; + responseDivider.style.display = "none"; + try { + this.responseAPIText = await this.sendRequestToChatGPT(); + sendButton.textContent = "Send"; + copyToClipboardButton.style.display = "block"; + addToPostButton.style.display = "block"; + responseDivider.style.display = "block"; + } catch (error) { + sendButton.textContent = "Send"; + } + }); + copyToClipboardButton.addEventListener("click", () => { + this.copyToClipboard(this.responseAPIText); + }); + addToPostButton.addEventListener("click", () => { + this.appendToCurrentNote(this.inputTextArea.value, this.responseAPIText, this.insertionMode); + }); + } + async sendRequestToChatGPT() { + if (!this.apiKey) { + new import_obsidian.Notice("Please enter your API key in the plugin settings."); + return; + } + this.outputContainer.empty(); + new import_obsidian.Notice("Sending..."); + const apiUrl = "https://api.openai.com/v1/chat/completions"; + const maxTokens = parseInt(this.maxTokensInput.value); + try { + const response = await fetch(apiUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${this.apiKey}` + }, + body: JSON.stringify({ + model: "gpt-3.5-turbo", + max_tokens: maxTokens, + temperature: this.temperature, + messages: [ + { role: "user", content: this.inputTextArea.value } + ] + }) + }); + if (response.ok) { + const result = await response.json(); + const gptResponse = result.choices[0].message.content; + this.outputContainer.empty(); + this.outputContainer.createEl("p", { text: gptResponse }); + return gptResponse; + } else { + throw new Error(`API request failed with status: ${response.status}`); + } + } catch (error) { + console.error("Error during API request:", error); + new import_obsidian.Notice("Error during API request: " + error.message); + } + } + insertAtCursor(textArea, text) { + const startPos = textArea.selectionStart; + const endPos = textArea.selectionEnd; + textArea.value = textArea.value.substring(0, startPos) + text + textArea.value.substring(endPos, textArea.value.length); + textArea.selectionStart = startPos + text.length; + textArea.selectionEnd = startPos + text.length; + } + async appendToCurrentNote(sentText, receivedText, insertionMode) { + const receivedAPIText = receivedText || ""; + if (receivedAPIText.length <= 0) { + new import_obsidian.Notice("No text to add"); + return; + } + const activeView = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView); + const activeLeaf = activeView == null ? void 0 : activeView.leaf; + if (activeView && activeLeaf && activeLeaf.view instanceof import_obsidian.MarkdownView) { + const editor = activeLeaf.view.editor; + const formattedText = ` +--- + +${receivedAPIText} + +--- +`; + if (insertionMode === "end") { + const lastLine = editor.lastLine(); + editor.replaceRange(formattedText, { line: lastLine + 1, ch: 0 }); + } else if (insertionMode === "current") { + const cursorPosition = editor.getCursor(); + const currentLine = cursorPosition.line; + editor.replaceRange(formattedText, { line: currentLine + 1, ch: 0 }); + } + } else { + new import_obsidian.Notice("Cannot append content to the current view. Please open a markdown note."); + } + } + async copyToClipboard(receivedText) { + const receivedAPIText = receivedText || ""; + if (receivedAPIText.length > 0) { + navigator.clipboard.writeText(receivedAPIText).then(() => { + new import_obsidian.Notice("Copied to clipboard!"); + }).catch((error) => { + console.error("Error copying to clipboard:", error); + new import_obsidian.Notice("Error copying to clipboard"); + }); + } else { + new import_obsidian.Notice("No text to copy"); + } + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +}; +var LightweightChatGPTSettingTab = class extends import_obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("h2", { text: "Settings Lightweight ChatGPT Window" }); + new import_obsidian.Setting(containerEl).setName("OpenAI API Key").setDesc("Enter your OpenAI API key").addText((text) => text.setPlaceholder("Enter your API key").setValue(this.plugin.settings.apiKey).onChange(async (value) => { + this.plugin.settings.apiKey = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Default Max Tokens").setDesc("Enter the maximum number of tokens for the API response (integer, min: 1, max: 2048)").addText((text) => text.setPlaceholder("Enter max tokens").setValue(this.plugin.settings.maxTokens.toString()).onChange(async (value) => { + let parsedValue = parseInt(value); + if (parsedValue < 1) { + parsedValue = 1; + } else if (parsedValue > 2048) { + parsedValue = 2048; + } + this.plugin.settings.maxTokens = parsedValue; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Temperature").setDesc("Enter the temperature value between 0 and 2 (inclusive) for the API response").addText((text) => text.setPlaceholder("Enter temperature").setValue(this.plugin.settings.temperature.toString()).onChange(async (value) => { + let parsedValue = parseFloat(value); + if (parsedValue < 0) { + parsedValue = 0; + } else if (parsedValue > 2) { + parsedValue = 2; + } + this.plugin.settings.temperature = parsedValue; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("OpenAI Model").setDesc("Select the OpenAI model to use").addDropdown((dropDown) => dropDown.addOption("gpt-3.5-turbo", "gpt-3.5-turbo").setValue(this.plugin.settings.chatGPTModel).onChange(async (value) => { + this.plugin.settings.chatGPTModel = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Insertion Mode").setDesc("Choose how to insert text").addDropdown((dropdown) => dropdown.addOption("end", "Insert at end of document").addOption("current", "Insert at current position").setValue(this.plugin.settings.insertionMode).onChange(async (value) => { + this.plugin.settings.insertionMode = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Show Sidebar Icon").setDesc("Toggle to show or hide the sidebar icon").addToggle((toggle) => toggle.setValue(this.plugin.settings.showSidebarIcon).onChange(async (value) => { + this.plugin.settings.showSidebarIcon = value; + await this.plugin.saveSettings(); + if (value) { + this.plugin.addSidebarIcon(); + } else { + this.plugin.removeSidebarIcon(); + } + })); + const politeMessage = containerEl.createEl("p", { + cls: "polite-message" + }); + politeMessage.textContent = "If you enjoy this plugin or would like to show your support, please consider giving it a free star on GitHub~ Your appreciation means a lot to me!"; + politeMessage.style.marginBottom = "1rem"; + politeMessage.style.fontStyle = "italic"; + const githubLink = containerEl.createEl("div", { + cls: "github-link-container" + }); + const githubAnchor = githubLink.createEl("a", { + cls: "github-link" + }); + githubAnchor.href = "https://github.com/ittuann/obsidian-lightweight-chatgpt-plugin"; + githubAnchor.target = "_blank"; + githubAnchor.rel = "noopener"; + githubAnchor.createEl("span", { + text: "View on GitHub" + }); + const style = document.createElement("style"); + style.innerHTML = ` + .github-link-container { + margin-top: 2rem; + text-align: center; + } + .github-link { + color: #0366d6; + text-decoration: none; + border: 1px solid #0366d6; + border-radius: 4px; + padding: 0.5rem 1rem; + font-weight: bold; + transition: all 0.3s; + } + .github-link:hover { + background-color: #0366d6; + color: white; + text-decoration: none; + } + `; + containerEl.appendChild(style); + } +}; diff --git a/main.ts b/main.ts index 50b75f3..15276e6 100644 --- a/main.ts +++ b/main.ts @@ -1,81 +1,100 @@ -import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; +import { App, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; -// Remember to rename these classes and interfaces! - -interface MyPluginSettings { - mySetting: string; +interface LightweightChatGPTPluginSettings { + apiKey: string; + maxTokens: number; + temperature: number; + chatGPTModel: string; + insertionMode: string; + showSidebarIcon: boolean; } -const DEFAULT_SETTINGS: MyPluginSettings = { - mySetting: 'default' +const DEFAULT_SETTINGS: LightweightChatGPTPluginSettings = { + apiKey: '', + maxTokens: 16, + temperature: 1.0, + chatGPTModel: 'gpt-3.5-turbo', + insertionMode: 'end', + showSidebarIcon: true } -export default class MyPlugin extends Plugin { - settings: MyPluginSettings; +export default class LightweightChatGPTPlugin extends Plugin { + settings: LightweightChatGPTPluginSettings; + ribbonIconEl: HTMLElement; async onload() { - await this.loadSettings(); + + try { + await this.loadSettings(); + } catch (error) { + console.error('Error loading settings:', error); + } - // This creates an icon in the left ribbon. - const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => { - // 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.app.workspace.onLayoutReady(() => { + if (this.settings.showSidebarIcon) { + this.addSidebarIcon(); } }); - // 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.addCommand({ + id: 'lightweight-chatgpt-window-hotkey', + name: 'Open Lightweight ChatGPT Plugin Window', + callback: () => { + try { + new LightweightChatGPTWindow(this.app, this.settings.apiKey, this.settings.temperature, this.settings.maxTokens, this.settings.insertionMode).open(); + } catch (error) { + console.error('Error opening Lightweight ChatGPT Plugin Window:', error); } - } - }); + }, + hotkeys: [ + { + modifiers: ['Alt'], + key: 'c', + }, + ], + }); - // This adds a settings tab so the user can configure various aspects of the plugin - this.addSettingTab(new SampleSettingTab(this.app, this)); + // Add a settings tab for user configuration + try { + this.addSettingTab(new LightweightChatGPTSettingTab(this.app, this)); + } catch (error) { + console.error('Error adding settings tab:', error); + } // 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); - }); - + // 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)); + // this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000)); + } + + addSidebarIcon() { + try { + this.ribbonIconEl = this.addRibbonIcon('feather', 'Lightweight ChatGPT Plugin Window', (evt: MouseEvent) => { + try { + new LightweightChatGPTWindow(this.app, this.settings.apiKey, this.settings.temperature, this.settings.maxTokens, this.settings.insertionMode).open(); + } catch (error) { + console.error('Error opening Lightweight ChatGPT Plugin Window:', error); + } + }); + } catch (error) { + console.error('Error adding sidebar icon:', error); + } + + // Perform additional things with the ribbon + this.ribbonIconEl.addClass('lightweight-chatgpt-ribbon-class'); + } + + removeSidebarIcon() { + if (this.ribbonIconEl) { + try { + this.ribbonIconEl.remove(); + } catch (error) { + console.error('Error closing sidebar icon:', error); + } + } } onunload() { @@ -91,47 +110,410 @@ export default class MyPlugin extends Plugin { } } -class SampleModal extends Modal { - constructor(app: App) { + + +class LightweightChatGPTWindow extends Modal { + private inputTextArea: HTMLTextAreaElement; + private outputContainer: HTMLElement; + private maxTokensInput: HTMLInputElement; + private apiKey: string; + private temperature: number; + private maxTokens: number; + private responseAPIText: string; + private insertionMode: string; + + constructor(app: App, apiKey: string, temperature: number, maxTokens: number, insertionMode: string) { super(app); + this.apiKey = apiKey; + this.temperature = temperature; + this.maxTokens = maxTokens; + this.insertionMode = insertionMode; } onOpen() { - const {contentEl} = this; - contentEl.setText('Woah!'); + const { contentEl } = this; + + contentEl.createEl('h2', { text: 'Lightweight ChatGPT Plugin Window' }); + + const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); + const selectedText = activeView ? activeView.editor.getSelection() : ''; + + this.inputTextArea = contentEl.createEl('textarea'); + this.inputTextArea.rows = 4; + this.inputTextArea.style.width = '100%'; + this.inputTextArea.placeholder = 'Enter your text here ...'; + this.inputTextArea.value = selectedText ? `${selectedText}\n====\n` : ''; + + this.inputTextArea.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey) { + event.preventDefault(); + this.insertAtCursor(this.inputTextArea, '\n'); + } else if (event.key === 'Enter' && event.ctrlKey) { + event.preventDefault(); + sendButton.click(); + } + }); + + contentEl.createEl('hr'); + + // Max Tokens + const maxTokensContainer = contentEl.createEl('div'); + maxTokensContainer.style.display = 'flex'; + maxTokensContainer.style.justifyContent = 'space-between'; + maxTokensContainer.style.alignItems = 'center'; + maxTokensContainer.style.marginTop = '1rem'; + + const maxTokensLabelContainer = maxTokensContainer.createEl('div'); + maxTokensLabelContainer.createEl('label', { text: 'Max tokens:' }); + const maxTokensDescription = maxTokensLabelContainer.createEl('p', { text: 'Max OpenAI ChatGpt Tokens' }); + maxTokensDescription.style.fontSize = '0.8rem'; + maxTokensDescription.style.marginTop = '0.25rem'; + maxTokensDescription.style.marginRight = '0.5rem'; + + this.maxTokensInput = maxTokensContainer.createEl('input', { type: 'number' }); + this.maxTokensInput.placeholder = 'Enter max Tokens number'; + this.maxTokensInput.style.width = '40%'; + this.maxTokensInput.style.height = 'calc(1.5em + 1.25em)'; // sum of label and description line heights + this.maxTokensInput.style.textAlign = 'right'; + this.maxTokensInput.min = "1"; + this.maxTokensInput.max = "2048"; + this.maxTokensInput.value = this.maxTokens.toString(); + + // Listener for maxTokensInput input event + this.maxTokensInput.addEventListener('input', () => { + if (parseInt(this.maxTokensInput.value) > parseInt(this.maxTokensInput.max)) { + this.maxTokensInput.value = this.maxTokensInput.max; + new Notice(`Max tokens cannot exceed ${this.maxTokensInput.max}`); + } else if (!parseInt(this.maxTokensInput.value) && parseInt(this.maxTokensInput.value) < parseInt(this.maxTokensInput.min)) { + this.maxTokensInput.value = this.maxTokensInput.min; + new Notice(`Max tokens cannot be less than ${this.maxTokensInput.min}`); + } + }); + + // Send Button + const buttonSendContainer = contentEl.createEl('div'); + buttonSendContainer.style.marginTop = '1rem'; + const sendButton = buttonSendContainer.createEl('button', { + text: 'Send' + }, (el: HTMLButtonElement) => { + el.style.backgroundColor = 'green'; + el.style.color = 'white'; + }); + + const responseDivider = contentEl.createEl('hr'); + responseDivider.style.display = 'none'; + + // Output Container + this.outputContainer = contentEl.createEl('div'); + this.outputContainer.style.whiteSpace = 'pre-wrap'; + this.outputContainer.style.userSelect = 'text'; + + // Add Other Button + const buttonsContainer = contentEl.createEl('div'); + buttonsContainer.style.display = 'flex'; + buttonsContainer.style.marginTop = '1rem'; + const copyToClipboardButton = buttonsContainer.createEl('button', { + text: 'Copy to clipboard' + }, (el: HTMLButtonElement) => { + el.style.backgroundColor = 'green'; + el.style.color = 'white'; + }); + copyToClipboardButton.style.marginRight = '1rem'; + copyToClipboardButton.style.display = 'none'; + const addToPostButton = buttonsContainer.createEl('button', { text: 'Add to current document' }); + addToPostButton.style.marginRight = '1rem'; + addToPostButton.style.display = 'none'; + + // Listener for sendButton click event + sendButton.addEventListener('click', async () => { + if (!parseInt(this.maxTokensInput.value)) { + new Notice(`Use the default value of ${this.maxTokens.toString()} for max Tokens`); + this.maxTokensInput.value = this.maxTokens.toString(); + } + + if (!this.inputTextArea.value) { + new Notice('Please Enter text'); + return; + } + + sendButton.textContent = 'Sending ...'; + sendButton.textContent = 'Waiting for API full response ...'; + copyToClipboardButton.style.display = 'none'; + addToPostButton.style.display = 'none'; + responseDivider.style.display = 'none'; + + try { + this.responseAPIText = await this.sendRequestToChatGPT(); + sendButton.textContent = 'Send'; + copyToClipboardButton.style.display = 'block'; + addToPostButton.style.display = 'block'; + responseDivider.style.display = 'block'; + } catch (error) { + sendButton.textContent = 'Send'; + // new Notice('Error during API request: ' + error.message); + } + }); + + copyToClipboardButton.addEventListener('click', () => { + this.copyToClipboard(this.responseAPIText); + }); + + addToPostButton.addEventListener('click', () => { + this.appendToCurrentNote(this.inputTextArea.value, this.responseAPIText, this.insertionMode); + }); + } + + async sendRequestToChatGPT() { + if (!this.apiKey) { + new Notice('Please enter your API key in the plugin settings.'); + return; + } + this.outputContainer.empty(); + + new Notice('Sending...'); + const apiUrl = 'https://api.openai.com/v1/chat/completions'; + const maxTokens = parseInt(this.maxTokensInput.value); + try { + const response = await fetch(apiUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.apiKey}` + }, + body: JSON.stringify({ + model: 'gpt-3.5-turbo', + max_tokens: maxTokens, + temperature: this.temperature, + messages: [ + { role: 'user', content: this.inputTextArea.value } + ] + }) + }); + + if (response.ok) { + const result = await response.json(); + const gptResponse = result.choices[0].message.content; + + // Display the response in the output container + this.outputContainer.empty(); + this.outputContainer.createEl('p', { text: gptResponse }); + return gptResponse; + } else { + throw new Error(`API request failed with status: ${response.status}`); + } + } catch (error) { + // Handle errors + console.error('Error during API request:', error); + new Notice('Error during API request: ' + error.message); + } + } + + insertAtCursor(textArea: HTMLTextAreaElement, text: string) { + const startPos = textArea.selectionStart; + const endPos = textArea.selectionEnd; + + textArea.value = textArea.value.substring(0, startPos) + text + textArea.value.substring(endPos, textArea.value.length); + textArea.selectionStart = startPos + text.length; + textArea.selectionEnd = startPos + text.length; + } + + async appendToCurrentNote(sentText: string, receivedText: string, insertionMode: string) { + const receivedAPIText = receivedText || ''; + if (receivedAPIText.length <= 0) { + new Notice('No text to add'); + return; + } + + const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); + const activeLeaf = activeView?.leaf; + if (activeView && activeLeaf && activeLeaf.view instanceof MarkdownView) { + const editor = activeLeaf.view.editor; + + // const formattedText = `\n---\n\n${sentText}\n\n${receivedAPIText}\n\n---\n`; + const formattedText = `\n---\n\n${receivedAPIText}\n\n---\n`; + + if (insertionMode === 'end') { + const lastLine = editor.lastLine(); + editor.replaceRange(formattedText, { line: lastLine + 1, ch: 0 }); + } else if (insertionMode === 'current') { + const cursorPosition = editor.getCursor(); + const currentLine = cursorPosition.line; + editor.replaceRange(formattedText, { line: currentLine + 1, ch: 0 }); + } + + } else { + new Notice('Cannot append content to the current view. Please open a markdown note.'); + } + } + + async copyToClipboard(receivedText: string) { + const receivedAPIText = receivedText || ''; + if (receivedAPIText.length > 0) { + navigator.clipboard.writeText(receivedAPIText).then(() => { + new Notice('Copied to clipboard!'); + }).catch((error) => { + console.error('Error copying to clipboard:', error); + new Notice('Error copying to clipboard'); + }); + } else { + new Notice('No text to copy'); + } } onClose() { - const {contentEl} = this; + const { contentEl } = this; contentEl.empty(); } } -class SampleSettingTab extends PluginSettingTab { - plugin: MyPlugin; +class LightweightChatGPTSettingTab extends PluginSettingTab { + plugin: LightweightChatGPTPlugin; - constructor(app: App, plugin: MyPlugin) { + constructor(app: App, plugin: LightweightChatGPTPlugin) { super(app, plugin); this.plugin = plugin; } display(): void { - const {containerEl} = this; + const { containerEl } = this; containerEl.empty(); - containerEl.createEl('h2', {text: 'Settings for my awesome plugin.'}); + containerEl.createEl('h2', { text: 'Settings Lightweight ChatGPT Window' }); new Setting(containerEl) - .setName('Setting #1') - .setDesc('It\'s a secret') + .setName('OpenAI API Key') + .setDesc('Enter your OpenAI API key') .addText(text => text - .setPlaceholder('Enter your secret') - .setValue(this.plugin.settings.mySetting) + .setPlaceholder('Enter your API key') + .setValue(this.plugin.settings.apiKey) .onChange(async (value) => { - console.log('Secret: ' + value); - this.plugin.settings.mySetting = value; + this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); })); + + new Setting(containerEl) + .setName('Default Max Tokens') + .setDesc('Enter the maximum number of tokens for the API response (integer, min: 1, max: 2048)') + .addText(text => text + .setPlaceholder('Enter max tokens') + .setValue(this.plugin.settings.maxTokens.toString()) + .onChange(async (value) => { + let parsedValue = parseInt(value); + if (parsedValue < 1) { + parsedValue = 1; + } else if (parsedValue > 2048) { + parsedValue = 2048; + } + this.plugin.settings.maxTokens = parsedValue; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Temperature') + .setDesc('Enter the temperature value between 0 and 2 (inclusive) for the API response') + .addText(text => text + .setPlaceholder('Enter temperature') + .setValue(this.plugin.settings.temperature.toString()) + .onChange(async (value) => { + let parsedValue = parseFloat(value); + if (parsedValue < 0) { + parsedValue = 0; + } else if (parsedValue > 2) { + parsedValue = 2; + } + this.plugin.settings.temperature = parsedValue ; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('OpenAI Model') + .setDesc('Select the OpenAI model to use') + .addDropdown(dropDown => dropDown + .addOption('gpt-3.5-turbo', 'gpt-3.5-turbo') + .setValue(this.plugin.settings.chatGPTModel) + .onChange(async (value) => { + this.plugin.settings.chatGPTModel = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Insertion Mode') + .setDesc('Choose how to insert text') + .addDropdown(dropdown => dropdown + .addOption('end', 'Insert at end of document') + .addOption('current', 'Insert at current position') + .setValue(this.plugin.settings.insertionMode) + .onChange(async (value) => { + this.plugin.settings.insertionMode = value; + await this.plugin.saveSettings(); + })); + + new Setting(containerEl) + .setName('Show Sidebar Icon') + .setDesc('Toggle to show or hide the sidebar icon') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.showSidebarIcon) + .onChange(async (value) => { + this.plugin.settings.showSidebarIcon = value; + await this.plugin.saveSettings(); + if (value) { + this.plugin.addSidebarIcon(); + } else { + this.plugin.removeSidebarIcon(); + } + })); + + const politeMessage = containerEl.createEl('p', { + cls: 'polite-message', + }); + politeMessage.textContent = 'If you enjoy this plugin or would like to show your support, please consider giving it a free star on GitHub~ Your appreciation means a lot to me!'; + // politeMessage.style.textAlign = 'center'; + politeMessage.style.marginBottom = '1rem'; + politeMessage.style.fontStyle = 'italic'; + + const githubLink = containerEl.createEl('div', { + cls: 'github-link-container', + }); + const githubAnchor = githubLink.createEl('a', { + cls: 'github-link', + }); + githubAnchor.href = 'https://github.com/ittuann/obsidian-lightweight-chatgpt-plugin'; + githubAnchor.target = '_blank'; + githubAnchor.rel = 'noopener'; + // const githubLogo = githubAnchor.createEl('img', { + // cls: 'github-logo', + // }); + // githubLogo.src = 'https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png'; + // githubLogo.alt = 'GitHub'; + // githubLogo.style.width = '24px'; + // githubLogo.style.height = '24px'; + // githubLogo.style.verticalAlign = 'middle'; + // githubLogo.style.marginRight = '4px'; + githubAnchor.createEl('span', { + text: 'View on GitHub', + }); + const style = document.createElement('style'); + style.innerHTML = ` + .github-link-container { + margin-top: 2rem; + text-align: center; + } + .github-link { + color: #0366d6; + text-decoration: none; + border: 1px solid #0366d6; + border-radius: 4px; + padding: 0.5rem 1rem; + font-weight: bold; + transition: all 0.3s; + } + .github-link:hover { + background-color: #0366d6; + color: white; + text-decoration: none; + } + `; + containerEl.appendChild(style); } } diff --git a/manifest.json b/manifest.json index 0897aff..d2b8cb5 100644 --- a/manifest.json +++ b/manifest.json @@ -1,11 +1,11 @@ { - "id": "obsidian-sample-plugin", - "name": "Sample Plugin", + "id": "lightweight-chatgpt-plugin", + "name": "Lightweight ChatGPT Plugin", "version": "1.0.0", "minAppVersion": "0.15.0", - "description": "This is a sample plugin for Obsidian. This plugin demonstrates some of the capabilities of the Obsidian API.", - "author": "Obsidian", - "authorUrl": "https://obsidian.md", - "fundingUrl": "https://obsidian.md/pricing", + "description": "Experience OpenAI ChatGPT assistance directly within Obsidian, drafting content without interrupting your creative flow.", + "author": "ittuann", + "authorUrl": "https://github.com/ittuann", + "fundingUrl": "https://github.com/ittuann/obsidian-lightweight-chatgpt-plugin", "isDesktopOnly": false } diff --git a/package.json b/package.json index 6a00766..c157822 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,16 @@ { - "name": "obsidian-sample-plugin", + "name": "lightweight-chatgpt-plugin", "version": "1.0.0", - "description": "This is a sample plugin for Obsidian (https://obsidian.md)", + "description": "Experience OpenAI ChatGPT assistance directly within Obsidian, drafting content without interrupting your creative flow.", "main": "main.js", "scripts": { "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", - "version": "node version-bump.mjs && git add manifest.json versions.json" + "version": "node version-bump.mjs && git add manifest.json versions.json", + "lint": "eslint ." }, "keywords": [], - "author": "", + "author": "ittuann", "license": "MIT", "devDependencies": { "@types/node": "^16.11.6", @@ -19,6 +20,7 @@ "esbuild": "0.17.3", "obsidian": "latest", "tslib": "2.4.0", - "typescript": "4.7.4" + "typescript": "4.7.4", + "eslint": "latest" } } diff --git a/styles.css b/styles.css index 71cc60f..27330be 100644 --- a/styles.css +++ b/styles.css @@ -3,6 +3,4 @@ This CSS file will be included with your plugin, and available in the app when your plugin is enabled. -If your plugin does not need CSS, delete this file. - */